EmployeeController.php 77 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698
  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. $check_workteam = DB::table("S002V01TEQMA")
  376. ->select("S002V01TEQMA.EQMA_ESTA as STATUS")
  377. ->where("S002V01TPEEM.PEEM_IDPE", '=', $id_employee)
  378. ->join('S002V01TPEEM', 'S002V01TEQMA.EQMA_IDEQ', '=', 'S002V01TPEEM.PEEM_IDEM')
  379. ->first();
  380. if($check_workteam->STATUS == "Eliminado"){
  381. return $this->response_controller
  382. ->makeResponse(TRUE, "ERR_EQUIPO_TRABAJO_REG004: El equipo de trabajo no esta activo", [], 500);
  383. }
  384. DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
  385. $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  386. $activate_employee = DB::table('S002V01TPERS')
  387. ->where('PERS_IDPE', $id_employee)
  388. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  389. ->update([
  390. "PERS_ESTA" => "Activo",
  391. "PERS_USMO" => trim($request->SAVED_BY_USER),
  392. "PERS_FEMO" => $UPDATE_DATE,
  393. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  394. ]);
  395. // Verifica que la actualización fuera exitosa
  396. if ($activate_employee < 1) {
  397. return $this->response_controller
  398. ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error activando al empleado', [], 500);
  399. }
  400. $activate_employee = DB::table('S002V01TPEEM')
  401. ->where('PEEM_IDPE', $id_employee)
  402. ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
  403. ->update([
  404. "PEEM_ESTA" => "Activo",
  405. "PEEM_USMO" => trim($request->SAVED_BY_USER),
  406. "PEEM_FEMO" => $UPDATE_DATE,
  407. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  408. ]);
  409. // Verifica que la actualización fuera exitosa
  410. if ($activate_employee < 1) {
  411. DB::rollBack(); # Si no se logra eliminar al empleado en el equipo, se revierten los cambios previos
  412. return $this->response_controller
  413. ->makeResponse(TRUE, 'ERR_PERSONAL_REG006: Algo salió mal, error activando al empleado del equipo', [], 500);
  414. }
  415. DB::commit(); # Para guardar los cambios en la base de datos
  416. return $this->response_controller->makeResponse(FALSE, "Activación exitosa");
  417. } catch (Throwable $th) {
  418. return $this->response_controller->
  419. makeResponse(TRUE, 'ERR_PERSONAL_REG007: Error inesperado', strtoupper($th->getMessage()), 500);
  420. }
  421. }
  422. // Metodo para obtener a los usuarios que no son empleados y el enviado por path
  423. public function getAvaibleUsers($id_employee, $line_number)
  424. {
  425. try {
  426. // Busca en la base si existe otro empleado con ese usuario
  427. $users = DB::table('S002V01TUSUA')
  428. ->select(
  429. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  430. "USUA_IDUS as ID_USER"
  431. )
  432. ->orderBy('NAME', 'asc')
  433. ->where('USUA_NULI', '=', $line_number)
  434. ->where('USUA_ESTA', '=', "Activo")
  435. ->get();
  436. $employees = DB::table('S002V01TPERS')
  437. ->select("PERS_IDUS as ID_USER")
  438. ->where('PERS_NULI', '=', $line_number)
  439. ->get();
  440. $avaibleUsers = [];
  441. foreach ($users as $user) {
  442. foreach ($employees as $employee) {
  443. if ($user->ID_USER == $employee->ID_USER) {
  444. $user->ID_USER = "XXXX";
  445. }
  446. }
  447. if ($user->ID_USER != "XXXX") {
  448. $avaibleUsers[] = $user;
  449. }
  450. }
  451. // Busca en la base el empleado requerido
  452. if ($id_employee != "0") {
  453. $employeSelected = DB::table('S002V01TPERS')
  454. ->select(
  455. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as NAME'),
  456. "S002V01TUSUA.USUA_IDUS as ID_USER"
  457. )
  458. ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
  459. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  460. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  461. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  462. ->first();
  463. $avaibleUsers[] = $employeSelected;
  464. }
  465. // Verifica si el objeto contiene algo
  466. if (!isset($users) && empty($users)) {
  467. return $this->response_controller
  468. ->makeResponse(TRUE, 'ERR_USUARIO_REG001: No se encontraron datos', [], 500);
  469. }
  470. return $this->response_controller->makeResponse(FALSE, 'Usuarios obtenidos', $avaibleUsers, 200);
  471. } catch (Throwable $th) {
  472. return $this->response_controller
  473. ->makeResponse(TRUE, 'ERR_PERSONAL_REG004: Error inesperado', strtoupper($th), 500);
  474. }
  475. }
  476. // Metodo para guardar un nuevo empleado
  477. public function storeEmployee(Request $request)
  478. {
  479. try {
  480. $REGISTER_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  481. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  482. $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
  483. $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
  484. $request['CONTACT_LADA'] = $this->encrypt_controller->decrypt($request->CONTACT_LADA);
  485. $request['CONTACT_ADDRESS'] = $this->encrypt_controller->decrypt($request->CONTACT_ADDRESS);
  486. $validator = Validator::make($request->all(), [
  487. "USER_ID" => ['required', 'digits:10'],
  488. "WORKTEAM_ID" => ['required', 'digits:10'],
  489. "CONTACT_NAME" => ['required', 'max:150'],
  490. "CONTACT_TELEPHONE" => ['required', 'max:11'],
  491. "CONTACT_LADA" => ['required', 'max:5'],
  492. "CONTACT_ADDRESS" => ['required', 'max:100'],
  493. "CONTRACT_TYPE" => ['required'],
  494. "SPECIALITY" => ['required', 'max:75'],
  495. "SUBCONTRATIST_ID" => ['max:10'],
  496. "SAVED_BY_USER" => ['required', 'digits:10'],
  497. "LINE_NUMBER" => ['required', 'digits:1']
  498. ]);
  499. if ($validator->fails()) {
  500. return $this->response_controller->makeResponse(
  501. TRUE,
  502. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  503. $this->response_controller->makeErrors($validator->errors()->messages()),
  504. 400
  505. );
  506. }
  507. // Busca en la base si existe otro empleado con ese usuario
  508. $uniq_user = DB::table('S002V01TPERS')
  509. ->select("PERS_IDPE")
  510. ->where('PERS_IDUS', '=', $request->USER_ID)
  511. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  512. ->first();
  513. // Verifica si el objeto contiene algo
  514. if (isset($uniq_user) && !empty($uniq_user)) {
  515. return $this->response_controller
  516. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: El usuario ya está registrado como empleado', [], 500);
  517. }
  518. // Busca si el usuario existe
  519. $user_exist = DB::table('S002V01TUSUA')
  520. ->select("USUA_IDUS")
  521. ->where('USUA_IDUS', '=', $request->USER_ID)
  522. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  523. ->first();
  524. // Verifica si el objeto esta vacio
  525. if (!isset($user_exist) && empty($user_exist)) {
  526. return $this->response_controller
  527. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: No se encontró al usuario', [], 500);
  528. }
  529. // Busca si el equipo de trabajo existe
  530. $team_found = DB::table('S002V01TEQMA')
  531. ->select('EQMA_NOMB')
  532. ->where('EQMA_IDEQ', '=', $request->WORKTEAM_ID)
  533. ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
  534. ->first();
  535. // Verifica si el objeto esta vacio
  536. if (!isset($team_found) && empty($team_found)) {
  537. return $this->response_controller
  538. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG004: No se encontró al equipo de trabajo', [], 500);
  539. }
  540. $user_register = DB::table('S002V01TUSUA')
  541. ->select('USUA_IDUS as ID_USER')
  542. ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
  543. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  544. ->first();
  545. // Verifica si el objeto esta vacio
  546. if (!isset($user_register) && empty($user_register)) {
  547. return $this->response_controller
  548. ->makeResponse(TRUE, "ERR_USUARIO_REG005: Tu usuario no es válido para registrar empleados", [], 500);
  549. }
  550. DB::beginTransaction(); # Para impedir que las actualizaciones queden a incompletas
  551. $insert_employee = DB::table('S002V01TPERS')
  552. ->insert([
  553. "PERS_IDUS" => $request->USER_ID,
  554. "PERS_NOCE" => trim($request->CONTACT_NAME),
  555. "PERS_NUTC" => $request->CONTACT_TELEPHONE,
  556. "PERS_LATC" => $request->CONTACT_LADA,
  557. "PERS_DICE" => trim($request->CONTACT_ADDRESS),
  558. "PERS_TICO" => trim($request->CONTRACT_TYPE),
  559. "PERS_ESPE" => trim($request->SPECIALITY),
  560. "PERS_IDPS" => $request->SUBCONTRATIST_ID,
  561. "PERS_NULI" => $request->LINE_NUMBER,
  562. "PERS_ESTA" => "Activo",
  563. "PERS_USRE" => $request->SAVED_BY_USER,
  564. "PERS_FERE" => $REGISTER_DATE,
  565. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  566. ]);
  567. // Verifica que la inserción del empleado se haya hecho correctamente
  568. if (!$insert_employee) {
  569. return $this->response_controller
  570. ->makeResponse(TRUE, 'ERR_PERSONAL_REG006: Algo salió mal, error registrando al empleado', [], 500);
  571. }
  572. // Obtiene el ID del empleado registrado
  573. $employee_id = DB::table('S002V01TPERS')
  574. ->select('PERS_IDPE as EMPLOYEE_ID')
  575. ->where('PERS_IDUS', '=', $request->USER_ID)
  576. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  577. ->first();
  578. // Saca el ID del objeto
  579. $employee_id = $employee_id->EMPLOYEE_ID;
  580. $insert_employee_on_workteam = DB::table('S002V01TPEEM')
  581. ->insert([
  582. "PEEM_IDPE" => $employee_id,
  583. "PEEM_IDEM" => $request->WORKTEAM_ID,
  584. "PEEM_NULI" => $request->LINE_NUMBER,
  585. "PEEM_ESTA" => "Activo",
  586. "PEEM_USRE" => $request->SAVED_BY_USER,
  587. "PEEM_FERE" => $REGISTER_DATE,
  588. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
  589. ]);
  590. // Verifica que la inserción del empleado en el equipo de trabajo se haya hecho correctamente
  591. if (!$insert_employee_on_workteam) {
  592. DB::rollBack(); # Si no se logra insertar al equipo, se revierten los cambios previos
  593. return $this->response_controller
  594. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG007: Algo salió mal, error registrando al empleado en el equipo', [], 500);
  595. }
  596. // Verifica si el objeto esta vacio
  597. if (isset($request->DOCUMENTS_AUTHO) && !empty($request->DOCUMENTS_AUTHO)) {
  598. $doc = $request->DOCUMENTS_AUTHO;
  599. // Se obtiene el nombre del archivo con su extensión
  600. $completeFileName = $doc->getClientOriginalName();
  601. // Se obtiene únicamente el nombre
  602. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  603. // Se obtiene la extensión del archivo
  604. $extension = $doc->getClientOriginalExtension();
  605. if ($extension != "pdf") {
  606. return $this->response_controller
  607. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  608. }
  609. // Se quitan los espacios y se concatena datos para ser guardado
  610. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  611. $name_document = $this->documents_controller->createDocument(
  612. "GPRS",
  613. "IN",
  614. $final_part_name_document,
  615. $employee_id,
  616. 'pdf',
  617. $request->LINE_NUMBER,
  618. $request->SAVED_BY_USER
  619. );
  620. // El documento es guardado en el storage
  621. $doc->storeAs('public/pdf_documents', $name_document);
  622. }
  623. // Verifica si el objeto esta vacio
  624. if (isset($request->DOCUMENTS_AUTHO2) && !empty($request->DOCUMENTS_AUTHO2)) {
  625. $doc = $request->DOCUMENTS_AUTHO2;
  626. // Se obtiene el nombre del archivo con su extensión
  627. $completeFileName = $doc->getClientOriginalName();
  628. // Se obtiene únicamente el nombre
  629. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  630. // Se obtiene la extensión del archivo
  631. $extension = $doc->getClientOriginalExtension();
  632. if ($extension != "pdf") {
  633. return $this->response_controller
  634. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  635. }
  636. // Se quitan los espacios y se concatena datos para ser guardado
  637. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  638. $name_document = $this->documents_controller->createDocument(
  639. "GPRS",
  640. "IN",
  641. $final_part_name_document,
  642. $employee_id,
  643. 'pdf',
  644. $request->LINE_NUMBER,
  645. $request->SAVED_BY_USER
  646. );
  647. // El documento es guardado en el storage
  648. $doc->storeAs('public/pdf_documents', $name_document);
  649. }
  650. // Verifica si el objeto esta vacio
  651. if (isset($request->DOCUMENTS_CERT) && !empty($request->DOCUMENTS_CERT)) {
  652. $doc = $request->DOCUMENTS_CERT;
  653. // Se obtiene el nombre del archivo con su extensión
  654. $completeFileName = $doc->getClientOriginalName();
  655. // Se obtiene únicamente el nombre
  656. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  657. // Se obtiene la extensión del archivo
  658. $extension = $doc->getClientOriginalExtension();
  659. if ($extension != "pdf") {
  660. return $this->response_controller
  661. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  662. }
  663. // Se quitan los espacios y se concatena datos para ser guardado
  664. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  665. $name_document = $this->documents_controller->createDocument(
  666. "GPRS",
  667. "CE",
  668. $final_part_name_document,
  669. $employee_id,
  670. 'pdf',
  671. $request->LINE_NUMBER,
  672. $request->SAVED_BY_USER
  673. );
  674. // El documento es guardado en el storage
  675. $doc->storeAs('public/pdf_documents', $name_document);
  676. }
  677. // Verifica si el objeto esta vacio
  678. if (isset($request->DOCUMENTS_CERT2) && !empty($request->DOCUMENTS_CERT2)) {
  679. $doc = $request->DOCUMENTS_CERT2;
  680. // Se obtiene el nombre del archivo con su extensión
  681. $completeFileName = $doc->getClientOriginalName();
  682. // Se obtiene únicamente el nombre
  683. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  684. // Se obtiene la extensión del archivo
  685. $extension = $doc->getClientOriginalExtension();
  686. if ($extension != "pdf") {
  687. return $this->response_controller
  688. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  689. }
  690. // Se quitan los espacios y se concatena datos para ser guardado
  691. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  692. $name_document = $this->documents_controller->createDocument(
  693. "GPRS",
  694. "CE",
  695. $final_part_name_document,
  696. $employee_id,
  697. 'pdf',
  698. $request->LINE_NUMBER,
  699. $request->SAVED_BY_USER
  700. );
  701. // El documento es guardado en el storage
  702. $doc->storeAs('public/pdf_documents', $name_document);
  703. }
  704. // Verifica si el objeto esta vacio
  705. if (isset($request->DOCUMENT_OFFICE) && !empty($request->DOCUMENT_OFFICE)) {
  706. $doc = $request->DOCUMENT_OFFICE;
  707. // Se obtiene el nombre del archivo con su extensión
  708. $completeFileName = $doc->getClientOriginalName();
  709. // Se obtiene únicamente el nombre
  710. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $employee_id;
  711. // Se obtiene la extensión del archivo
  712. $extension = $doc->getClientOriginalExtension();
  713. if ($extension != "pdf") {
  714. return $this->response_controller
  715. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  716. }
  717. // Se quitan los espacios y se concatena datos para ser guardado
  718. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  719. $name_document = $this->documents_controller->createDocument(
  720. "GPRS",
  721. "CO",
  722. $final_part_name_document,
  723. $employee_id,
  724. 'pdf',
  725. $request->LINE_NUMBER,
  726. $request->SAVED_BY_USER
  727. );
  728. // El documento es guardado en el storage
  729. $doc->storeAs('public/pdf_documents', $name_document);
  730. }
  731. DB::commit(); # Para guardar los cambios en la base de datos
  732. return $this->response_controller->makeResponse(FALSE, 'Creación exitosa', 200);
  733. } catch (Throwable $th) {
  734. return $this->response_controller
  735. ->makeResponse(TRUE, 'ERR_PERSONAL_REG008: Error inesperado', strtoupper($th), 500);
  736. }
  737. }
  738. // Metodo para obtener un empleado por id con sus documentos (Pensado: 1 empleado solo tiene un equipo de trabajo)
  739. public function getEmployeeById($id_employee, $line_number)
  740. {
  741. try {
  742. $employee = DB::table('S002V01TPERS')
  743. ->select(
  744. 'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
  745. 'S002V01TPERS.PERS_IDUS as USER_ID',
  746. 'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
  747. 'S002V01TPERS.PERS_IDPS as SUBCONTRATIST_ID',
  748. 'S002V01TEQMA.EQMA_NOMB as WORKTEAM_NAME',
  749. 'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
  750. 'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
  751. 'S002V01TPERS.PERS_LATC as CONTACT_LADA',
  752. 'S002V01TPERS.PERS_DICE as CONTACT_ADDRESS',
  753. 'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
  754. 'S002V01TPERS.PERS_ESPE as SPECIALITY',
  755. 'S002V01TPERS.PERS_NULI as LINE_NUMBER',
  756. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) as EMPLOYEE_NAME')
  757. )
  758. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  759. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  760. ->where('s002v01TPEEM.PEEM_NULI', '=', $line_number)
  761. ->where('s002v01TEQMA.EQMA_NULI', '=', $line_number)
  762. ->where('s002v01TUSUA.USUA_NULI', '=', $line_number)
  763. ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
  764. ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
  765. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  766. ->first();
  767. // Verifica si el objeto esta vacio
  768. if (!isset($employee) && empty($employee)) {
  769. return $this->response_controller
  770. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  771. }
  772. $employee->CONTACT_NAME = $this->encrypt_controller->encrypt($employee->CONTACT_NAME);
  773. $employee->CONTACT_TELEPHONE = $this->encrypt_controller->encrypt($employee->CONTACT_TELEPHONE);
  774. $employee->CONTACT_LADA = $this->encrypt_controller->encrypt($employee->CONTACT_LADA);
  775. $employee->CONTACT_ADDRESS = $this->encrypt_controller->encrypt($employee->CONTACT_ADDRESS);
  776. $employee->DOCUMENTS = [];
  777. // Obtiene los documentos de un empleado
  778. $documents_of_employee = DB::table('S002V01TDOCU_P')
  779. ->select('DOCU_LIDO as DOCUMENT')
  780. ->where('DOCU_IDPE', '=', $id_employee)
  781. ->where('DOCU_NULI', '=', $line_number)
  782. ->get();
  783. // Verifica si el objeto contiene algo
  784. if (isset($documents_of_employee[0]) && !empty($documents_of_employee[0])) {
  785. foreach ($documents_of_employee as $doc) {
  786. $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
  787. }
  788. }
  789. return $this->response_controller
  790. ->makeResponse(FALSE, "Consulta exitosa", $employee);
  791. } catch (Throwable $th) {
  792. return $this->response_controller
  793. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
  794. }
  795. }
  796. // Metodo para obtener todos los empleados con sus documentos (Pensado: 1 empleado solo tiene un equipo de trabajo)
  797. public function getAllEmployees($line_number)
  798. {
  799. try {
  800. $employees = DB::table('S002V01TPERS')
  801. ->select(
  802. 'S002V01TPERS.PERS_IDPE as EMPLOYEE_ID',
  803. 'S002V01TPERS.PERS_IDUS as USER_ID',
  804. 'S002V01TEQMA.EQMA_IDEQ as WORKTEAM_ID',
  805. 'S002V01TPERS.PERS_NOCE as CONTACT_NAME',
  806. 'S002V01TPERS.PERS_NUTC as CONTACT_TELEPHONE',
  807. 'S002V01TPERS.PERS_LATC as CONTACT_LADA',
  808. 'S002V01TPERS.PERS_DICE as CONTACT_ADDRESS',
  809. 'S002V01TPERS.PERS_TICO as CONTRACT_TYPE',
  810. 'S002V01TPERS.PERS_ESPE as SPECIALITY',
  811. )
  812. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  813. ->where('S002V01TPEEM.PEEM_NULI', '=', $line_number)
  814. ->where('S002V01TEQMA.EQMA_NULI', '=', $line_number)
  815. ->join('S002V01TPEEM', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPEEM.PEEM_IDPE')
  816. ->join('S002V01TEQMA', 'S002V01TPEEM.PEEM_IDEM', '=', 'S002V01TEQMA.EQMA_IDEQ')
  817. ->get();
  818. // Verifica si el objeto esta vacio
  819. if (!isset($employees[0]) && empty($employees[0])) {
  820. return $this->response_controller
  821. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontraron datos', [], 500);
  822. }
  823. foreach ($employees as $employee) {
  824. $employee->CONTACT_NAME = $this->encrypt_controller->encrypt($employee->CONTACT_NAME);
  825. $employee->CONTACT_TELEPHONE = $this->encrypt_controller->encrypt($employee->CONTACT_TELEPHONE);
  826. $employee->CONTACT_LADA = $this->encrypt_controller->encrypt($employee->CONTACT_LADA);
  827. $employee->CONTACT_ADDRESS = $this->encrypt_controller->encrypt($employee->CONTACT_ADDRESS);
  828. $employee->DOCUMENTS = [];
  829. }
  830. // Obtiene los documentos
  831. $documents_of_employees = DB::table('S002V01TDOCU_P')
  832. ->select('DOCU_LIDO as DOCUMENT', 'DOCU_IDPE as EMPLOYEE_ID')
  833. ->where('DOCU_NULI', '=', $line_number)
  834. ->get();
  835. // Verifica si el objeto esta vacio
  836. if (isset($documents_of_employees[0]) && !empty($documents_of_employees[0])) {
  837. // Asigna al empleado los documentos que le pertenezcan
  838. foreach ($employees as $employee) {
  839. foreach ($documents_of_employees as $doc) {
  840. if ($employee->EMPLOYEE_ID == $doc->EMPLOYEE_ID) {
  841. $employee->DOCUMENTS[] = $this->encrypt_controller->encrypt($doc->DOCUMENT);
  842. }
  843. }
  844. }
  845. }
  846. return $this->response_controller
  847. ->makeResponse(FALSE, "Consulta exitosa", $employees);
  848. } catch (Throwable $th) {
  849. return $this->response_controller
  850. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
  851. }
  852. }
  853. // Metodo para actualizar un empleado
  854. public function updateEmployee(Request $request, $id_employee)
  855. {
  856. try {
  857. $save_option = $request->UPLOAD_NEW_DOCUMENTS != "N";
  858. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  859. $UPDATE_DATE = Carbon::now()->timezone('America/Mexico_City')->toDateTimeString();
  860. $request['CONTACT_NAME'] = $this->encrypt_controller->decrypt($request->CONTACT_NAME);
  861. $request['CONTACT_TELEPHONE'] = $this->encrypt_controller->decrypt($request->CONTACT_TELEPHONE);
  862. $request['CONTACT_LADA'] = $this->encrypt_controller->decrypt($request->CONTACT_LADA);
  863. $request['CONTACT_ADDRESS'] = $this->encrypt_controller->decrypt($request->CONTACT_ADDRESS);
  864. $validator = Validator::make($request->all(), [
  865. "USER_ID" => ['required', 'digits:10'],
  866. "WORKTEAM_ID" => ['required', 'digits:10'],
  867. "CONTACT_NAME" => ['required', 'max:150'],
  868. "CONTACT_TELEPHONE" => ['required', 'max:11'],
  869. "CONTACT_LADA" => ['required', 'max:5'],
  870. "CONTACT_ADDRESS" => ['required', 'max:100'],
  871. "CONTRACT_TYPE" => ['required'],
  872. "SPECIALITY" => ['required', 'max:75'],
  873. "SUBCONTRATIST_ID" => ['max:10'],
  874. "SAVED_BY_USER" => ['required', 'digits:10'],
  875. "LINE_NUMBER" => ['required', 'digits:1']
  876. ]);
  877. if ($validator->fails()) {
  878. return $this->response_controller->makeResponse(
  879. TRUE,
  880. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  881. $this->response_controller->makeErrors($validator->errors()->messages()),
  882. 400
  883. );
  884. }
  885. // Busca al empleado si existe
  886. $employee_exist = DB::table('S002V01TPERS')
  887. ->select('PERS_IDPE')
  888. ->where('PERS_IDPE', '=', $id_employee)
  889. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  890. ->first();
  891. // Verifica si el objeto esta vacio
  892. if (!isset($employee_exist) && empty($employee_exist)) {
  893. return $this->response_controller
  894. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: No se encontró al empleado', [], 500);
  895. }
  896. // Busca al equipo de trabajo si existe
  897. $team_found = DB::table('S002V01TEQMA')
  898. ->select('EQMA_NOMB')
  899. ->where('EQMA_IDEQ', '=', $request->WORKTEAM_ID)
  900. ->where('EQMA_NULI', '=', $request->LINE_NUMBER)
  901. ->first();
  902. // Verifica si el objeto esta vacio
  903. if (!isset($team_found) && empty($team_found)) {
  904. return $this->response_controller
  905. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG003: No se encontró al equipo de trabajo', [], 500);
  906. }
  907. $user_register = DB::table('S002V01TUSUA')
  908. ->select('USUA_IDUS as ID_USER')
  909. ->where('USUA_IDUS', '=', $request->SAVED_BY_USER)
  910. ->where('USUA_NULI', '=', $request->LINE_NUMBER)
  911. ->first();
  912. // Verifica si el objeto esta vacio
  913. if (!isset($user_register) && empty($user_register)) {
  914. return $this->response_controller
  915. ->makeResponse(TRUE, "ERR_USUARIO_REG004: Tu usuario no es válido para actualizar empleados", [], 500);
  916. }
  917. DB::beginTransaction(); # Para impedir que las actualizaciones queden incompletas
  918. $update_employee = DB::table('S002V01TPERS')
  919. ->where('PERS_IDPE', '=', $id_employee)
  920. ->where('PERS_NULI', '=', $request->LINE_NUMBER)
  921. ->update([
  922. "PERS_IDUS" => $request->USER_ID,
  923. "PERS_NOCE" => trim($request->CONTACT_NAME),
  924. "PERS_NUTC" => $request->CONTACT_TELEPHONE,
  925. "PERS_LATC" => $request->CONTACT_LADA,
  926. "PERS_DICE" => trim($request->CONTACT_ADDRESS),
  927. "PERS_TICO" => trim($request->CONTRACT_TYPE),
  928. "PERS_ESPE" => trim($request->SPECIALITY),
  929. "PERS_IDPS" => $request->SUBCONTRATIST_ID,
  930. "PERS_ESTA" => "Activo",
  931. "PERS_USMO" => $request->SAVED_BY_USER,
  932. "PERS_FEMO" => $UPDATE_DATE,
  933. "PERS_FEAR" => DB::raw('CURRENT_TIMESTAMP')
  934. ]);
  935. // Verifica que la actualización del empleado haya sido satisfactoria
  936. if ($update_employee < 1) {
  937. return $this->response_controller
  938. ->makeResponse(TRUE, 'ERR_PERSONAL_REG005: Algo salió mal, error actualizando al empleado', [], 500);
  939. }
  940. $update_employee_on_workteam = DB::table('S002V01TPEEM')
  941. ->where('PEEM_IDPE', '=', $id_employee)
  942. ->where('PEEM_NULI', '=', $request->LINE_NUMBER)
  943. ->update([
  944. "PEEM_IDEM" => $request->WORKTEAM_ID,
  945. "PEEM_ESTA" => "Activo",
  946. "PEEM_USRE" => $request->SAVED_BY_USER,
  947. "PEEM_FERE" => $UPDATE_DATE,
  948. "PEEM_FEAR" => DB::raw('CURRENT_TIMESTAMP'),
  949. ]);
  950. // Verifica que la actualización del cambio de equipo del empleado haya sido satisfactoria
  951. if ($update_employee_on_workteam < 1) {
  952. DB::rollBack(); # Si no se logra actualizar el equipo, se revierten los cambios previos
  953. return $this->response_controller
  954. ->makeResponse(TRUE, 'ERR_EQUIPO_TRABAJO_REG006: Algo salió mal, error cambiando al empleado de equipo', [], 500);
  955. }
  956. // Verifica si el objeto esta vacio
  957. if (isset($request->DOCUMENTS_AUTHO) && !empty($request->DOCUMENTS_AUTHO)) {
  958. $doc = $request->DOCUMENTS_AUTHO;
  959. // Se obtiene el nombre del archivo con su extensión
  960. $completeFileName = $doc->getClientOriginalName();
  961. // Se obtiene únicamente el nombre
  962. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  963. // Se obtiene la extensión del archivo
  964. $extension = $doc->getClientOriginalExtension();
  965. if ($extension != "pdf") {
  966. return $this->response_controller
  967. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  968. }
  969. // Se quitan los espacios y se concatena datos para ser guardado
  970. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  971. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  972. $name_document = $this->documents_controller->createDocument(
  973. "GPRS",
  974. "IN",
  975. $final_part_name_document,
  976. $id_employee,
  977. 'pdf',
  978. $request->LINE_NUMBER,
  979. $request->SAVED_BY_USER,
  980. $request->DOCUMENTS_AUTHO_UPDATE
  981. );
  982. // El documento es guardado en el storage
  983. $doc->storeAs('public/pdf_documents', $name_document);
  984. }
  985. // Verifica si el objeto esta vacio
  986. if (isset($request->DOCUMENTS_AUTHO2) && !empty($request->DOCUMENTS_AUTHO2)) {
  987. $doc = $request->DOCUMENTS_AUTHO2;
  988. // Se obtiene el nombre del archivo con su extensión
  989. $completeFileName = $doc->getClientOriginalName();
  990. // Se obtiene únicamente el nombre
  991. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  992. // Se obtiene la extensión del archivo
  993. $extension = $doc->getClientOriginalExtension();
  994. if ($extension != "pdf") {
  995. return $this->response_controller
  996. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  997. }
  998. // Se quitan los espacios y se concatena datos para ser guardado
  999. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1000. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1001. $name_document = $this->documents_controller->createDocument(
  1002. "GPRS",
  1003. "IN",
  1004. $final_part_name_document,
  1005. $id_employee,
  1006. 'pdf',
  1007. $request->LINE_NUMBER,
  1008. $request->SAVED_BY_USER,
  1009. $request->DOCUMENTS_AUTHO2_UPDATE
  1010. );
  1011. // El documento es guardado en el storage
  1012. $doc->storeAs('public/pdf_documents', $name_document);
  1013. }
  1014. // Verifica si el objeto esta vacio
  1015. if (isset($request->DOCUMENTS_CERT) && !empty($request->DOCUMENTS_CERT)) {
  1016. $doc = $request->DOCUMENTS_CERT;
  1017. // Se obtiene el nombre del archivo con su extensión
  1018. $completeFileName = $doc->getClientOriginalName();
  1019. // Se obtiene únicamente el nombre
  1020. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  1021. // Se obtiene la extensión del archivo
  1022. $extension = $doc->getClientOriginalExtension();
  1023. if ($extension != "pdf") {
  1024. return $this->response_controller
  1025. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  1026. }
  1027. // Se quitan los espacios y se concatena datos para ser guardado
  1028. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1029. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1030. $name_document = $this->documents_controller->createDocument(
  1031. "GPRS",
  1032. "CE",
  1033. $final_part_name_document,
  1034. $id_employee,
  1035. 'pdf',
  1036. $request->LINE_NUMBER,
  1037. $request->SAVED_BY_USER,
  1038. $request->DOCUMENTS_CERT_UPDATE
  1039. );
  1040. // El documento es guardado en el storage
  1041. $doc->storeAs('public/pdf_documents', $name_document);
  1042. }
  1043. // Verifica si el objeto esta vacio
  1044. if (isset($request->DOCUMENTS_CERT2) && !empty($request->DOCUMENTS_CERT2)) {
  1045. $doc = $request->DOCUMENTS_CERT2;
  1046. // Se obtiene el nombre del archivo con su extensión
  1047. $completeFileName = $doc->getClientOriginalName();
  1048. // Se obtiene únicamente el nombre
  1049. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  1050. // Se obtiene la extensión del archivo
  1051. $extension = $doc->getClientOriginalExtension();
  1052. if ($extension != "pdf") {
  1053. return $this->response_controller
  1054. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  1055. }
  1056. // Se quitan los espacios y se concatena datos para ser guardado
  1057. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1058. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1059. $name_document = $this->documents_controller->createDocument(
  1060. "GPRS",
  1061. "CE",
  1062. $final_part_name_document,
  1063. $id_employee,
  1064. 'pdf',
  1065. $request->LINE_NUMBER,
  1066. $request->SAVED_BY_USER,
  1067. $request->DOCUMENTS_CERT2_UPDATE
  1068. );
  1069. // El documento es guardado en el storage
  1070. $doc->storeAs('public/pdf_documents', $name_document);
  1071. }
  1072. // Verifica si el objeto esta vacio
  1073. if (isset($request->DOCUMENT_OFFICE) && !empty($request->DOCUMENT_OFFICE)) {
  1074. $doc = $request->DOCUMENT_OFFICE;
  1075. // Se obtiene el nombre del archivo con su extensión
  1076. $completeFileName = $doc->getClientOriginalName();
  1077. // Se obtiene únicamente el nombre
  1078. $fileNameOnly = pathinfo($completeFileName, PATHINFO_FILENAME) . '-' . $id_employee;
  1079. // Se obtiene la extensión del archivo
  1080. $extension = $doc->getClientOriginalExtension();
  1081. if ($extension != "pdf") {
  1082. return $this->response_controller
  1083. ->makeResponse(TRUE, 'ERR_DOCUMENTO_REG007: Solo se permiten archivos PDF', [], 500);
  1084. }
  1085. // Se quitan los espacios y se concatena datos para ser guardado
  1086. $final_part_name_document = str_replace(' ', '_', $fileNameOnly) . '.' . $extension;
  1087. $final_part_name_document = $this->documents_controller->deleteCodificationStructureName($final_part_name_document, "01", "GPRS");
  1088. $name_document = $this->documents_controller->createDocument(
  1089. "GPRS",
  1090. "CO",
  1091. $final_part_name_document,
  1092. $id_employee,
  1093. 'pdf',
  1094. $request->LINE_NUMBER,
  1095. $request->SAVED_BY_USER,
  1096. $request->DOCUMENT_OFFICE_UPDATE
  1097. );
  1098. // El documento es guardado en el storage
  1099. $doc->storeAs('public/pdf_documents', $name_document);
  1100. }
  1101. DB::commit(); # Para guardar los cambios en la base de datos
  1102. return $this->response_controller->makeResponse(FALSE, 'Actualización exitosa', 200);
  1103. } catch (Throwable $th) {
  1104. return $this->response_controller
  1105. ->makeResponse(TRUE, 'ERR_PERSONAL_REG008: Error inesperado', strtoupper($th), 500);
  1106. }
  1107. }
  1108. // Metodo para obtener la cantidad de contratos otorgados a cada empleado
  1109. public function getContractsOfEveryEmployee($line_number)
  1110. {
  1111. try {
  1112. // Obtiene la cantidad de contratos que tiene cada empleado
  1113. $contracts_by_employee = DB::table('S002V01TPERS')
  1114. ->select(
  1115. 'S002V01TPERS.PERS_IDPE as ID_EMPLOYEE',
  1116. DB::raw('TRIM(CONCAT(S002V01TUSUA.USUA_NOMB, " " , S002V01TUSUA.USUA_APPA, " ", COALESCE(S002V01TUSUA.USUA_APMA,""))) AS NAME'),
  1117. DB::raw(
  1118. 'COUNT(S002V01TPECO.PECO_IDPE) AS CONTRACTS_COUNT',
  1119. )
  1120. )
  1121. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  1122. ->where('S002V01TUSUA.USUA_NULI', '=', $line_number)
  1123. ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
  1124. ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
  1125. ->groupBy('S002V01TPERS.PERS_IDPE', 'NAME', 'S002V01TPECO.PECO_IDPE')
  1126. ->join('S002V01TUSUA', 'S002V01TPERS.PERS_IDUS', '=', 'S002V01TUSUA.USUA_IDUS')
  1127. ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
  1128. ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
  1129. ->get();
  1130. // Verifica si el objeto esta vacio
  1131. if (!isset($contracts_by_employee[0]) && empty($contracts_by_employee[0])) {
  1132. return $this->response_controller
  1133. ->makeResponse(TRUE, 'ERR_PERSONAL_CONTRATO_REG001: No se encontraron datos', [], 500);
  1134. }
  1135. return $this->response_controller
  1136. ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
  1137. } catch (Throwable $th) {
  1138. return $this->response_controller
  1139. ->makeResponse(TRUE, 'ERR_PERSONAL_REG002: Error inesperado', strtoupper($th->getMessage()), 500);
  1140. }
  1141. }
  1142. // Metodo para obtener detalles acerca de los contratos otorgados al empleado
  1143. public function getDetailsOfContractsByEmployee($id_employee, $line_number)
  1144. {
  1145. try {
  1146. // Busca al empleado si existe
  1147. $employee_exist = DB::table('S002V01TPERS')
  1148. ->select('PERS_IDPE')
  1149. ->where('PERS_IDPE', '=', $id_employee)
  1150. ->where('PERS_NULI', '=', $line_number)
  1151. ->first();
  1152. // Verifica si el objeto esta vacio
  1153. if (!isset($employee_exist) && empty($employee_exist)) {
  1154. return $this->response_controller
  1155. ->makeResponse(TRUE, 'ERR_PERSONAL_REG001: No se encontró al empleado', [], 500);
  1156. }
  1157. //Obtiene los contratos pertenecientes al subcontratista deseado
  1158. $contracts_by_employee = DB::table('S002V01TPERS')
  1159. ->orderBy("S002V01TCONT.CONT_FEIN", 'desc')
  1160. ->where('S002V01TPERS.PERS_IDPE', '=', $id_employee)
  1161. ->where('S002V01TPERS.PERS_NULI', '=', $line_number)
  1162. ->where('S002V01TPECO.PECO_NULI', '=', $line_number)
  1163. ->where('S002V01TCONT.CONT_NULI', '=', $line_number)
  1164. ->select('S002V01TCONT.CONT_FEIN as START_DATE', 'S002V01TCONT.CONT_FEFI as END_DATE', 'S002V01TCONT.CONT_COST as CONTRACT_COST')
  1165. ->join('S002V01TPECO', 'S002V01TPERS.PERS_IDPE', '=', 'S002V01TPECO.PECO_IDPE')
  1166. ->join('S002V01TCONT', 'S002V01TPECO.PECO_IDCO', '=', 'S002V01TCONT.CONT_IDCO')
  1167. ->get();
  1168. // Verifica si el objeto esta vacio
  1169. if (!isset($contracts_by_employee[0]) && empty($contracts_by_employee[0])) {
  1170. return $this->response_controller
  1171. ->makeResponse(TRUE, 'ERR_PERSONAL_CONTRATO_REG002: Empleado sin contratos', $contracts_by_employee, 500);
  1172. }
  1173. foreach ($contracts_by_employee as $contract) {
  1174. $contract->START_DATE = Carbon::create($contract->START_DATE)->format("d-m-Y h:i:s A");
  1175. $contract->END_DATE = Carbon::create($contract->END_DATE)->format("d-m-Y h:i:s A");
  1176. $contract->CONTRACT_COST = $this->encrypt_controller->encrypt($contract->CONTRACT_COST);
  1177. }
  1178. return $this->response_controller
  1179. ->makeResponse(FALSE, "Consulta exitosa", $contracts_by_employee);
  1180. } catch (Throwable $th) {
  1181. return $this->response_controller
  1182. ->makeResponse(TRUE, 'ERR_PERSONAL_REG003: Error inesperado', strtoupper($th->getMessage()), 500);
  1183. }
  1184. }
  1185. // Metodo para la descarga de archivo excel con los detalles del empleado
  1186. public function downoloadEmployeeInfoOnExcel(Request $request)
  1187. {
  1188. try {
  1189. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  1190. $employee_id = $request->EMPLOYEE['ID_EMPLOYEE'];
  1191. $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".xlsx";
  1192. // Crea el documento con los datos del request
  1193. $document = $this->createDocument($request);
  1194. // Busca la ultima versión del documento que se haya insertado
  1195. $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'excel');
  1196. if ($old_document_name != null) {
  1197. // Obtiene el nombre del documento que tiene el mismo contenido
  1198. $old_document_name = $this->documents_controller->sameDocumentsExcel($document, $old_document_name);
  1199. // Si no hay ningun cambio en el documento, se descarga la ultima versión
  1200. if ($old_document_name != null) {
  1201. return $this->response_controller
  1202. ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($old_document_name), 200);
  1203. }
  1204. }
  1205. // Guarda el documento creado en la variable
  1206. $writer = IOFactory::createWriter($document, 'Xlsx');
  1207. $content = tmpfile();
  1208. $writer->save($content);
  1209. // Inserta la nueva version del documento en la base de datos y en el storage
  1210. $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, $employee_id, "excel", $request->EMPLOYEE['LINE_NUMBER'], $request->SAVED_BY_USER);
  1211. Storage::disk('excel')->put(
  1212. $name_document,
  1213. $content
  1214. );
  1215. return $this->response_controller
  1216. ->makeResponse(False, 'Éxito', Storage::disk('excel')->url($name_document), 200);
  1217. } catch (Throwable $th) {
  1218. return $this->response_controller
  1219. ->makeResponse(TRUE, 'ERR_EXCEL_REG001: Error inesperado', strtoupper($th), 500);
  1220. }
  1221. }
  1222. // Metodo para la descarga de archivo pdf con los detalles del empleado
  1223. public function downoloadEmployeeInfoOnPdf(Request $request)
  1224. {
  1225. try {
  1226. $request['SAVED_BY_USER'] = $this->encrypt_controller->decrypt($request->SAVED_BY_USER);
  1227. $employee_id = $request->EMPLOYEE['ID_EMPLOYEE'];
  1228. $final_part_name_document = "Details_Of_Employee_" . $employee_id . ".pdf";
  1229. // Crea el documento
  1230. $document = $this->createDocument($request);
  1231. $writer = IOFactory::createWriter($document, 'Mpdf');
  1232. $content = tmpfile();
  1233. // Busca la ultima versión del documento que se haya insertado
  1234. $old_document_name = $this->documents_controller->getDocumentsWithSameName($final_part_name_document, 'pdf');
  1235. $writer->save($content);
  1236. if ($old_document_name != null) {
  1237. // Obtiene el nombre del documento que tiene el mismo contenido
  1238. $old_document_name = $this->documents_controller->sameDocumentsPdf($content, $old_document_name);
  1239. // Si no hay ningun cambio en el documento, se descarga la ultima versión
  1240. if ($old_document_name != null) {
  1241. return $this->response_controller
  1242. ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($old_document_name), 200);
  1243. }
  1244. }
  1245. // Inserta la nueva version del documento en la base de datos y en el storage
  1246. $name_document = $this->documents_controller->createDocument("GPRS", "IN", $final_part_name_document, $employee_id, "pdf", $request->EMPLOYEE['LINE_NUMBER'], $request->SAVED_BY_USER);
  1247. Storage::disk('pdf')->put(
  1248. $name_document,
  1249. $content
  1250. );
  1251. return $this->response_controller
  1252. ->makeResponse(False, 'Éxito', Storage::disk('pdf')->url($name_document), 200);
  1253. } catch (Throwable $th) {
  1254. return $this->response_controller
  1255. ->makeResponse(TRUE, 'ERR_PDF_REG001: Error inesperado', strtoupper($th), 500);
  1256. }
  1257. }
  1258. // Metodo para la creación de archivo
  1259. public function createDocument(Request $request)
  1260. {
  1261. try {
  1262. $employee = $request->EMPLOYEE;
  1263. $document = new Spreadsheet();
  1264. // Propiedades del documento
  1265. $document->getProperties()
  1266. ->setCreator("ITTEC")
  1267. ->setTitle("Detalles del empleado")
  1268. ->setDescription("Detalles de solo un empleado.")
  1269. ->setKeywords("Empleado Detalles")
  1270. ->setCategory("Empleado Detalles Pdf");
  1271. // Cambia la hoja a horizontal par que se observen mejor los datos
  1272. $document->getActiveSheet()->getPageSetup()->setOrientation("landscape");
  1273. // Hace la escritura dentro del archivo
  1274. $start_row = 2; # Indica desde que fila inicia la tabla
  1275. $start_col = "B"; # Indica desde que columna inicia la tabla
  1276. $col = $start_col;
  1277. $row = $start_row;
  1278. $col++;
  1279. $second_col = $col;
  1280. $col++;
  1281. $third_col = $col;
  1282. $col++;
  1283. $fourth_col = $col;
  1284. $col++;
  1285. $fifth_col = $col;
  1286. $col++;
  1287. $sixth_col = $col;
  1288. $col++;
  1289. $seventh_col = $col;
  1290. $col++;
  1291. $eight_col = $col;
  1292. $col = $start_col;
  1293. $final_col = "";
  1294. for ($i = 0; $i < 9; $i++) {
  1295. $final_col = $col;
  1296. $col++;
  1297. }
  1298. $col = $start_col;
  1299. // Titulo del documento
  1300. $document->getActiveSheet()->mergeCells($start_col . $row . ":" . $final_col . $row);
  1301. $document->getActiveSheet()->setCellValue($start_col . $row, 'DETALLES DEL EMPLEADO')->getStyle($start_col . $row)->getFill()
  1302. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1303. ->getStartColor()->setRGB('FFCC88');
  1304. $document->getActiveSheet()->getStyle($start_col . $row)->getFont()->setBold(true);
  1305. $row++;
  1306. //Cuerpo del documento
  1307. $document->getActiveSheet()->setCellValue($col . $row, 'ID EMPLEADO')->getStyle($col . $row)->getFill()
  1308. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1309. ->getStartColor()->setRGB('38D9CE');
  1310. $col++;
  1311. $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE EMPLEADO')->getStyle($col . $row)->getFill()
  1312. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1313. ->getStartColor()->setRGB('38D9CE');
  1314. $col++;
  1315. $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE EQUIPO')->getStyle($col . $row)->getFill()
  1316. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1317. ->getStartColor()->setRGB('38D9CE');
  1318. $col++;
  1319. $document->getActiveSheet()->setCellValue($col . $row, 'NOMBRE CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
  1320. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1321. ->getStartColor()->setRGB('38D9CE');
  1322. $col++;
  1323. $document->getActiveSheet()->setCellValue($col . $row, 'TELEFONO CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
  1324. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1325. ->getStartColor()->setRGB('38D9CE');
  1326. $col++;
  1327. $document->getActiveSheet()->setCellValue($col . $row, 'DIRECCIÓN CONTACTO DE EMERGENCIA')->getStyle($col . $row)->getFill()
  1328. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1329. ->getStartColor()->setRGB('38D9CE');
  1330. $col++;
  1331. $document->getActiveSheet()->setCellValue($col . $row, 'TIPO DE CONTRATO')->getStyle($col . $row)->getFill()
  1332. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1333. ->getStartColor()->setRGB('38D9CE');
  1334. $col++;
  1335. $document->getActiveSheet()->setCellValue($col . $row, 'ESPECIALIDAD DEL EMPLEADO')->getStyle($col . $row)->getFill()
  1336. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1337. ->getStartColor()->setRGB('38D9CE');
  1338. $col++;
  1339. $document->getActiveSheet()->setCellValue($col . $row, 'DOCUMENTOS')->getStyle($col . $row)->getFill()
  1340. ->setFillType(\PhpOffice\PhpSpreadsheet\Style\Fill::FILL_SOLID)
  1341. ->getStartColor()->setRGB('38D9CE');
  1342. $row++;
  1343. $col = $start_col;
  1344. $document->getActiveSheet()->setCellValue($col . $row, "#" . $employee['ID_EMPLOYEE']);
  1345. $col++;
  1346. $document->getActiveSheet()->setCellValue($col . $row, $employee['EMPLOYEE_NAME']);
  1347. $col++;
  1348. $document->getActiveSheet()->setCellValue($col . $row, $employee['WORKTEAM_NAME']);
  1349. $col++;
  1350. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_NAME']));
  1351. $col++;
  1352. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_LADA']) . $this->encrypt_controller->decrypt($employee['CONTACT_TELEPHONE']));
  1353. $col++;
  1354. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($employee['CONTACT_ADDRESS']));
  1355. $col++;
  1356. $document->getActiveSheet()->setCellValue($col . $row, $employee['CONTRACT_TYPE']);
  1357. $col++;
  1358. $document->getActiveSheet()->setCellValue($col . $row, $employee['SPECIALITY']);
  1359. $col++;
  1360. // Verifica si el empleado tiene documentos
  1361. if (isset($employee['DOCUMENTS'][0]) && !empty($employee['DOCUMENTS'][0])) {
  1362. foreach ($employee['DOCUMENTS'] as $doc) {
  1363. $document->getActiveSheet()->setCellValue($col . $row, $this->encrypt_controller->decrypt($doc));
  1364. $row++;
  1365. }
  1366. } else {
  1367. $document->getActiveSheet()->setCellValue($col . $row, 'SIN DOCUMENTOS...');
  1368. $document->getActiveSheet()->getStyle($col . $row)->getFont()->setBold(true);
  1369. $row++;
  1370. }
  1371. //Ajusta las celdas a su contenido y da estilo
  1372. $document->getActiveSheet()->mergeCells($start_col . $start_row + 2 . ":" . $start_col . $row - 1);
  1373. $document->getActiveSheet()->mergeCells($second_col . $start_row + 2 . ":" . $second_col . $row - 1);
  1374. $document->getActiveSheet()->mergeCells($third_col . $start_row + 2 . ":" . $third_col . $row - 1);
  1375. $document->getActiveSheet()->mergeCells($fourth_col . $start_row + 2 . ":" . $fourth_col . $row - 1);
  1376. $document->getActiveSheet()->mergeCells($fifth_col . $start_row + 2 . ":" . $fifth_col . $row - 1);
  1377. $document->getActiveSheet()->mergeCells($sixth_col . $start_row + 2 . ":" . $sixth_col . $row - 1);
  1378. $document->getActiveSheet()->mergeCells($seventh_col . $start_row + 2 . ":" . $seventh_col . $row - 1);
  1379. $document->getActiveSheet()->mergeCells($eight_col . $start_row + 2 . ":" . $eight_col . $row - 1);
  1380. $col = $start_col;
  1381. for ($i = 0; $i < 9; $i++) {
  1382. $document->getActiveSheet()->getColumnDimension($col)->setAutoSize(true);
  1383. $col++;
  1384. }
  1385. $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row)->getAlignment()->setHorizontal(\PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER);
  1386. $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row)->getAlignment()->setVertical(\PhpOffice\PhpSpreadsheet\Style\Alignment::VERTICAL_CENTER);
  1387. $document->getActiveSheet()->getStyle($start_col . $start_row . ':' . $final_col . $row - 1)->getBorders()->getAllBorders()->setBorderStyle(\PhpOffice\PhpSpreadsheet\Style\Border::BORDER_MEDIUM);
  1388. return $document;
  1389. } catch (Throwable $th) {
  1390. return $this->response_controller
  1391. ->makeResponse(TRUE, 'ERR_CREACIÓN_DOCUMENTO_REG001: Error inesperado', strtoupper($th->getMessage()), 500);
  1392. }
  1393. }
  1394. }