TableController.php 16 KB

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