TableController.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  1. <?php
  2. /*
  3. Desarrollador: Ing. Jean Jairo Benitez Meza
  4. Ultima Modificación: 11/04/2023
  5. Módulo: Formularios Dinámicos
  6. */
  7. namespace App\Http\Controllers;
  8. use App\Http\Controllers\Controller;
  9. use App\Http\Controllers\ResponseController;
  10. use App\Http\Controllers\EncryptionController;
  11. use Illuminate\Http\Request;
  12. use Illuminate\Support\Carbon;
  13. use Illuminate\Support\Facades\DB;
  14. use Illuminate\Support\Facades\Validator;
  15. class TableController extends Controller
  16. {
  17. private $responseController;
  18. private $encController;
  19. public function __construct(){
  20. $this->responseController = new ResponseController();
  21. $this->encController = new EncryptionController();
  22. }
  23. public function getTables($line){
  24. try {
  25. $data = DB::table('S002V01TTABL')
  26. ->where('TABL_NULI', '=', $line)
  27. ->get([
  28. 'TABL_IDTA AS CODIGO_TABLA',
  29. 'TABL_NOMB AS NOMBRE_TABLA',
  30. 'TABL_FERE AS FECHA_REGISTRA',
  31. 'TABL_FEMO AS FECHA_MODIFICA',
  32. 'TABL_USRE AS USUARIO_REGISTRA',
  33. 'TABL_USMO AS USUARIO_MODIFICA',
  34. 'TABL_ESTA AS ESTADO'
  35. ]);
  36. }catch (\Exception $e){
  37. return $this->responseController->makeResponse(true, "ERR_TABLE_GET000: Ocurrió un error al consultar los datos.", [], 500);
  38. }
  39. return $this->responseController->makeResponse(false, "ÉXITO", $data);
  40. }
  41. public function getColumnsByTables(Request $request){
  42. $validator = Validator::make($request->all(), [
  43. 'tables' => 'required|array',
  44. ]);
  45. if ($validator->fails()) {
  46. return $this->responseController->makeResponse(
  47. true,
  48. "ERR_TABLE_GET000: Se encontraron uno o más errores.",
  49. $this->responseController->makeErrors($validator->errors()->messages()),
  50. 401
  51. );
  52. }
  53. try {
  54. $form = $request->all();
  55. $resp = array();
  56. foreach ($form['tables'] as $table) {
  57. $data = array();
  58. $data['table'] = $table;
  59. $data['columns'] = [];
  60. $column_response = $this->getColumns(strtolower( $table));
  61. if ( $column_response['error']) return $this->responseController->makeResponse(false, $column_response['msg']);
  62. $columns = $column_response['response'];
  63. foreach ($columns as $column) {
  64. $nameColumn = explode('_', $column->COLUMN_NAME)[1];
  65. if ($nameColumn !== 'INEX'){
  66. $data['columns'][] = $column->COLUMN_NAME;
  67. }
  68. }
  69. $resp[] = $data;
  70. }
  71. } catch (\Throwable $th) {
  72. return $this->responseController->makeResponse(true, "ERR_TABLE_GET000: Ocurrió un error al consultar los datos.", [], 500);
  73. }
  74. return $this->responseController->makeResponse(false, "ÉXITO", $resp);
  75. }
  76. public function getColumnsExtra(Request $request) {
  77. $validator = Validator::make($request->all(), [
  78. 'numberForm' => 'required|integer',
  79. 'tables' => 'required|array',
  80. ]);
  81. if ($validator->fails()) {
  82. return $this->responseController->makeResponse(
  83. true,
  84. "Se encontraron uno o más errores.",
  85. $this->responseController->makeErrors($validator->errors()->messages()),
  86. 401
  87. );
  88. }
  89. $form = $request->all();
  90. $data = array();
  91. $data['table'] = 'NA';
  92. $data['type'] = 'JSON';
  93. $getColumnsExtra = DB::table('S002V01TFODI')->where('FODI_NUFO', '=', $form['numberForm'])->first('FODI_DAFO');
  94. $arrFields = json_decode($getColumnsExtra->FODI_DAFO);
  95. foreach ($arrFields->fields as $keyFields => $fields) {
  96. foreach ($fields->form as $keyForm => $form) {
  97. if ($form->data_table->table == 'NA') {
  98. $data['columns'][] = $form->data_table->column;
  99. }
  100. }
  101. }
  102. return $this->responseController->makeResponse(false, "ÉXITO", $data);
  103. }
  104. public function createTable(Request $request){
  105. $validator = Validator::make($request->all(), [
  106. 'table_name' => 'required|string',
  107. 'user' => 'required|string'
  108. ]);
  109. if ($validator->fails()) {
  110. return $this->responseController->makeResponse(
  111. true,
  112. "ERR_TABLE_REG000: Se encontraron uno o más errores.",
  113. $this->responseController->makeErrors($validator->errors()->messages()),
  114. 401
  115. );
  116. }
  117. DB::beginTransaction();
  118. $request_form = $request->all();
  119. $table_name = $this->encController->decrypt($request_form['table_name']);
  120. try {
  121. $user = $this->encController->decrypt($request_form['user']);
  122. } catch (\Throwable $th) {
  123. DB::rollBack();
  124. return $this->responseController->makeResponse(true, "ERR_TABLE_REG001: No se pudo obtener el usuario.", [], 500);
  125. }
  126. $reg = [
  127. "TABL_NULI" => 1,
  128. "TABL_NOMB" => $table_name,
  129. "TABL_USRE" => $user,
  130. "TABL_FERE" => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
  131. "TABL_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  132. ];
  133. try {
  134. $validateInsert = DB::table('S002V01TTABL')->insert($reg);
  135. if (!$validateInsert) {
  136. return $this->responseController->makeResponse(true, "ERR_TABLE_REG002: No se pudo realizar la inserción en la base.", [], 500);
  137. }
  138. }catch (\PDOException $e){
  139. if($e->getCode() == 23000){
  140. DB::rollBack();
  141. return $this->responseController->makeResponse(true, "ERR_TABLE_REG003: La tabla ya ha sido registrada anteriormente.", [], 500);
  142. }else{
  143. DB::rollBack();
  144. return $this->responseController->makeResponse(true, "ERR_TABLE_REG004: Ocurrió un error al consultar los datos.", [], 500);
  145. }
  146. } catch (\Throwable $th) {
  147. DB::rollBack();
  148. return $this->responseController->makeResponse(true, "ERR_TABLE_REG005: Ocurrió un error al consultar los datos.", [], 500);
  149. }
  150. DB::commit();
  151. return $this->responseController->makeResponse(false, "ÉXITO: Registro correcto");
  152. }
  153. public function updateTable(Request $request){
  154. $validator = Validator::make($request->all(), [
  155. 'table_code' => 'required|string',
  156. 'table_name' => 'required|string',
  157. 'user' => 'required|string'
  158. ]);
  159. if ($validator->fails()) {
  160. return $this->responseController->makeResponse(
  161. true,
  162. "ERR_TABLE_UPD000: Se encontraron uno o más errores.",
  163. $this->responseController->makeErrors($validator->errors()->messages()),
  164. 401
  165. );
  166. }
  167. DB::beginTransaction();
  168. $request_form = $request->all();
  169. $table_name = $this->encController->decrypt($request_form['table_name']);
  170. try {
  171. $user = $this->encController->decrypt($request_form['user']);
  172. } catch (\Throwable $th) {
  173. DB::rollBack();
  174. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD001: No se pudo obtener el usuario.", [], 500);
  175. }
  176. try {
  177. $data_table = DB::table('S002V01TTABL')->where('TABL_IDTA', '=', $request_form['table_code'])->first();
  178. } catch (\Throwable $th) {
  179. DB::rollBack();
  180. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD002: Ocurrió un error al obtener los datos de la base.", [], 500);
  181. }
  182. if (empty($data_table)) {
  183. DB::rollBack();
  184. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD003: El nombre de la tabla no existe.", [], 500);
  185. }
  186. $upd = [
  187. "TABL_NOMB" => $table_name,
  188. "TABL_USMO" => $user,
  189. "TABL_FEMO" => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
  190. "TABL_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  191. ];
  192. try{
  193. $validateUpdate = DB::table('S002V01TTABL')->where('TABL_IDTA', '=', $request_form['table_code'])->update($upd);
  194. if (!$validateUpdate) {
  195. DB::rollBack();
  196. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD004: No se pudo realizar la inserción en la base.", [], 500);
  197. }
  198. }catch (\PDOException $e){
  199. if($e->getCode() == 23000){
  200. DB::rollBack();
  201. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD005: La tabla ya ha sido registrada anteriormente.", [], 500);
  202. }else{
  203. DB::rollBack();
  204. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD006: Ocurrió un error al consultar los datos.", [], 500);
  205. }
  206. } catch (\Throwable $th) {
  207. DB::rollBack();
  208. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD007: Ocurrió un error al consultar los datos.", [], 500);
  209. }
  210. DB::commit();
  211. return $this->responseController->makeResponse(false, "ÉXITO: Modificación correcta");
  212. }
  213. public function updateStateTables(Request $request){
  214. $validator = Validator::make($request->all(), [
  215. 'table_name' => 'required|string',
  216. 'state' => 'required|string',
  217. 'user' => 'required|string'
  218. ]);
  219. if ($validator->fails()) {
  220. return $this->responseController->makeResponse(
  221. true,
  222. "ERR_TABLE_UPD000: Se encontraron uno o más errores.",
  223. $this->responseController->makeErrors($validator->errors()->messages()),
  224. 401
  225. );
  226. }
  227. DB::beginTransaction();
  228. $form = $request->all();
  229. try{
  230. $valid_tb = DB::table('S002V01TTABL')
  231. ->where('TABL_NOMB', $form['table_name'])
  232. ->first();
  233. } catch (\Throwable $th) {
  234. DB::rollBack();
  235. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD001: Ocurrió un error al hacer la consulta en la base.", [], 500);
  236. }
  237. if (empty($valid_tb)) {
  238. DB::rollBack();
  239. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD002: El nombre de la tabla ".$form['table_name']." no existe.", [], 500);
  240. }
  241. try {
  242. $user = $this->encController->decrypt($form['user']);
  243. } catch (\Throwable $th) {
  244. DB::rollBack();
  245. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD003: No se pudo obtener el usuario.", [], 500);
  246. }
  247. $upd = [
  248. "TABL_ESTA" => "",
  249. "TABL_USMO" => $user,
  250. "TABL_FEMO" => Carbon::now()->timezone('America/Mazatlan')->toDateTimeString(),
  251. "TABL_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  252. ];
  253. switch ($form['state']){
  254. case "delete":
  255. $upd["TABL_ESTA"] = "Eliminado";
  256. break;
  257. case "active":
  258. $upd["TABL_ESTA"] = "Activo";
  259. break;
  260. default:
  261. DB::rollBack();
  262. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD004: No ha elegido una opción correcta para cambiar el estado", [], 500);
  263. }
  264. try{
  265. $validateUpdate = DB::table('S002V01TTABL')->where('TABL_NOMB', $form['table_name'])->update($upd);
  266. if (!$validateUpdate) {
  267. DB::rollBack();
  268. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD005: No se pudo realizar la modificación en la base.", [], 500);
  269. }
  270. }catch (\PDOException $e){
  271. if($e->getCode() == 23000){
  272. DB::rollBack();
  273. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD005: La tabla ya ha sido registrada anteriormente.", [], 500);
  274. }else{
  275. DB::rollBack();
  276. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD006: Ocurrió un error al consultar los datos.", [], 500);
  277. }
  278. } catch (\Throwable $th) {
  279. DB::rollBack();
  280. return $this->responseController->makeResponse(true, "ERR_TABLE_UPD007: Ocurrió un error al consultar los datos.", [], 500);
  281. }
  282. DB::commit();
  283. return $this->responseController->makeResponse(false, "ÉXITO: Modificación correcta");
  284. }
  285. /* --------------------------------------- FUNCIONES ---------------------------------------------- */
  286. private function getColumns($table_name){
  287. $tables_name = $this->getTablesName();
  288. if ( $tables_name['error']) {
  289. return $tables_name;
  290. }
  291. $tables = $tables_name['response'];
  292. $valid_table = false;
  293. foreach ($tables as $table) {
  294. if ($table->TABLE_NAME == $table_name){
  295. $valid_table = true;
  296. break;
  297. }
  298. }
  299. if (!$valid_table) {
  300. return ["error" => true, "msg" => "ERR_DYNTABLE_REG000: No se encontró la tabla en la base de datos."];
  301. }
  302. $databaseName = DB::connection()->getDatabaseName();
  303. $qry = "SELECT COLUMN_NAME FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA = '".$databaseName."' AND TABLE_NAME = '".$table_name."'";
  304. try{
  305. $data_columns = DB::select($qry);
  306. }catch (\Exception $e){
  307. return ["error" => true, "msg" => "ERR_DYNTABLE_REG000: No se pudo realizar la consulta a la base."];
  308. }
  309. return ["error" => false, "msg" => "ÉXITO", "response" => $data_columns];
  310. }
  311. private function getTablesName(){
  312. $databaseName = DB::connection()->getDatabaseName();
  313. try{
  314. $resp = DB::select('SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_SCHEMA="'.$databaseName.'"');
  315. }catch (\Exception $e){
  316. return ["error" => true, "msg" => "ERR_DYNTABLE_REG000: Ocurrió un error al obtener el nombre de las tablas."];
  317. }
  318. if ( count((array)$resp) == 0) {
  319. return ["error" => true, "msg" => "ERR_DYNTABLE_REG000: No se pudo obtener el nombre de las tablas."];
  320. }
  321. return ["error" => false, "msg" => "ÉXITO", "response" => $resp];
  322. }
  323. }