EmployeeController.php 75 KB

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