TableController.php 15 KB

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