EmployeeController.php 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687
  1. <?php
  2. /*
  3. Nombre del programador: Cordourier Rojas Mathew
  4. Ultima fecha de modificación: [ 24 / Marzo / 2023 ]
  5. Descripción: Controlador del submodulo Personal. Perteneciente al Módulo 13 - Gestion del Personal de Mantenimiento
  6. */
  7. namespace App\Http\Controllers;
  8. use Carbon\Carbon;
  9. use Illuminate\Http\Request;
  10. use Illuminate\Support\Facades\DB;
  11. use Illuminate\Support\Facades\Storage;
  12. use Illuminate\Support\Facades\Validator;
  13. use PhpOffice\PhpSpreadsheet\IOFactory;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use stdClass;
  16. use Throwable;
  17. class EmployeeController extends Controller
  18. {
  19. private $response_controller;
  20. private $encrypt_controller;
  21. private $documents_controller;
  22. public function __construct()
  23. {
  24. $this->response_controller = new ResponseController();
  25. $this->encrypt_controller = new EncryptionController();
  26. $this->documents_controller = new DocumentsController();
  27. }
  28. // Metodo para obtener datos del personal
  29. public function getConsultOfEmployees($line_number)
  30. {
  31. try {
  32. $employees = DB::table('S002V01TPERS')
  33. ->select(
  34. 'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
  35. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as NAME'),
  36. 'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
  37. 'S002V01TPERS.PERS_ESPE as SPECIALITY',
  38. 'S002V01TPERS.PERS_FERE as REGISTER_DATE',
  39. 'S002V01TPERS.PERS_USRE as REGISTERED_BY_USER',
  40. 'S002V01TPERS.PERS_FEMO as UPDATE_DATE',
  41. 'S002V01TPERS.PERS_USMO as UPDATED_BY_USER',
  42. 'S002V01TPERS.PERS_ESTA as STATUS'
  43. )
  44. // ->where('S002V01TPERS.PERS_ESTA', '=', 'Activo')
  45. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  46. ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
  47. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  48. ->get();
  49. // Verifica si el objeto esta vacio
  50. if (!isset($employees[0]) && empty($employees[0])) {
  51. return $this->response_controller
  52. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontraron datos', $employees, 500);
  53. }
  54. $users = DB::table('S002V01TUSUA')
  55. ->select('USUA_IDUS as ID', DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'))
  56. ->where('USUA_NULI', '=', $line_number)
  57. ->get();
  58. // Verifica si el objeto esta vacio
  59. if (!isset($users[0]) && empty($users[0])) {
  60. return $this->response_controller
  61. ->makeResponse(TRUE, 'ERR_USUARIO_REG002: No se encontraron datos', $users, 500);
  62. }
  63. $workteams = DB::table('S002V01TEQMA')
  64. ->select('S002V01TEQMA.EQMA_NOMB as NAME', 'S002V01TPEEM.PEEM_IDPE as ID_EMPLOYEE')
  65. ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
  66. ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
  67. ->join('S002V01TPEEM', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TPEEM.PEEM_IDEM')
  68. ->get();
  69. // Verifica si el objeto esta vacio
  70. if (!isset($workteams[0]) && empty($workteams[0])) {
  71. return $this->response_controller
  72. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: No se encontraron datos', $workteams, 500);
  73. }
  74. foreach ($employees as $employee) {
  75. // Introduce los equipos de trabajo a los que pertenece
  76. foreach ($workteams as $workteam) {
  77. if ($employee->ID_EMPLOYEE == $workteam->ID_EMPLOYEE) {
  78. $employee->WORKTEAMS = $workteam->NAME;
  79. }
  80. }
  81. // Introduce la persona que lo registro
  82. foreach ($users as $user) {
  83. if ($employee->REGISTERED_BY_USER == $user->ID) {
  84. $employee->REGISTERED_BY_USER = $user->NAME;
  85. }
  86. // Si hubo actualización, introduce a la persona que lo actualizo
  87. if ($employee->UPDATED_BY_USER != null) {
  88. if ($employee->UPDATED_BY_USER == $user->ID) {
  89. $employee->UPDATED_BY_USER = $user->NAME;
  90. }
  91. }
  92. }
  93. // Introduce la fecha en que se registro y actualizo al empleado (si hubo actualización)
  94. $employee->REGISTER_DATE = Carbon::create($employee->REGISTER_DATE)->format("d-m-Y h:i:s A");
  95. if ($employee->UPDATE_DATE != null) {
  96. $employee->UPDATE_DATE = Carbon::create($employee->UPDATE_DATE)->format("d-m-Y h:i:s A");
  97. }
  98. }
  99. return $this->response_controller
  100. ->makeResponse(FALSE, "Consulta exitosa", $employees);
  101. } catch (Throwable $th) {
  102. return $this->response_controller
  103. ->makeResponse(TRUE, 'ERR_PERSONAL_REG004: Error inesperado', strtoupper($th->getMessage()), 500);
  104. }
  105. }
  106. // Metodo para ver el listado de documentos de un empleado
  107. public function getDocumentsByEmployee($id_employee, $line_number)
  108. {
  109. try {
  110. // Busca si existe el empleado
  111. $employee_found = DB::table('S002V01TPERS')
  112. ->select('PERS_IDPE')
  113. ->where('PERS_IDPE', '=', $id_employee)
  114. ->where('PERS_NULI', '=', $line_number)
  115. ->first();
  116. // Verifica si el objeto esta vacio
  117. if (!isset($employee_found) && empty($employee_found)) {
  118. return $this->response_controller
  119. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  120. }
  121. // Busca si el empleado tiene documentos
  122. $documents_by_employee = DB::table('S002V01TDOCU_P')
  123. ->select('DOCU_LIDO as DOCUMENT_LINK')
  124. ->where('DOCU_IDPE', '=', $id_employee)
  125. ->where('DOCU_NULI', '=', $line_number)
  126. ->get();
  127. // Verifica si el objeto esta vacio
  128. if (!isset($documents_by_employee[0]) && empty($documents_by_employee[0])) {
  129. return $this->response_controller
  130. ->makeResponse(FALSE, 'El empleado no tiene documentos', []);
  131. }
  132. // Encripta la liga de cada documento
  133. foreach ($documents_by_employee as $doc) {
  134. $doc->DOCUMENT_NAME = $doc->DOCUMENT_LINK;
  135. $doc->DOCUMENT_LINK = Storage::disk('pdf')->url($doc->DOCUMENT_LINK);
  136. $doc->DOCUMENT_LINK = $this->encrypt_controller->encrypt($doc->DOCUMENT_LINK);
  137. }
  138. return $this->response_controller
  139. ->makeResponse(FALSE, "Consulta exitosa", $documents_by_employee);
  140. } catch (Throwable $th) {
  141. return $this->response_controller
  142. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
  143. }
  144. }
  145. public function getLastDocumentsByEmployee($id_employee, $line_number)
  146. {
  147. try {
  148. // Busca si existe el empleado
  149. $employee_found = DB::table('S002V01TPERS')
  150. ->select('PERS_IDPE')
  151. ->where('PERS_IDPE', '=', $id_employee)
  152. ->where('PERS_NULI', '=', $line_number)
  153. ->first();
  154. // Verifica si el objeto esta vacio
  155. if (!isset($employee_found) && empty($employee_found)) {
  156. return $this->response_controller
  157. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  158. }
  159. // Busca si el empleado tiene documentos
  160. $documents_by_employee = DB::table('S002V01TDOCU_P')
  161. ->select('DOCU_LIDO as DOCUMENT_LINK', 'DOCU_NUSE as SEQUENCE')
  162. ->where('DOCU_IDPE', '=', $id_employee)
  163. ->where('DOCU_NULI', '=', $line_number)
  164. ->get();
  165. // Busca los numeros de secuencia
  166. $documents_sequence = DB::table('S002V01TDOCU_P')
  167. ->select('DOCU_NUSE as SEQUENCE')
  168. ->where('DOCU_IDPE', '=', $id_employee)
  169. ->where('DOCU_NULI', '=', $line_number)
  170. ->groupBy('DOCU_NUSE')
  171. ->get();
  172. $test = [];
  173. for ($i = 0; $i < sizeof($documents_sequence); $i++) {
  174. foreach ($documents_by_employee as $doc) {
  175. if ($doc->SEQUENCE == $documents_sequence[$i]->SEQUENCE) {
  176. if (isset($test[$i]) && !empty($test[$i])) {
  177. if (substr($doc->DOCUMENT_LINK, 25, 2) > substr($test[$i], 25, 2)) {
  178. $test[$i] = $doc->DOCUMENT_LINK;
  179. }
  180. } else {
  181. $test[$i] = $doc->DOCUMENT_LINK;
  182. }
  183. }
  184. }
  185. }
  186. return $this->response_controller
  187. ->makeResponse(FALSE, "Consulta exitosa", $test);
  188. } catch (Throwable $th) {
  189. return $this->response_controller
  190. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
  191. }
  192. }
  193. // Metodo para obtener todas las intervenciones relacionadas a un empleado
  194. public function getInterventionsByEmployee($id_employee, $line_number)
  195. {
  196. try {
  197. // Verifica si el empleado existe
  198. $employee_exist = DB::table('S002V01TPERS')
  199. ->select('PERS_IDPE')
  200. ->where('PERS_IDPE', '=', $id_employee)
  201. ->where('PERS_NULI', '=', $line_number)
  202. ->first();
  203. // Verifica si el objeto esta vacio
  204. if (!isset($employee_exist) && empty($employee_exist)) {
  205. return $this->response_controller
  206. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  207. }
  208. // Obtiene las intervenciones del empleado
  209. $employee_interventions = DB::table('S002V01TPERS')
  210. ->select(
  211. 'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
  212. 'S002V01TINTE_P.INTE_NOMB as INTERVENTION_NAME',
  213. 'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
  214. 'S002V01TINTE_P.INTE_IDIN as INTERVENTION_ID',
  215. 'S002V01TINTE_P.INTE_DESC as INTERVENTION_DESCRIPTION',
  216. )
  217. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  218. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  219. ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
  220. ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
  221. ->where('S002V01TEMIN.EMIN_NULI', '=', $line_number)
  222. ->where('S002V01TINTE_P.INTE_NULI', '=', $line_number)
  223. ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
  224. ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
  225. ->join('S002V01TEMIN', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TEMIN.EMIN_IDEM')
  226. ->join('S002V01TINTE_P', 'S002V01TEMIN.EMIN_IDIN', '=', 'S002V01TINTE_P.INTE_IDIN')
  227. ->get();
  228. // Verifica si el objeto esta vacio
  229. if (!isset($employee_interventions[0]) && empty($employee_interventions[0])) {
  230. return $this->response_controller
  231. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: El empleado no tiene intervenciones', [], 500);
  232. }
  233. return $this->response_controller
  234. ->makeResponse(FALSE, "Consulta exitosa", $employee_interventions);
  235. } catch (Throwable $th) {
  236. return $this->response_controller
  237. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
  238. }
  239. }
  240. // Metodo para la eliminación logica de un empleado
  241. public function updateToInactiveStatus(Request $request, $id_employee)
  242. {
  243. try {
  244. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  245. $validator = Validator::make($request->all(), [
  246. "SAVED_BY_USER" => ['required', 'digits:10']
  247. ]);
  248. if ($validator->fails()) {
  249. return $this->response_controller->makeResponse(
  250. TRUE,
  251. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  252. $this->response_controller->makeErrors($validator->errors()->messages()),
  253. 400
  254. );
  255. }
  256. // Busca si el empleado existe
  257. $search_employee = DB::table("S002V01TPERS")
  258. ->select("PERS_IDPE")
  259. ->where("PERS_IDPE", "=", $id_employee)
  260. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  261. ->first();
  262. // Verifica si el objeto esta vacio
  263. if (!isset($search_employee) && empty($search_employee)) {
  264. return $this->response_controller
  265. ->makeResponse(TRUE, "ERR_PERSONAL_REG002: No se encontró al empleado", $search_employee, 500);
  266. }
  267. $user_register = DB::table('S002V01TUSUA')
  268. ->select('USUA_IDUS as ID_USER')
  269. ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
  270. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  271. ->first();
  272. // Verifica si el objeto esta vacio
  273. if (!isset($user_register) && empty($user_register)) {
  274. return $this->response_controller
  275. ->makeResponse(TRUE, "ERR_USUARIO_REG003: Tu usuario no es válido para eliminar empleados", [], 500);
  276. }
  277. // Busca si el empleado tiene intervenciones activas
  278. $search_employee = DB::table("S002V01TPERS")
  279. ->select("S002V01TINTE_P.INTE_NOMB")
  280. ->where("S002V01TPERS.PERS_IDPE", "=", $id_employee)
  281. ->where("S002V01TINTE_P.INTE_ESTA", "=", "Activo")
  282. ->where("S002V01TEMIN.EMIN_ESTA", "=", "Activo")
  283. ->where("S002V01TPERS.PERS_NULI", "=", $request->LINE_NUMBER)
  284. ->where('S002V01TPEEM.PEEM_NULI', '=', $request->LINE_NUMBER)
  285. ->where('S002V01TEQMA.EQMA_NULI', '=', $request->LINE_NUMBER)
  286. ->where('S002V01TEMIN.EMIN_NULI', '=', $request->LINE_NUMBER)
  287. ->where('S002V01TINTE_P.INTE_NULI', '=', $request->LINE_NUMBER)
  288. ->groupBy('S002V01TINTE_P.INTE_NOMB')
  289. ->join("S002V01TPEEM", "S002V01TPERS.PERS_IDPE", "=", "S002V01TPEEM.PEEM_IDPE")
  290. ->join("S002V01TEQMA", "S002V01TPEEM.PEEM_IDEM", "=", "S002V01TEQMA.EQMA_IDEQ")
  291. ->join("S002V01TEMIN", "S002V01TEQMA.EQMA_IDEQ", "=", "S002V01TEMIN.EMIN_IDEM")
  292. ->join("S002V01TINTE_P", "S002V01TEMIN.EMIN_IDIN", "=", "S002V01TINTE_P.INTE_IDIN")
  293. ->get();
  294. // Verifica si el objeto contiene algo
  295. if (isset($search_employee[0]) && !empty($search_employee[0])) {
  296. return $this->response_controller
  297. ->makeResponse(TRUE, "ERR_PERSONAL_REG004: Empleado ocupado con intervenciones", $search_employee, 500);
  298. } else {
  299. DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
  300. $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  301. $delete_employee = DB::table('S002V01TPERS')
  302. ->where('PERS_IDPE', $id_employee)
  303. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  304. ->update([
  305. "PERS_ESTA" => "Eliminado",
  306. "PERS_USMO" => trim($request->SAVED_BY_USER),
  307. "PERS_FEMO" => $UPDATE_DATE,
  308. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  309. ]);
  310. // Verifica que la actualización fuera exitosa
  311. if ($delete_employee < 1) {
  312. return $this->response_controller
  313. ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error eliminando al empleado', [], 500);
  314. }
  315. $delete_employee = DB::table('S002V01TPEEM')
  316. ->where('PEEM_IDPE', $id_employee)
  317. ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
  318. ->update([
  319. "PEEM_ESTA" => "Eliminado",
  320. "PEEM_USMO" => trim($request->SAVED_BY_USER),
  321. "PEEM_FEMO" => $UPDATE_DATE,
  322. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  323. ]);
  324. // Verifica que la actualización fuera exitosa
  325. if ($delete_employee < 1) {
  326. DB::rollBack(); # Si no se logra eliminar al empleado en el equipo, se revierten los cambios previos
  327. return $this->response_controller
  328. ->makeResponse(TRUE, 'ERR_PERSONAL_REG006: Algo salió mal, error eliminando al empleado del equipo', [], 500);
  329. }
  330. }
  331. DB::commit(); # Para guardar los cambios en la base de datos
  332. return $this->response_controller->makeResponse(FALSE, "Eliminado exitoso");
  333. } catch (Throwable $th) {
  334. return $this->response_controller
  335. ->makeResponse(TRUE, 'ERR_PERSONAL_REG007: Error inesperado', strtoupper($th->getMessage()), 500);
  336. }
  337. }
  338. // Metodo para la activación logica de un empleado
  339. public function updateToActiveStatus(Request $request, $id_employee)
  340. {
  341. try {
  342. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  343. $validator = Validator::make($request->all(), [
  344. "SAVED_BY_USER" => ['required', 'digits:10']
  345. ]);
  346. if ($validator->fails()) {
  347. return $this->response_controller->makeResponse(
  348. TRUE,
  349. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  350. $this->response_controller->makeErrors($validator->errors()->messages()),
  351. 400
  352. );
  353. }
  354. // Busca si el empleado existe
  355. $search_employee = DB::table("S002V01TPERS")
  356. ->select("PERS_IDPE")
  357. ->where("PERS_IDPE", "=", $id_employee)
  358. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  359. ->first();
  360. // Verifica si el objeto esta vacio
  361. if (!isset($search_employee) && empty($search_employee)) {
  362. return $this->response_controller
  363. ->makeResponse(TRUE, "ERR_PERSONAL_REG002: No se encontró al empleado", $search_employee, 500);
  364. }
  365. $user_register = DB::table('S002V01TUSUA')
  366. ->select('USUA_IDUS as ID_USER')
  367. ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
  368. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  369. ->first();
  370. // Verifica si el objeto esta vacio
  371. if (!isset($user_register) && empty($user_register)) {
  372. return $this->response_controller
  373. ->makeResponse(TRUE, "ERR_USUARIO_REG003: Tu usuario no es válido para activar empleados", [], 500);
  374. }
  375. DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
  376. $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  377. $activate_employee = DB::table('S002V01TPERS')
  378. ->where('PERS_IDPE', $id_employee)
  379. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  380. ->update([
  381. "PERS_ESTA" => "Activo",
  382. "PERS_USMO" => trim($request->SAVED_BY_USER),
  383. "PERS_FEMO" => $UPDATE_DATE,
  384. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  385. ]);
  386. // Verifica que la actualización fuera exitosa
  387. if ($activate_employee < 1) {
  388. return $this->response_controller
  389. ->makeResponse(TRUE, 'ERR_PERSONAL_REG004: Algo salió mal, error activando al empleado', [], 500);
  390. }
  391. $activate_employee = DB::table('S002V01TPEEM')
  392. ->where('PEEM_IDPE', $id_employee)
  393. ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
  394. ->update([
  395. "PEEM_ESTA" => "Activo",
  396. "PEEM_USMO" => trim($request->SAVED_BY_USER),
  397. "PEEM_FEMO" => $UPDATE_DATE,
  398. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  399. ]);
  400. // Verifica que la actualización fuera exitosa
  401. if ($activate_employee < 1) {
  402. DB::rollBack(); # Si no se logra eliminar al empleado en el equipo, se revierten los cambios previos
  403. return $this->response_controller
  404. ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error activando al empleado del equipo', [], 500);
  405. }
  406. DB::commit(); # Para guardar los cambios en la base de datos
  407. return $this->response_controller->makeResponse(FALSE, "Activación exitosa");
  408. } catch (Throwable $th) {
  409. return $this->response_controller->
  410. makeResponse(TRUE, 'ERR_PERSONAL_REG006: Error inesperado', strtoupper($th->getMessage()), 500);
  411. }
  412. }
  413. // Metodo para obtener a los usuarios que no son empleados y el enviado por path
  414. public function getAvaibleUsers($id_employee, $line_number)
  415. {
  416. try {
  417. // Busca en la base si existe otro empleado con ese usuario
  418. $users = DB::table('S002V01TUSUA')
  419. ->select(
  420. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  421. "USUA_IDUS as ID_USER"
  422. )
  423. ->orderBy('NAME', 'asc')
  424. ->where('USUA_NULI', '=', $line_number)
  425. ->where('USUA_ESTA', '=', "Activo")
  426. ->get();
  427. $employees = DB::table('S002V01TPERS')
  428. ->select("PERS_IDUS as ID_USER")
  429. ->where('PERS_NULI', '=', $line_number)
  430. ->get();
  431. $avaibleUsers = [];
  432. foreach ($users as $user) {
  433. foreach ($employees as $employee) {
  434. if ($user->ID_USER == $employee->ID_USER) {
  435. $user->ID_USER = "XXXX";
  436. }
  437. }
  438. if ($user->ID_USER != "XXXX") {
  439. $avaibleUsers[] = $user;
  440. }
  441. }
  442. // Busca en la base el empleado requerido
  443. if ($id_employee != "0") {
  444. $employeSelected = DB::table('S002V01TPERS')
  445. ->select(
  446. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as NAME'),
  447. "S002V01TUSUA.USUA_IDUS as ID_USER"
  448. )
  449. ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
  450. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  451. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  452. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  453. ->first();
  454. $avaibleUsers[] = $employeSelected;
  455. }
  456. // Verifica si el objeto contiene algo
  457. if (!isset($users) && empty($users)) {
  458. return $this->response_controller
  459. ->makeResponse(TRUE, 'ERR_USUARIO_REG001: No se encontraron datos', [], 500);
  460. }
  461. return $this->response_controller->makeResponse(FALSE, 'Usuarios obtenidos', $avaibleUsers, 200);
  462. } catch (Throwable $th) {
  463. return $this->response_controller
  464. ->makeResponse(TRUE, 'ERR_PERSONAL_REG004: Error inesperado', strtoupper($th), 500);
  465. }
  466. }
  467. // Metodo para guardar un nuevo empleado
  468. public function storeEmployee(Request $request)
  469. {
  470. try {
  471. $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  472. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  473. $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
  474. $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
  475. $request['CONTACT_LADA'] = $this->encrypt_controller->decrypt($request->CONTACT_LADA);
  476. $request['CONTACT_ADDRESS'] = $this->encrypt_controller->decrypt($request->CONTACT_ADDRESS);
  477. $validator = Validator::make($request->all(), [
  478. "USER_ID" => ['required', 'digits:10'],
  479. "WORKTEAM_ID" => ['required', 'digits:10'],
  480. "CONTACT_NAME" => ['required', 'max:150'],
  481. "CONTACT_TELEPHONE" => ['required', 'max:11'],
  482. "CONTACT_LADA" => ['required', 'max:5'],
  483. "CONTACT_ADDRESS" => ['required', 'max:100'],
  484. "CONTRACT_TYPE" => ['required'],
  485. "SPECIALITY" => ['required', 'max:75'],
  486. "SUBCONTRATIST_ID" => ['max:10'],
  487. "SAVED_BY_USER" => ['required', 'digits:10'],
  488. "LINE_NUMBER" => ['required', 'digits:1']
  489. ]);
  490. if ($validator->fails()) {
  491. return $this->response_controller->makeResponse(
  492. TRUE,
  493. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  494. $this->response_controller->makeErrors($validator->errors()->messages()),
  495. 400
  496. );
  497. }
  498. // Busca en la base si existe otro empleado con ese usuario
  499. $uniq_user = DB::table('S002V01TPERS')
  500. ->select("PERS_IDPE")
  501. ->where('PERS_IDUS', '=', $request->USER_ID)
  502. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  503. ->first();
  504. // Verifica si el objeto contiene algo
  505. if (isset($uniq_user) && !empty($uniq_user)) {
  506. return $this->response_controller
  507. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: El usuario ya está registrado como empleado', [], 500);
  508. }
  509. // Busca si el usuario existe
  510. $user_exist = DB::table('S002V01TUSUA')
  511. ->select("USUA_IDUS")
  512. ->where('USUA_IDUS', '=', $request->USER_ID)
  513. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  514. ->first();
  515. // Verifica si el objeto esta vacio
  516. if (!isset($user_exist) && empty($user_exist)) {
  517. return $this->response_controller
  518. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontró al usuario', [], 500);
  519. }
  520. // Busca si el equipo de trabajo existe
  521. $team_found = DB::table('S002V01TEQMA')
  522. ->select('EQMA_NOMB')
  523. ->where('EQMA_IDEQ', '=', $request->WORKTEAM_ID)
  524. ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
  525. ->first();
  526. // Verifica si el objeto esta vacio
  527. if (!isset($team_found) && empty($team_found)) {
  528. return $this->response_controller
  529. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG004: No se encontró al equipo de trabajo', [], 500);
  530. }
  531. $user_register = DB::table('S002V01TUSUA')
  532. ->select('USUA_IDUS as ID_USER')
  533. ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
  534. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  535. ->first();
  536. // Verifica si el objeto esta vacio
  537. if (!isset($user_register) && empty($user_register)) {
  538. return $this->response_controller
  539. ->makeResponse(TRUE, "ERR_USUARIO_REG005: Tu usuario no es válido para registrar empleados", [], 500);
  540. }
  541. DB::beginTransaction(); # Para impedir que las actualizaciones queden a incompletas
  542. $insert_employee = DB::table('S002V01TPERS')
  543. ->insert([
  544. "PERS_IDUS" => $request->USER_ID,
  545. "PERS_NOCE" => trim($request->CONTACT_NAME),
  546. "PERS_NUTC" => $request->CONTACT_TELEPHONE,
  547. "PERS_LATC" => $request->CONTACT_LADA,
  548. "PERS_DICE" => trim($request->CONTACT_ADDRESS),
  549. "PERS_TICO" => trim($request->CONTRACT_TYPE),
  550. "PERS_ESPE" => trim($request->SPECIALITY),
  551. "PERS_IDPS" => $request->SUBCONTRATIST_ID,
  552. "PERS_NULI" => $request->LINE_NUMBER,
  553. "PERS_ESTA" => "Activo",
  554. "PERS_USRE" => $request->SAVED_BY_USER,
  555. "PERS_FERE" => $REGISTER_DATE,
  556. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  557. ]);
  558. // Verifica que la inserción del empleado se haya hecho correctamente
  559. if (!$insert_employee) {
  560. return $this->response_controller
  561. ->makeResponse(TRUE, 'ERR_PERSONAL_REG006: Algo salió mal, error registrando al empleado', [], 500);
  562. }
  563. // Obtiene el ID del empleado registrado
  564. $employee_id = DB::table('S002V01TPERS')
  565. ->select('PERS_IDPE as EMPLOYEE_ID')
  566. ->where('PERS_IDUS', '=', $request->USER_ID)
  567. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  568. ->first();
  569. // Saca el ID del objeto
  570. $employee_id = $employee_id->EMPLOYEE_ID;
  571. $insert_employee_on_workteam = DB::table('S002V01TPEEM')
  572. ->insert([
  573. "PEEM_IDPE" => $employee_id,
  574. "PEEM_IDEM" => $request->WORKTEAM_ID,
  575. "PEEM_NULI" => $request->LINE_NUMBER,
  576. "PEEM_ESTA" => "Activo",
  577. "PEEM_USRE" => $request->SAVED_BY_USER,
  578. "PEEM_FERE" => $REGISTER_DATE,
  579. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
  580. ]);
  581. // Verifica que la inserción del empleado en el equipo de trabajo se haya hecho correctamente
  582. if (!$insert_employee_on_workteam) {
  583. DB::rollBack(); # Si no se logra insertar al equipo, se revierten los cambios previos
  584. return $this->response_controller
  585. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG007: Algo salió mal, error registrando al empleado en el equipo', [], 500);
  586. }
  587. // Verifica si el objeto esta vacio
  588. if (isset($request->DOCUMENTS_AUTHO) && !empty($request->DOCUMENTS_AUTHO)) {
  589. $doc = $request->DOCUMENTS_AUTHO;
  590. // Se obtiene el nombre del archivo con su extensión
  591. $completeFileName = $doc->getClientOriginalName();
  592. // Se obtiene únicamente el nombre
  593. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  594. // Se obtiene la extensión del archivo
  595. $extension = $doc->getClientOriginalExtension();
  596. if ($extension != "pdf") {
  597. return $this->response_controller
  598. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  599. }
  600. // Se quitan los espacios y se concatena datos para ser guardado
  601. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  602. $name_document = $this->documents_controller->createDocument(
  603. "GPRS",
  604. "IN",
  605. $final_part_name_document,
  606. $employee_id,
  607. 'pdf',
  608. $request->LINE_NUMBER,
  609. $request->SAVED_BY_USER
  610. );
  611. // El documento es guardado en el storage
  612. $doc->storeAs('public/pdf_documents', $name_document);
  613. }
  614. // Verifica si el objeto esta vacio
  615. if (isset($request->DOCUMENTS_AUTHO2) && !empty($request->DOCUMENTS_AUTHO2)) {
  616. $doc = $request->DOCUMENTS_AUTHO2;
  617. // Se obtiene el nombre del archivo con su extensión
  618. $completeFileName = $doc->getClientOriginalName();
  619. // Se obtiene únicamente el nombre
  620. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  621. // Se obtiene la extensión del archivo
  622. $extension = $doc->getClientOriginalExtension();
  623. if ($extension != "pdf") {
  624. return $this->response_controller
  625. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  626. }
  627. // Se quitan los espacios y se concatena datos para ser guardado
  628. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  629. $name_document = $this->documents_controller->createDocument(
  630. "GPRS",
  631. "IN",
  632. $final_part_name_document,
  633. $employee_id,
  634. 'pdf',
  635. $request->LINE_NUMBER,
  636. $request->SAVED_BY_USER
  637. );
  638. // El documento es guardado en el storage
  639. $doc->storeAs('public/pdf_documents', $name_document);
  640. }
  641. // Verifica si el objeto esta vacio
  642. if (isset($request->DOCUMENTS_CERT) && !empty($request->DOCUMENTS_CERT)) {
  643. $doc = $request->DOCUMENTS_CERT;
  644. // Se obtiene el nombre del archivo con su extensión
  645. $completeFileName = $doc->getClientOriginalName();
  646. // Se obtiene únicamente el nombre
  647. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  648. // Se obtiene la extensión del archivo
  649. $extension = $doc->getClientOriginalExtension();
  650. if ($extension != "pdf") {
  651. return $this->response_controller
  652. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  653. }
  654. // Se quitan los espacios y se concatena datos para ser guardado
  655. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  656. $name_document = $this->documents_controller->createDocument(
  657. "GPRS",
  658. "CE",
  659. $final_part_name_document,
  660. $employee_id,
  661. 'pdf',
  662. $request->LINE_NUMBER,
  663. $request->SAVED_BY_USER
  664. );
  665. // El documento es guardado en el storage
  666. $doc->storeAs('public/pdf_documents', $name_document);
  667. }
  668. // Verifica si el objeto esta vacio
  669. if (isset($request->DOCUMENTS_CERT2) && !empty($request->DOCUMENTS_CERT2)) {
  670. $doc = $request->DOCUMENTS_CERT2;
  671. // Se obtiene el nombre del archivo con su extensión
  672. $completeFileName = $doc->getClientOriginalName();
  673. // Se obtiene únicamente el nombre
  674. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  675. // Se obtiene la extensión del archivo
  676. $extension = $doc->getClientOriginalExtension();
  677. if ($extension != "pdf") {
  678. return $this->response_controller
  679. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  680. }
  681. // Se quitan los espacios y se concatena datos para ser guardado
  682. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  683. $name_document = $this->documents_controller->createDocument(
  684. "GPRS",
  685. "CE",
  686. $final_part_name_document,
  687. $employee_id,
  688. 'pdf',
  689. $request->LINE_NUMBER,
  690. $request->SAVED_BY_USER
  691. );
  692. // El documento es guardado en el storage
  693. $doc->storeAs('public/pdf_documents', $name_document);
  694. }
  695. // Verifica si el objeto esta vacio
  696. if (isset($request->DOCUMENT_OFFICE) && !empty($request->DOCUMENT_OFFICE)) {
  697. $doc = $request->DOCUMENT_OFFICE;
  698. // Se obtiene el nombre del archivo con su extensión
  699. $completeFileName = $doc->getClientOriginalName();
  700. // Se obtiene únicamente el nombre
  701. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  702. // Se obtiene la extensión del archivo
  703. $extension = $doc->getClientOriginalExtension();
  704. if ($extension != "pdf") {
  705. return $this->response_controller
  706. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  707. }
  708. // Se quitan los espacios y se concatena datos para ser guardado
  709. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  710. $name_document = $this->documents_controller->createDocument(
  711. "GPRS",
  712. "CO",
  713. $final_part_name_document,
  714. $employee_id,
  715. 'pdf',
  716. $request->LINE_NUMBER,
  717. $request->SAVED_BY_USER
  718. );
  719. // El documento es guardado en el storage
  720. $doc->storeAs('public/pdf_documents', $name_document);
  721. }
  722. DB::commit(); # Para guardar los cambios en la base de datos
  723. return $this->response_controller->makeResponse(FALSE, 'Creación exitosa', 200);
  724. } catch (Throwable $th) {
  725. return $this->response_controller
  726. ->makeResponse(TRUE, 'ERR_PERSONAL_REG008: Error inesperado', strtoupper($th), 500);
  727. }
  728. }
  729. // Metodo para obtener un empleado por id con sus documentos (Pensado: 1 empleado solo tiene un equipo de trabajo)
  730. public function getEmployeeById($id_employee, $line_number)
  731. {
  732. try {
  733. $employee = DB::table('S002V01TPERS')
  734. ->select(
  735. 'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
  736. 'S002V01TPERS.PERS_IDUS as USER_ID',
  737. 'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
  738. 'S002V01TPERS.PERS_IDPS as SUBCONTRATIST_ID',
  739. 'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
  740. 'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
  741. 'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
  742. 'S002V01TPERS.PERS_LATC as CONTACT_LADA',
  743. 'S002V01TPERS.PERS_DICE as CONTACT_ADDRESS',
  744. 'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
  745. 'S002V01TPERS.PERS_ESPE as SPECIALITY',
  746. 'S002V01TPERS.PERS_NULI as LINE_NUMBER',
  747. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as EMPLOYEE_NAME')
  748. )
  749. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  750. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  751. ->where('s002v01TPEEM.PEEM_NULI', '=', $line_number)
  752. ->where('s002v01TEQMA.EQMA_NULI', '=', $line_number)
  753. ->where('s002v01TUSUA.USUA_NULI', '=', $line_number)
  754. ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
  755. ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
  756. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  757. ->first();
  758. // Verifica si el objeto esta vacio
  759. if (!isset($employee) && empty($employee)) {
  760. return $this->response_controller
  761. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  762. }
  763. $employee->CONTACT_NAME = $this->encrypt_controller->encrypt($employee->CONTACT_NAME);
  764. $employee->CONTACT_TELEPHONE = $this->encrypt_controller->encrypt($employee->CONTACT_TELEPHONE);
  765. $employee->CONTACT_LADA = $this->encrypt_controller->encrypt($employee->CONTACT_LADA);
  766. $employee->CONTACT_ADDRESS = $this->encrypt_controller->encrypt($employee->CONTACT_ADDRESS);
  767. $employee->DOCUMENTS = [];
  768. // Obtiene los documentos de un empleado
  769. $documents_of_employee = DB::table('S002V01TDOCU_P')
  770. ->select('DOCU_LIDO as DOCUMENT')
  771. ->where('DOCU_IDPE', '=', $id_employee)
  772. ->where('DOCU_NULI', '=', $line_number)
  773. ->get();
  774. // Verifica si el objeto contiene algo
  775. if (isset($documents_of_employee[0]) && !empty($documents_of_employee[0])) {
  776. foreach ($documents_of_employee as $doc) {
  777. $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
  778. }
  779. }
  780. return $this->response_controller
  781. ->makeResponse(FALSE, "Consulta exitosa", $employee);
  782. } catch (Throwable $th) {
  783. return $this->response_controller
  784. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
  785. }
  786. }
  787. // Metodo para obtener todos los empleados con sus documentos (Pensado: 1 empleado solo tiene un equipo de trabajo)
  788. public function getAllEmployees($line_number)
  789. {
  790. try {
  791. $employees = DB::table('S002V01TPERS')
  792. ->select(
  793. 'S002V01TPERS.PERS_IDPE as EMPLOYEE_ID',
  794. 'S002V01TPERS.PERS_IDUS as USER_ID',
  795. 'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
  796. 'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
  797. 'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
  798. 'S002V01TPERS.PERS_LATC as CONTACT_LADA',
  799. 'S002V01TPERS.PERS_DICE as CONTACT_ADDRESS',
  800. 'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
  801. 'S002V01TPERS.PERS_ESPE as SPECIALITY',
  802. )
  803. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  804. ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
  805. ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
  806. ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
  807. ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
  808. ->get();
  809. // Verifica si el objeto esta vacio
  810. if (!isset($employees[0]) && empty($employees[0])) {
  811. return $this->response_controller
  812. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontraron datos', [], 500);
  813. }
  814. foreach ($employees as $employee) {
  815. $employee->CONTACT_NAME = $this->encrypt_controller->encrypt($employee->CONTACT_NAME);
  816. $employee->CONTACT_TELEPHONE = $this->encrypt_controller->encrypt($employee->CONTACT_TELEPHONE);
  817. $employee->CONTACT_LADA = $this->encrypt_controller->encrypt($employee->CONTACT_LADA);
  818. $employee->CONTACT_ADDRESS = $this->encrypt_controller->encrypt($employee->CONTACT_ADDRESS);
  819. $employee->DOCUMENTS = [];
  820. }
  821. // Obtiene los documentos
  822. $documents_of_employees = DB::table('S002V01TDOCU_P')
  823. ->select('DOCU_LIDO as DOCUMENT', 'DOCU_IDPE as EMPLOYEE_ID')
  824. ->where('DOCU_NULI', '=', $line_number)
  825. ->get();
  826. // Verifica si el objeto esta vacio
  827. if (isset($documents_of_employees[0]) && !empty($documents_of_employees[0])) {
  828. // Asigna al empleado los documentos que le pertenezcan
  829. foreach ($employees as $employee) {
  830. foreach ($documents_of_employees as $doc) {
  831. if ($employee->EMPLOYEE_ID == $doc->EMPLOYEE_ID) {
  832. $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
  833. }
  834. }
  835. }
  836. }
  837. return $this->response_controller
  838. ->makeResponse(FALSE, "Consulta exitosa", $employees);
  839. } catch (Throwable $th) {
  840. return $this->response_controller
  841. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
  842. }
  843. }
  844. // Metodo para actualizar un empleado
  845. public function updateEmployee(Request $request, $id_employee)
  846. {
  847. try {
  848. $save_option = $request->UPLOAD_NEW_DOCUMENTS != "N";
  849. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  850. $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  851. $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
  852. $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
  853. $request['CONTACT_LADA'] = $this->encrypt_controller->decrypt($request->CONTACT_LADA);
  854. $request['CONTACT_ADDRESS'] = $this->encrypt_controller->decrypt($request->CONTACT_ADDRESS);
  855. $validator = Validator::make($request->all(), [
  856. "USER_ID" => ['required', 'digits:10'],
  857. "WORKTEAM_ID" => ['required', 'digits:10'],
  858. "CONTACT_NAME" => ['required', 'max:150'],
  859. "CONTACT_TELEPHONE" => ['required', 'max:11'],
  860. "CONTACT_LADA" => ['required', 'max:5'],
  861. "CONTACT_ADDRESS" => ['required', 'max:100'],
  862. "CONTRACT_TYPE" => ['required'],
  863. "SPECIALITY" => ['required', 'max:75'],
  864. "SUBCONTRATIST_ID" => ['max:10'],
  865. "SAVED_BY_USER" => ['required', 'digits:10'],
  866. "LINE_NUMBER" => ['required', 'digits:1']
  867. ]);
  868. if ($validator->fails()) {
  869. return $this->response_controller->makeResponse(
  870. TRUE,
  871. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  872. $this->response_controller->makeErrors($validator->errors()->messages()),
  873. 400
  874. );
  875. }
  876. // Busca al empleado si existe
  877. $employee_exist = DB::table('S002V01TPERS')
  878. ->select('PERS_IDPE')
  879. ->where('PERS_IDPE', '=', $id_employee)
  880. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  881. ->first();
  882. // Verifica si el objeto esta vacio
  883. if (!isset($employee_exist) && empty($employee_exist)) {
  884. return $this->response_controller
  885. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: No se encontró al empleado', [], 500);
  886. }
  887. // Busca al equipo de trabajo si existe
  888. $team_found = DB::table('S002V01TEQMA')
  889. ->select('EQMA_NOMB')
  890. ->where('EQMA_IDEQ', '=', $request->WORKTEAM_ID)
  891. ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
  892. ->first();
  893. // Verifica si el objeto esta vacio
  894. if (!isset($team_found) && empty($team_found)) {
  895. return $this->response_controller
  896. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: No se encontró al equipo de trabajo', [], 500);
  897. }
  898. $user_register = DB::table('S002V01TUSUA')
  899. ->select('USUA_IDUS as ID_USER')
  900. ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
  901. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  902. ->first();
  903. // Verifica si el objeto esta vacio
  904. if (!isset($user_register) && empty($user_register)) {
  905. return $this->response_controller
  906. ->makeResponse(TRUE, "ERR_USUARIO_REG004: Tu usuario no es válido para actualizar empleados", [], 500);
  907. }
  908. DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
  909. $update_employee = DB::table('S002V01TPERS')
  910. ->where('PERS_IDPE', '=', $id_employee)
  911. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  912. ->update([
  913. "PERS_IDUS" => $request->USER_ID,
  914. "PERS_NOCE" => trim($request->CONTACT_NAME),
  915. "PERS_NUTC" => $request->CONTACT_TELEPHONE,
  916. "PERS_LATC" => $request->CONTACT_LADA,
  917. "PERS_DICE" => trim($request->CONTACT_ADDRESS),
  918. "PERS_TICO" => trim($request->CONTRACT_TYPE),
  919. "PERS_ESPE" => trim($request->SPECIALITY),
  920. "PERS_IDPS" => $request->SUBCONTRATIST_ID,
  921. "PERS_ESTA" => "Activo",
  922. "PERS_USMO" => $request->SAVED_BY_USER,
  923. "PERS_FEMO" => $UPDATE_DATE,
  924. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  925. ]);
  926. // Verifica que la actualización del empleado haya sido satisfactoria
  927. if ($update_employee < 1) {
  928. return $this->response_controller
  929. ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error actualizando al empleado', [], 500);
  930. }
  931. $update_employee_on_workteam = DB::table('S002V01TPEEM')
  932. ->where('PEEM_IDPE', '=', $id_employee)
  933. ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
  934. ->update([
  935. "PEEM_IDEM" => $request->WORKTEAM_ID,
  936. "PEEM_ESTA" => "Activo",
  937. "PEEM_USRE" => $request->SAVED_BY_USER,
  938. "PEEM_FERE" => $UPDATE_DATE,
  939. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
  940. ]);
  941. // Verifica que la actualización del cambio de equipo del empleado haya sido satisfactoria
  942. if ($update_employee_on_workteam < 1) {
  943. DB::rollBack(); # Si no se logra actualizar el equipo, se revierten los cambios previos
  944. return $this->response_controller
  945. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG006: Algo salió mal, error cambiando al empleado de equipo', [], 500);
  946. }
  947. // Verifica si el objeto esta vacio
  948. if (isset($request->DOCUMENTS_AUTHO) && !empty($request->DOCUMENTS_AUTHO)) {
  949. $doc = $request->DOCUMENTS_AUTHO;
  950. // Se obtiene el nombre del archivo con su extensión
  951. $completeFileName = $doc->getClientOriginalName();
  952. // Se obtiene únicamente el nombre
  953. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  954. // Se obtiene la extensión del archivo
  955. $extension = $doc->getClientOriginalExtension();
  956. if ($extension != "pdf") {
  957. return $this->response_controller
  958. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  959. }
  960. // Se quitan los espacios y se concatena datos para ser guardado
  961. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  962. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  963. $name_document = $this->documents_controller->createDocument(
  964. "GPRS",
  965. "IN",
  966. $final_part_name_document,
  967. $id_employee,
  968. 'pdf',
  969. $request->LINE_NUMBER,
  970. $request->SAVED_BY_USER,
  971. $request->DOCUMENTS_AUTHO_UPDATE
  972. );
  973. // El documento es guardado en el storage
  974. $doc->storeAs('public/pdf_documents', $name_document);
  975. }
  976. // Verifica si el objeto esta vacio
  977. if (isset($request->DOCUMENTS_AUTHO2) && !empty($request->DOCUMENTS_AUTHO2)) {
  978. $doc = $request->DOCUMENTS_AUTHO2;
  979. // Se obtiene el nombre del archivo con su extensión
  980. $completeFileName = $doc->getClientOriginalName();
  981. // Se obtiene únicamente el nombre
  982. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  983. // Se obtiene la extensión del archivo
  984. $extension = $doc->getClientOriginalExtension();
  985. if ($extension != "pdf") {
  986. return $this->response_controller
  987. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  988. }
  989. // Se quitan los espacios y se concatena datos para ser guardado
  990. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  991. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  992. $name_document = $this->documents_controller->createDocument(
  993. "GPRS",
  994. "IN",
  995. $final_part_name_document,
  996. $id_employee,
  997. 'pdf',
  998. $request->LINE_NUMBER,
  999. $request->SAVED_BY_USER,
  1000. $request->DOCUMENTS_AUTHO2_UPDATE
  1001. );
  1002. // El documento es guardado en el storage
  1003. $doc->storeAs('public/pdf_documents', $name_document);
  1004. }
  1005. // Verifica si el objeto esta vacio
  1006. if (isset($request->DOCUMENTS_CERT) && !empty($request->DOCUMENTS_CERT)) {
  1007. $doc = $request->DOCUMENTS_CERT;
  1008. // Se obtiene el nombre del archivo con su extensión
  1009. $completeFileName = $doc->getClientOriginalName();
  1010. // Se obtiene únicamente el nombre
  1011. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  1012. // Se obtiene la extensión del archivo
  1013. $extension = $doc->getClientOriginalExtension();
  1014. if ($extension != "pdf") {
  1015. return $this->response_controller
  1016. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  1017. }
  1018. // Se quitan los espacios y se concatena datos para ser guardado
  1019. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1020. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1021. $name_document = $this->documents_controller->createDocument(
  1022. "GPRS",
  1023. "CE",
  1024. $final_part_name_document,
  1025. $id_employee,
  1026. 'pdf',
  1027. $request->LINE_NUMBER,
  1028. $request->SAVED_BY_USER,
  1029. $request->DOCUMENTS_CERT_UPDATE
  1030. );
  1031. // El documento es guardado en el storage
  1032. $doc->storeAs('public/pdf_documents', $name_document);
  1033. }
  1034. // Verifica si el objeto esta vacio
  1035. if (isset($request->DOCUMENTS_CERT2) && !empty($request->DOCUMENTS_CERT2)) {
  1036. $doc = $request->DOCUMENTS_CERT2;
  1037. // Se obtiene el nombre del archivo con su extensión
  1038. $completeFileName = $doc->getClientOriginalName();
  1039. // Se obtiene únicamente el nombre
  1040. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  1041. // Se obtiene la extensión del archivo
  1042. $extension = $doc->getClientOriginalExtension();
  1043. if ($extension != "pdf") {
  1044. return $this->response_controller
  1045. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  1046. }
  1047. // Se quitan los espacios y se concatena datos para ser guardado
  1048. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1049. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1050. $name_document = $this->documents_controller->createDocument(
  1051. "GPRS",
  1052. "CE",
  1053. $final_part_name_document,
  1054. $id_employee,
  1055. 'pdf',
  1056. $request->LINE_NUMBER,
  1057. $request->SAVED_BY_USER,
  1058. $request->DOCUMENTS_CERT2_UPDATE
  1059. );
  1060. // El documento es guardado en el storage
  1061. $doc->storeAs('public/pdf_documents', $name_document);
  1062. }
  1063. // Verifica si el objeto esta vacio
  1064. if (isset($request->DOCUMENT_OFFICE) && !empty($request->DOCUMENT_OFFICE)) {
  1065. $doc = $request->DOCUMENT_OFFICE;
  1066. // Se obtiene el nombre del archivo con su extensión
  1067. $completeFileName = $doc->getClientOriginalName();
  1068. // Se obtiene únicamente el nombre
  1069. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  1070. // Se obtiene la extensión del archivo
  1071. $extension = $doc->getClientOriginalExtension();
  1072. if ($extension != "pdf") {
  1073. return $this->response_controller
  1074. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  1075. }
  1076. // Se quitan los espacios y se concatena datos para ser guardado
  1077. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1078. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1079. $name_document = $this->documents_controller->createDocument(
  1080. "GPRS",
  1081. "CO",
  1082. $final_part_name_document,
  1083. $id_employee,
  1084. 'pdf',
  1085. $request->LINE_NUMBER,
  1086. $request->SAVED_BY_USER,
  1087. $request->DOCUMENT_OFFICE_UPDATE
  1088. );
  1089. // El documento es guardado en el storage
  1090. $doc->storeAs('public/pdf_documents', $name_document);
  1091. }
  1092. DB::commit(); # Para guardar los cambios en la base de datos
  1093. return $this->response_controller->makeResponse(FALSE, 'Actualización exitosa', 200);
  1094. } catch (Throwable $th) {
  1095. return $this->response_controller
  1096. ->makeResponse(TRUE, 'ERR_PERSONAL_REG008: Error inesperado', strtoupper($th), 500);
  1097. }
  1098. }
  1099. // Metodo para obtener la cantidad de contratos otorgados a cada empleado
  1100. public function getContractsOfEveryEmployee($line_number)
  1101. {
  1102. try {
  1103. // Obtiene la cantidad de contratos que tiene cada empleado
  1104. $contracts_by_employee = DB::table('S002V01TPERS')
  1105. ->select(
  1106. 'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
  1107. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) AS NAME'),
  1108. DB::raw(
  1109. 'COUNT(S002V01TPECO.PECO_IDPE) AS CONTRACTS_COUNT',
  1110. )
  1111. )
  1112. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  1113. ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
  1114. ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
  1115. ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
  1116. ->groupBy('S002V01TPERS.PERS_IDPE', 'NAME', 'S002V01TPECO.PECO_IDPE')
  1117. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  1118. ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
  1119. ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
  1120. ->get();
  1121. // Verifica si el objeto esta vacio
  1122. if (!isset($contracts_by_employee[0]) && empty($contracts_by_employee[0])) {
  1123. return $this->response_controller
  1124. ->makeResponse(TRUE, 'ERR_PERSONAL_CONTRATO_REG001: No se encontraron datos', [], 500);
  1125. }
  1126. return $this->response_controller
  1127. ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
  1128. } catch (Throwable $th) {
  1129. return $this->response_controller
  1130. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
  1131. }
  1132. }
  1133. // Metodo para obtener detalles acerca de los contratos otorgados al empleado
  1134. public function getDetailsOfContractsByEmployee($id_employee, $line_number)
  1135. {
  1136. try {
  1137. // Busca al empleado si existe
  1138. $employee_exist = DB::table('S002V01TPERS')
  1139. ->select('PERS_IDPE')
  1140. ->where('PERS_IDPE', '=', $id_employee)
  1141. ->where('PERS_NULI', '=', $line_number)
  1142. ->first();
  1143. // Verifica si el objeto esta vacio
  1144. if (!isset($employee_exist) && empty($employee_exist)) {
  1145. return $this->response_controller
  1146. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  1147. }
  1148. //Obtiene los contratos pertenecientes al subcontratista deseado
  1149. $contracts_by_employee = DB::table('S002V01TPERS')
  1150. ->orderBy("S002V01TCONT.CONT_FEIN", 'desc')
  1151. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  1152. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  1153. ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
  1154. ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
  1155. ->select('S002V01TCONT.CONT_FEIN as START_DATE', 'S002V01TCONT.CONT_FEFI as END_DATE', 'S002V01TCONT.CONT_COST as CONTRACT_COST')
  1156. ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
  1157. ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
  1158. ->get();
  1159. // Verifica si el objeto esta vacio
  1160. if (!isset($contracts_by_employee[0]) && empty($contracts_by_employee[0])) {
  1161. return $this->response_controller
  1162. ->makeResponse(TRUE, 'ERR_PERSONAL_CONTRATO_REG002: Empleado sin contratos', $contracts_by_employee, 500);
  1163. }
  1164. foreach ($contracts_by_employee as $contract) {
  1165. $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
  1166. $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
  1167. $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
  1168. }
  1169. return $this->response_controller
  1170. ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
  1171. } catch (Throwable $th) {
  1172. return $this->response_controller
  1173. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
  1174. }
  1175. }
  1176. // Metodo para la descarga de archivo excel con los detalles del empleado
  1177. public function downoloadEmployeeInfoOnExcel(Request $request)
  1178. {
  1179. try {
  1180. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  1181. $employee_id = $request->EMPLOYEE['ID_EMPLOYEE'];
  1182. $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".xlsx";
  1183. // Crea el documento con los datos del request
  1184. $document = $this->createDocument($request);
  1185. // Busca la ultima versión del documento que se haya insertado
  1186. $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'excel');
  1187. if ($old_document_name != null) {
  1188. // Obtiene el nombre del documento que tiene el mismo contenido
  1189. $old_document_name = $this->documents_controller->sameDocumentsExcel($document, $old_document_name);
  1190. // Si no hay ningun cambio en el documento, se descarga la ultima versión
  1191. if ($old_document_name != null) {
  1192. return $this->response_controller
  1193. ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($old_document_name), 200);
  1194. }
  1195. }
  1196. // Guarda el documento creado en la variable
  1197. $writer = IOFactory::createWriter($document, 'Xlsx');
  1198. $content = tmpfile();
  1199. $writer->save($content);
  1200. // Inserta la nueva version del documento en la base de datos y en el storage
  1201. $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, $employee_id, "excel", $request->EMPLOYEE['LINE_NUMBER'], $request->SAVED_BY_USER);
  1202. Storage::disk('excel')->put(
  1203. $name_document,
  1204. $content
  1205. );
  1206. return $this->response_controller
  1207. ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($name_document), 200);
  1208. } catch (Throwable $th) {
  1209. return $this->response_controller
  1210. ->makeResponse(TRUE, 'ERR_EXCEL_REG001: Error inesperado', strtoupper($th), 500);
  1211. }
  1212. }
  1213. // Metodo para la descarga de archivo pdf con los detalles del empleado
  1214. public function downoloadEmployeeInfoOnPdf(Request $request)
  1215. {
  1216. try {
  1217. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  1218. $employee_id = $request->EMPLOYEE['ID_EMPLOYEE'];
  1219. $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".pdf";
  1220. // Crea el documento
  1221. $document = $this->createDocument($request);
  1222. $writer = IOFactory::createWriter($document, 'Mpdf');
  1223. $content = tmpfile();
  1224. // Busca la ultima versión del documento que se haya insertado
  1225. $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'pdf');
  1226. $writer->save($content);
  1227. if ($old_document_name != null) {
  1228. // Obtiene el nombre del documento que tiene el mismo contenido
  1229. $old_document_name = $this->documents_controller->sameDocumentsPdf($content, $old_document_name);
  1230. // Si no hay ningun cambio en el documento, se descarga la ultima versión
  1231. if ($old_document_name != null) {
  1232. return $this->response_controller
  1233. ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($old_document_name), 200);
  1234. }
  1235. }
  1236. // Inserta la nueva version del documento en la base de datos y en el storage
  1237. $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, $employee_id, "pdf", $request->EMPLOYEE['LINE_NUMBER'], $request->SAVED_BY_USER);
  1238. Storage::disk('pdf')->put(
  1239. $name_document,
  1240. $content
  1241. );
  1242. return $this->response_controller
  1243. ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($name_document), 200);
  1244. } catch (Throwable $th) {
  1245. return $this->response_controller
  1246. ->makeResponse(TRUE, 'ERR_PDF_REG001: Error inesperado', strtoupper($th), 500);
  1247. }
  1248. }
  1249. // Metodo para la creación de archivo
  1250. public function createDocument(Request $request)
  1251. {
  1252. try {
  1253. $employee = $request->EMPLOYEE;
  1254. $document = new Spreadsheet();
  1255. // Propiedades del documento
  1256. $document->getProperties()
  1257. ->setCreator("ITTEC")
  1258. ->setTitle("Detalles del empleado")
  1259. ->setDescription("Detalles de solo un empleado.")
  1260. ->setKeywords("Empleado Detalles")
  1261. ->setCategory("Empleado Detalles Pdf");
  1262. // Cambia la hoja a horizontal par que se observen mejor los datos
  1263. $document->getActiveSheet()->getPageSetup()->setOrientation("landscape");
  1264. // Hace la escritura dentro del archivo
  1265. $start_row = 2; # Indica desde que fila inicia la tabla
  1266. $start_col = "B"; # Indica desde que columna inicia la tabla
  1267. $col = $start_col;
  1268. $row = $start_row;
  1269. $col++;
  1270. $second_col = $col;
  1271. $col++;
  1272. $third_col = $col;
  1273. $col++;
  1274. $fourth_col = $col;
  1275. $col++;
  1276. $fifth_col = $col;
  1277. $col++;
  1278. $sixth_col = $col;
  1279. $col++;
  1280. $seventh_col = $col;
  1281. $col++;
  1282. $eight_col = $col;
  1283. $col = $start_col;
  1284. $final_col = "";
  1285. for ($i = 0; $i < 9; $i++) {
  1286. $final_col = $col;
  1287. $col++;
  1288. }
  1289. $col = $start_col;
  1290. // Titulo del documento
  1291. $document->getActiveSheet()->mergeCells($start_col . $row . ":" . $final_col . $row);
  1292. $document->getActiveSheet()->setCellValue($start_col . $row, 'DETALLES DEL EMPLEADO')->getStyle($start_col . $row)->getFill()
  1293. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1294. ->getStartColor()->setRGB('FFCC88');
  1295. $document->getActiveSheet()->getStyle($start_col . $row)->getFont()->setBold(true);
  1296. $row++;
  1297. //Cuerpo del documento
  1298. $document->getActiveSheet()->setCellValue($col . $row, 'ID EMPLEADO')->getStyle($col . $row)->getFill()
  1299. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1300. ->getStartColor()->setRGB('38D9CE');
  1301. $col++;
  1302. $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE EMPLEADO')->getStyle($col . $row)->getFill()
  1303. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1304. ->getStartColor()->setRGB('38D9CE');
  1305. $col++;
  1306. $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE EQUIPO')->getStyle($col . $row)->getFill()
  1307. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1308. ->getStartColor()->setRGB('38D9CE');
  1309. $col++;
  1310. $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
  1311. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1312. ->getStartColor()->setRGB('38D9CE');
  1313. $col++;
  1314. $document->getActiveSheet()->setCellValue($col . $row, 'TELEFONO CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
  1315. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1316. ->getStartColor()->setRGB('38D9CE');
  1317. $col++;
  1318. $document->getActiveSheet()->setCellValue($col . $row, 'DIRECCIÓN CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
  1319. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1320. ->getStartColor()->setRGB('38D9CE');
  1321. $col++;
  1322. $document->getActiveSheet()->setCellValue($col . $row, 'TIPO DE CONTRATO')->getStyle($col . $row)->getFill()
  1323. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1324. ->getStartColor()->setRGB('38D9CE');
  1325. $col++;
  1326. $document->getActiveSheet()->setCellValue($col . $row, 'ESPECIALIDAD DEL EMPLEADO')->getStyle($col . $row)->getFill()
  1327. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1328. ->getStartColor()->setRGB('38D9CE');
  1329. $col++;
  1330. $document->getActiveSheet()->setCellValue($col . $row, 'DOCUMENTOS')->getStyle($col . $row)->getFill()
  1331. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1332. ->getStartColor()->setRGB('38D9CE');
  1333. $row++;
  1334. $col = $start_col;
  1335. $document->getActiveSheet()->setCellValue($col . $row, "#" . $employee['ID_EMPLOYEE']);
  1336. $col++;
  1337. $document->getActiveSheet()->setCellValue($col . $row, $employee['EMPLOYEE_NAME']);
  1338. $col++;
  1339. $document->getActiveSheet()->setCellValue($col . $row, $employee['WORKTEAM_NAME']);
  1340. $col++;
  1341. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_NAME']));
  1342. $col++;
  1343. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_LADA']) . $this->encrypt_controller->decrypt($employee['CONTACT_TELEPHONE']));
  1344. $col++;
  1345. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_ADDRESS']));
  1346. $col++;
  1347. $document->getActiveSheet()->setCellValue($col . $row, $employee['CONTRACT_TYPE']);
  1348. $col++;
  1349. $document->getActiveSheet()->setCellValue($col . $row, $employee['SPECIALITY']);
  1350. $col++;
  1351. // Verifica si el empleado tiene documentos
  1352. if (isset($employee['DOCUMENTS'][0]) && !empty($employee['DOCUMENTS'][0])) {
  1353. foreach ($employee['DOCUMENTS'] as $doc) {
  1354. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($doc));
  1355. $row++;
  1356. }
  1357. } else {
  1358. $document->getActiveSheet()->setCellValue($col . $row, 'SIN DOCUMENTOS...');
  1359. $document->getActiveSheet()->getStyle($col . $row)->getFont()->setBold(true);
  1360. $row++;
  1361. }
  1362. //Ajusta las celdas a su contenido y da estilo
  1363. $document->getActiveSheet()->mergeCells($start_col . $start_row + 2 . ":" . $start_col . $row - 1);
  1364. $document->getActiveSheet()->mergeCells($second_col . $start_row + 2 . ":" . $second_col . $row - 1);
  1365. $document->getActiveSheet()->mergeCells($third_col . $start_row + 2 . ":" . $third_col . $row - 1);
  1366. $document->getActiveSheet()->mergeCells($fourth_col . $start_row + 2 . ":" . $fourth_col . $row - 1);
  1367. $document->getActiveSheet()->mergeCells($fifth_col . $start_row + 2 . ":" . $fifth_col . $row - 1);
  1368. $document->getActiveSheet()->mergeCells($sixth_col . $start_row + 2 . ":" . $sixth_col . $row - 1);
  1369. $document->getActiveSheet()->mergeCells($seventh_col . $start_row + 2 . ":" . $seventh_col . $row - 1);
  1370. $document->getActiveSheet()->mergeCells($eight_col . $start_row + 2 . ":" . $eight_col . $row - 1);
  1371. $col = $start_col;
  1372. for ($i = 0; $i < 9; $i++) {
  1373. $document->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
  1374. $col++;
  1375. }
  1376. $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
  1377. $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  1378. $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row - 1)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM);
  1379. return $document;
  1380. } catch (Throwable $th) {
  1381. return $this->response_controller
  1382. ->makeResponse(TRUE, 'ERR_CREACIÓN_DOCUMENTO_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
  1383. }
  1384. }
  1385. }