TableController.php 16 KB

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