PersonnelManagementController.php 210 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Carbon\Carbon;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Support\Facades\DB;
  6. use Illuminate\Support\Facades\Storage;
  7. use Illuminate\Support\Facades\Validator;
  8. use Illuminate\Database\Query\Builder;
  9. use Illuminate\Http\File;
  10. use PhpOffice\PhpSpreadsheet\IOFactory;
  11. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  12. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  13. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  14. use PhpOffice\PhpSpreadsheet\Style\Fill;
  15. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  16. use PhpOffice\PhpSpreadsheet\Style\NumberFormat;
  17. use PhpOffice\PhpSpreadsheet\Style\Border;
  18. use ElephantIO\Client;
  19. use stdClass;
  20. use Throwable;
  21. class PersonnelManagementController extends Controller
  22. {
  23. private $responseController;
  24. private $encryptionController;
  25. private $documentManagementController;
  26. private $functionsController;
  27. private $resourcesController;
  28. public function __construct(){
  29. $this->responseController = new ResponseController();
  30. $this->encryptionController = new EncryptionController();
  31. $this->documentManagementController = new DocumentManagementController();
  32. $this->functionsController = new FunctionsController();
  33. $this->resourcesController = new ResourcesController();
  34. }
  35. public function getConsultOfEmployees($idUser, $line) {
  36. DB::enableQueryLog();
  37. $idUser = $this->encryptionController->decrypt($idUser);
  38. if(!$idUser){
  39. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  40. }
  41. $usr = DB::table('S002V01TUSUA')->where([
  42. ['USUA_NULI', '=', $line],
  43. ['USUA_IDUS', '=', $idUser],
  44. ])->first();
  45. if(is_null($usr)){
  46. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  47. }
  48. $employees = DB::table('S002V01TPERS')->select([
  49. 'PERS_IDPE AS ID_EMPLOYEE',
  50. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  51. 'PERS_TICO AS CONTRACT_TYPE',
  52. 'PERS_IDPS AS ID_SUBCONTRATISTA',
  53. 'PERS_ESPE AS SPECIALITY',
  54. 'PERS_EQTR AS TEAM_ID',
  55. 'EQMA_NOMB AS TEAM_NAME',
  56. 'PERS_FERE AS REGISTER_DATE',
  57. 'PERS_USRE AS REGISTERED_BY_USER',
  58. 'PERS_FEMO AS UPDATE_DATE',
  59. 'PERS_USMO AS UPDATED_BY_USER',
  60. 'PERS_ESTA AS STATUS'
  61. ])->join('S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS')
  62. ->leftJoin('S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ')
  63. ->where('USUA_NULI', '=', $line)->get()->all();
  64. foreach($employees as $key=>$employee){
  65. $employee->ID_EMPLOYEE = $this->encryptionController->encrypt($employee->ID_EMPLOYEE);
  66. if(!is_null($employee->TEAM_ID)){
  67. $employee->TEAM_ID = $this->encryptionController->encrypt($employee->TEAM_ID);
  68. }
  69. if(!is_null($employee->ID_SUBCONTRATISTA)){
  70. $employee->ID_SUBCONTRATISTA = $this->encryptionController->encrypt($employee->ID_SUBCONTRATISTA);
  71. }
  72. $specialtiesArr = json_decode($employee->SPECIALITY, true);
  73. foreach($specialtiesArr as $key0=>$specialtyCode){
  74. $specialty = DB::table('S002V01TGEES')->where([
  75. ['GEES_NULI', '=', $line],
  76. ['GEES_COES', '=', $specialtyCode]
  77. ])->first();
  78. $specialtyName = $specialtyCode . " - " . $specialty->GEES_NOES;
  79. $specialtiesArr[$key0] = $this->encryptionController->encrypt($specialtyName);
  80. }
  81. $employee->SPECIALITY = json_encode($specialtiesArr);
  82. $employees[$key] = $employee;
  83. }
  84. $now = $this->functionsController->now();
  85. $nowStr = $now->toDateTimeString();
  86. $actions = DB::getQueryLog();
  87. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  88. $idac = $this->functionsController->registerActivity(
  89. $line,
  90. 'S002V01M11GPRS',
  91. 'S002V01F01GEPE',
  92. 'S002V01P01COEM',
  93. 'Consulta',
  94. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados registrados.",
  95. $idUser,
  96. $nowStr,
  97. 'S002V01S02GEPE'
  98. );
  99. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  100. return $this->responseController->makeResponse(false, 'EXITO', $employees);
  101. }
  102. public function getEmployeeById($idEmployee, $idUser, $line) {
  103. DB::enableQueryLog();
  104. $idUser = $this->encryptionController->decrypt($idUser);
  105. if(!$idUser){
  106. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  107. }
  108. $usr = DB::table('S002V01TUSUA')->where([
  109. ['USUA_NULI', '=', $line],
  110. ['USUA_IDUS', '=', $idUser],
  111. ])->first();
  112. if(is_null($usr)){
  113. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  114. }
  115. $idEmployee = $this->encryptionController->decrypt($idEmployee);
  116. if(!$idEmployee){
  117. return $this->responseController->makeResponse(true, 'El ID del empleado solicitado no está encriptado correctamente', [], 400);
  118. }
  119. $employee = DB::table('S002V01TPERS')->select([
  120. 'PERS_IDPE AS ID_EMPLOYEE',
  121. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as EMPLOYEE_NAME'),
  122. 'PERS_IDUS AS USER_ID',
  123. 'EQMA_IDEQ AS WORKTEAM_ID',
  124. 'EQMA_NOMB AS WORKTEAM_NAME',
  125. 'PERS_TICO AS CONTRACT_TYPE',
  126. 'PERS_IDPS AS SUBCONTRATIST_ID',
  127. 'PESU_RASO AS SUBCONTRATIST_NAME',
  128. 'PESU_REFI AS TAX_REGIME',
  129. 'REFI_DRFI AS TAX_REGIME_DESCRIPTION',
  130. 'PERS_ESPE AS SPECIALITY',
  131. 'PERS_EXTR AS FOREIGNER',
  132. 'PERS_XRFC AS RFC',
  133. 'PERS_TAID AS TAX_ID',
  134. 'PERS_IDPA AS COUNTRY',
  135. 'PERS_ENFE AS STATE',
  136. 'PERS_CIUD AS CITY',
  137. 'PERS_LOCA AS TOWN',
  138. 'PERS_COLO AS SETTING',
  139. 'PERS_COPO AS ZIP_CODE',
  140. 'PERS_CALL AS STREET',
  141. 'PERS_NUEX AS EXTERIOR_NUMBER',
  142. 'PERS_NUIN AS INTERIOR_NUMBER',
  143. 'PERS_NOCE AS CONTACT_NAME',
  144. 'PERS_LCEM AS CONTACT_LADA',
  145. 'PERS_NUTC AS CONTACT_TELEPHONE',
  146. 'PERS_DCEM AS CONTACT_ADDRESS',
  147. 'PERS_DOAS AS DOCUMENTS',
  148. 'PERS_ESTA AS STATUS',
  149. 'PERS_USRE AS USRREG',
  150. 'PERS_USMO AS USRMOD',
  151. 'PERS_FERE AS FECREG',
  152. 'PERS_FEMO AS FECMOD',
  153. ])->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')
  154. ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  155. ->leftJoin('S002V01TREFI', 'REFI_CRFI', '=', 'PESU_REFI')
  156. ->join('S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS')->where([
  157. ['PERS_NULI', '=', $line],
  158. ['PERS_IDPE', '=', $idEmployee],
  159. ])->first();
  160. if(is_null($employee)){
  161. return $this->responseController->makeResponse(true, 'El empleado consultado no existe.', [], 404);
  162. }else if($employee->STATUS == 'Eliminado'){
  163. return $this->responseController->makeResponse(true, 'El empleado consultado está eliminado.', [], 404);
  164. }
  165. if(!is_null($employee->RFC)){
  166. $employee->RFC = $this->encryptionController->encrypt($employee->RFC);
  167. }
  168. if(!is_null($employee->TAX_ID)){
  169. $employee->TAX_ID = $this->encryptionController->encrypt($employee->TAX_ID);
  170. }
  171. $attached = [];
  172. $docsArr = json_decode($employee->DOCUMENTS, true);
  173. foreach($docsArr as $doc){
  174. $docArr = explode('=', $doc['CODE']);
  175. $codeArr = explode('-', $docArr[0]);
  176. $document = DB::table('S002V01TAFAL')->select([
  177. 'AFAL_NOAR AS FILE_NAME',
  178. 'AFAL_EXTE AS FILE_EXTENSION',
  179. 'AFAL_TAMA AS FILE_SIZE',
  180. 'AFAL_ESTA AS FILE_STATUS'
  181. ])->where([
  182. ['AFAL_NULI', '=', $line],
  183. ['AFAL_COMO', '=', $codeArr[1]],
  184. ['AFAL_CLDO', '=', $codeArr[2]],
  185. ['AFAL_FECR', '=', $codeArr[3]],
  186. ['AFAL_NUSE', '=', $codeArr[4]],
  187. ['AFAL_NUVE', '=', $docArr[1]],
  188. ])->first();
  189. if (!is_null($document)) {
  190. $document->FILE_ID = $this->encryptionController->encrypt($doc['CODE']);
  191. $document->FILE_TYPE = $doc['TYPE'];
  192. $attached[] = $document;
  193. }
  194. }
  195. $employee->DOCUMENTS = json_encode($attached);
  196. $country = DB::table('S002V01TPAIS')->where([
  197. ['PAIS_NULI', '=', $line],
  198. ['PAIS_IDPA', '=', $employee->COUNTRY]
  199. ])->first();
  200. $state = DB::table('S002V01TESTA')->where([
  201. ['ESTA_NULI', '=', $line],
  202. ['ESTA_COES', '=', $employee->STATE],
  203. ['ESTA_COPA', '=', $employee->COUNTRY]
  204. ])->first();
  205. $city = DB::table('S002V01TMUNI')->where([
  206. ['MUNI_NULI', '=', $line],
  207. ['MUNI_COMU', '=', $employee->CITY],
  208. ['MUNI_COES', '=', $employee->STATE],
  209. ])->first();
  210. $town = DB::table('S002V01TLOCA')->where([
  211. ['LOCA_NULI', '=', $line],
  212. ['LOCA_COLO', '=', $employee->TOWN],
  213. ['LOCA_COES', '=', $employee->STATE],
  214. ])->first();
  215. $setting = DB::table('S002V01TCOLO')->where([
  216. ['COLO_NULI', '=', $line],
  217. ['COLO_COCO', '=', $employee->SETTING],
  218. ['COLO_COPO', '=', $employee->ZIP_CODE],
  219. ])->first();
  220. $employee->COUNTRY = $country->PAIS_NOMB . " (" . $employee->COUNTRY . ")";
  221. $employee->STATE = is_null($state) ? $employee->STATE : $state->ESTA_NOES . " (" . $employee->STATE . ")";
  222. $employee->CITY = is_null($city) ? $employee->CITY : $city->MUNI_NOMU . " (" . $employee->CITY . ")";
  223. $employee->TOWN = is_null($town) ? $employee->TOWN : $town->LOCA_NOLO . " (" . $employee->TOWN . ")";
  224. $employee->SETTING = is_null($setting) ? $employee->SETTING : $setting->COLO_NOCO . " (" . $employee->SETTING . ")";
  225. $employee->ZIP_CODE = $this->encryptionController->encrypt($employee->ZIP_CODE);
  226. $employee->CONTACT_TELEPHONE = $this->encryptionController->encrypt($employee->CONTACT_TELEPHONE);
  227. $employee->USER_ID = $this->encryptionController->encrypt($employee->USER_ID);
  228. $employee->WORKTEAM_ID = !is_null($employee->WORKTEAM_ID) ? $this->encryptionController->encrypt($employee->WORKTEAM_ID) : null;
  229. $usrReg = DB::table('S002V01TUSUA')->where([
  230. ['USUA_NULI', '=', $line],
  231. ['USUA_IDUS', '=', $employee->USRREG]
  232. ])->first();
  233. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  234. $employee->USRREG = "$nameReg (" . $employee->USRREG . ")";
  235. if(!is_null($employee->USRMOD)){
  236. $usrMod = DB::table('S002V01TUSUA')->where([
  237. ['USUA_NULI', '=', $line],
  238. ['USUA_IDUS', '=', $employee->USRMOD]
  239. ])->first();
  240. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  241. $employee->USRMOD = "$nameMod (" . $employee->USRMOD . ")";
  242. }
  243. $specialtiesArr = json_decode($employee->SPECIALITY, true);
  244. foreach($specialtiesArr as $key=>$specialtyCode){
  245. $specialtyObj = DB::table('S002V01TGEES')->where([
  246. ['GEES_NULI', '=', $line],
  247. ['GEES_COES', '=', $specialtyCode]
  248. ])->first();
  249. $specialty = $specialtyCode . " - " . $specialtyObj->GEES_NOES;
  250. $specialtiesArr[$key] = $this->encryptionController->encrypt($specialty);
  251. }
  252. $employee->SPECIALITY = json_encode($specialtiesArr);
  253. $now = $this->functionsController->now();
  254. $nowStr = $now->toDateTimeString();
  255. $actions = DB::getQueryLog();
  256. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  257. $idac = $this->functionsController->registerActivity(
  258. $line,
  259. 'S002V01M11GPRS',
  260. 'S002V01F01GEPE',
  261. 'S002V01P03DEEM',
  262. 'Consulta',
  263. "El usuario $name (" . $usr->USUA_IDUS . ") consultó al empleado " . $employee->EMPLOYEE_NAME . " ($idEmployee).",
  264. $idUser,
  265. $nowStr,
  266. 'S002V01S02GEPE'
  267. );
  268. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  269. return $this->responseController->makeResponse(false, 'EXITO', $employee);
  270. }
  271. public function updateToInactiveStatusEmployee(Request $request) {
  272. DB::enableQueryLog();
  273. $validator = Validator::make($request->all(), [
  274. 'id_user' => 'required|string',
  275. 'linea' => 'required|integer',
  276. 'id_employee' => 'required|string',
  277. ]);
  278. if($validator->fails()){
  279. return $this->responseController->makeResponse(
  280. true,
  281. "Se encontraron uno o más errores.",
  282. $this->responseController->makeErrors(
  283. $validator->errors()->messages()
  284. ),
  285. 401
  286. );
  287. }
  288. $form = $request->all();
  289. $idUser = $this->encryptionController->decrypt($form['id_user']);
  290. if(!$idUser){
  291. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  292. }
  293. $usr = DB::table('S002V01TUSUA')->where([
  294. ['USUA_NULI', '=', $form['linea']],
  295. ['USUA_IDUS', '=', $idUser]
  296. ])->first();
  297. if(is_null($usr)){
  298. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  299. }
  300. $idEmployee = $this->encryptionController->decrypt($form['id_employee']);
  301. if(!$idEmployee){
  302. return $this->responseController->makeResponse(true, 'El ID del empleado que desea actualizar no fue encriptado correctamente.', [], 400);
  303. }
  304. $employee = DB::table('S002V01TPERS')->where([
  305. ['PERS_NULI', '=', $form['linea']],
  306. ['PERS_IDPE', '=', $idEmployee]
  307. ])->first();
  308. if(is_null($employee)){
  309. return $this->responseController->makeResponse(true, 'El empleado que desea actualizar no existe.', [], 404);
  310. }
  311. if($idUser == $employee->PERS_IDUS){
  312. return $this->responseController->makeResponse(true, 'El usuario no puede eliminarse a sí mismo.', [], 400);
  313. }
  314. $now = $this->functionsController->now();
  315. $nowStr = $now->toDateTimeString();
  316. DB::table('S002V01TPERS')->where([
  317. ['PERS_NULI', '=', $form['linea']],
  318. ['PERS_IDPE', '=', $idEmployee]
  319. ])->update([
  320. 'PERS_ESTA' => 'Eliminado',
  321. 'PERS_USMO' => $idUser,
  322. 'PERS_FEMO' => $nowStr,
  323. ]);
  324. $actions = DB::getQueryLog();
  325. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  326. $idac = $this->functionsController->registerActivity(
  327. $form['linea'],
  328. 'S002V01M11GPRS',
  329. 'S002V01F01GEPE',
  330. 'S002V01P02REEM',
  331. 'Eliminación',
  332. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó al empleado $idEmployee.",
  333. $idUser,
  334. $nowStr,
  335. 'S002V01S02GEPE'
  336. );
  337. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  338. return $this->responseController->makeResponse(false, 'EXITO');
  339. }
  340. public function getContractsOfEveryEmployee($idUser, $line) {
  341. DB::enableQueryLog();
  342. $idUser = $this->encryptionController->decrypt($idUser);
  343. if(!$idUser){
  344. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  345. }
  346. $usr = DB::table('S002V01TUSUA')->where([
  347. ['USUA_NULI', '=', $line],
  348. ['USUA_IDUS', '=', $idUser],
  349. ])->first();
  350. if(is_null($usr)){
  351. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  352. }
  353. $contractsByEmployees = DB::table('S002V01TPERS')->select([
  354. DB::raw("
  355. TRIM(CONCAT(
  356. USUA_NOMB,
  357. ' ',
  358. USUA_APPA,
  359. IF(ISNULL(USUA_APMA), '', CONCAT(' ', USUA_APMA)),
  360. ' <(',
  361. PERS_IDPE,
  362. ')> (',
  363. PERS_IDUS,
  364. ')'
  365. )) AS EMPLOYEE
  366. "),
  367. DB::raw("COUNT(CONT_IDCO) AS CONTRACTS")
  368. ])->leftJoin('S002V01TCONT', 'CONT_IDEM', '=', 'PERS_IDPE')
  369. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  370. ->groupBy('EMPLOYEE')->where([
  371. ['PERS_NULI', '=', $line],
  372. ['PERS_TICO', '=', 'Interno'],
  373. ])->get()->all();
  374. foreach($contractsByEmployees as $key=>$val){
  375. $employeeArr = explode('<', $val->EMPLOYEE);
  376. $employeeName = $employeeArr[0];
  377. $employeeArr = array_reverse($employeeArr);
  378. $employeeArr = explode('>', $employeeArr[0]);
  379. $employeeID = str_replace('(', '', $employeeArr[0]);
  380. $employeeID = str_replace(')', '', $employeeID);
  381. $val->ID_EMPLOYEE = $this->encryptionController->encrypt($employeeID);
  382. $val->EMPLOYEE = $employeeName . join('', $employeeArr);
  383. $contractsByEmployees[$key] = $val;
  384. }
  385. $now = $this->functionsController->now();
  386. $nowStr = $now->toDateTimeString();
  387. $actions = DB::getQueryLog();
  388. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  389. $idac = $this->functionsController->registerActivity(
  390. $line,
  391. 'S002V01M11GPRS',
  392. 'S002V01F02ACEM',
  393. 'S002V01P01HCEM',
  394. 'Consulta',
  395. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos por empleados.",
  396. $idUser,
  397. $nowStr,
  398. 'S002V01S02GEPE'
  399. );
  400. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  401. return $this->responseController->makeResponse(false, 'EXITO', $contractsByEmployees);
  402. }
  403. public function getDetailsOfContractsByEmployee($idEmployee, $idUser, $line) {
  404. DB::enableQueryLog();
  405. $idUser = $this->encryptionController->decrypt($idUser);
  406. if(!$idUser){
  407. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  408. }
  409. $usr = DB::table('S002V01TUSUA')->where([
  410. ['USUA_NULI', '=', $line],
  411. ['USUA_IDUS', '=', $idUser]
  412. ])->first();
  413. if(is_null($usr)){
  414. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  415. }
  416. $idEmployee = $this->encryptionController->decrypt($idEmployee);
  417. if(!$idEmployee){
  418. return $this->responseController->makeResponse(true, 'El ID del empleado no fue encriptado correctamente.', [], 400);
  419. }
  420. $sub = DB::table('S002V01TPERS')->where([
  421. ['PERS_NULI', '=', $line],
  422. ['PERS_IDPE', '=', $idEmployee],
  423. ['PERS_TICO', '=', 'Interno'],
  424. ])->first();
  425. if(is_null($sub)){
  426. return $this->responseController->makeResponse(true, 'El empleado solicitado no existe.', [], 404);
  427. }
  428. $contracts = DB::table('S002V01TCONT')->select([
  429. 'CONT_NOCO AS CONTRACT_NAME',
  430. 'CONT_FEIN AS START_DATE',
  431. 'CONT_FEFI AS END_DATE',
  432. 'CONT_COST AS COST',
  433. ])->where([
  434. ['CONT_NULI', '=', $line],
  435. ['CONT_IDEM', '=', $idEmployee],
  436. ['CONT_TIPO', '=', 'Interno'],
  437. ])->get()->all();
  438. $now = $this->functionsController->now();
  439. $nowStr = $now->toDateTimeString();
  440. $actions = DB::getQueryLog();
  441. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  442. $idac = $this->functionsController->registerActivity(
  443. $line,
  444. 'S002V01M11GPRS',
  445. 'S002V01F02ACEM',
  446. 'S002V01P01HCEM',
  447. 'Consulta',
  448. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos del empleado #$idEmployee.",
  449. $idUser,
  450. $nowStr,
  451. 'S002V01S02GEPE'
  452. );
  453. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  454. return $this->responseController->makeResponse(false, 'EXITO', $contracts);
  455. }
  456. public function getInterventionsByEmployee($idEmployee, $idUser, $line) {
  457. DB::enableQueryLog();
  458. $idUser = $this->encryptionController->decrypt($idUser);
  459. if(!$idUser){
  460. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  461. }
  462. $usr = DB::table('S002V01TUSUA')->where([
  463. ['USUA_NULI', '=', $line],
  464. ['USUA_IDUS', '=', $idUser]
  465. ])->first();
  466. if(is_null($usr)){
  467. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  468. }
  469. $idEmployee = $this->encryptionController->decrypt($idEmployee);
  470. if(!$idEmployee){
  471. return $this->responseController->makeResponse(true, 'El ID del empleado no fue encriptado correctamente.', [], 400);
  472. }
  473. $employee = DB::table('S002V01TPERS')->where([
  474. ['PERS_NULI', '=', $line],
  475. ['PERS_IDPE', '=', $idEmployee],
  476. ])->first();
  477. if(is_null($employee)){
  478. return $this->responseController->makeResponse(true, 'El empleado solicitado no existe.', [], 404);
  479. }
  480. $preventiveOrders = DB::select("
  481. SELECT
  482. DISTINCT(S002V01TOTPR.OTPR_IDOT) AS IDORDEN,
  483. S002V01TOTPR.OTPR_DEIN AS DESCRIPCION,
  484. 'Preventivo' AS TIPOORDEN
  485. FROM
  486. S002V01TOTPR,
  487. JSON_TABLE(OTPR_OPPR, '$[*]' COLUMNS(
  488. OTPR_OPPR_ID INT PATH '$.ID',
  489. OTPR_OPPR_TYPE VARCHAR(100) PATH '$.TYPE'
  490. )) OPPR
  491. WHERE
  492. (OTPR_OPPR_ID = :emp_id AND OTPR_OPPR_TYPE = 'EM')
  493. OR (OTPR_OPPR_ID = :sub_id AND OTPR_OPPR_TYPE = 'SU')
  494. OR (OTPR_OPPR_ID = :team_id AND OTPR_OPPR_TYPE = 'EQ')
  495. ", [
  496. 'emp_id' => $employee->PERS_IDPE,
  497. 'sub_id' => $employee->PERS_IDPS,
  498. 'team_id' => $employee->PERS_EQTR
  499. ]);
  500. //PENDIENTE MANTENIMIENTO CORRECTIVO
  501. $ordersFN = [];
  502. $relatedOrders = [];
  503. foreach($preventiveOrders as $order){
  504. if(!in_array($order->IDORDEN, $relatedOrders)){
  505. $relatedOrders[] = $order->IDORDEN;
  506. $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
  507. $ordersFN[] = $order;
  508. }
  509. }
  510. $now = $this->functionsController->now();
  511. $nowStr = $now->toDateTimeString();
  512. $actions = DB::getQueryLog();
  513. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  514. $idac = $this->functionsController->registerActivity(
  515. $line,
  516. 'S002V01M11GPRS',
  517. 'S002V01F01GEPE',
  518. 'S002V01P03DEEM',
  519. 'Consulta',
  520. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo relacionadas al empleado #$idEmployee.",
  521. $idUser,
  522. $nowStr,
  523. 'S002V01S02GEPE'
  524. );
  525. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  526. return $this->responseController->makeResponse(false, 'EXITO', $ordersFN);
  527. }
  528. public function getConsultOfEmployeesForLeader($idEmployee, $idUser, $line) {
  529. DB::enableQueryLog();
  530. $idUser = $this->encryptionController->decrypt($idUser);
  531. if(!$idUser){
  532. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  533. }
  534. try {
  535. $idEmployee = $this->encryptionController->decrypt($idEmployee);
  536. } catch (Throwable $th) {
  537. return $this->responseController->makeResponse(true, 'El ID del empleado no se encriptó correctamente', [], 400);
  538. }
  539. $usr = DB::table('S002V01TUSUA')->where([
  540. ['USUA_NULI', '=', $line],
  541. ['USUA_IDUS', '=', $idUser],
  542. ])->first();
  543. if(is_null($usr)){
  544. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  545. }
  546. if ( is_null($idEmployee) || $idEmployee === '') {
  547. $employees = DB::table('S002V01TPERS')
  548. ->select([
  549. 'PERS_IDPE AS ID_EMPLOYEE',
  550. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  551. 'PERS_TICO AS CONTRACT_TYPE',
  552. 'PERS_ESPE AS SPECIALITY',
  553. 'PERS_EQTR AS TEAM_ID',
  554. 'EQMA_NOMB AS TEAM_NAME',
  555. 'PERS_FERE AS REGISTER_DATE',
  556. 'PERS_USRE AS REGISTERED_BY_USER',
  557. 'PERS_FEMO AS UPDATE_DATE',
  558. 'PERS_USMO AS UPDATED_BY_USER',
  559. ])
  560. ->join('S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS')
  561. ->leftJoin('S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ')
  562. ->where('PERS_ESTA', '=', 'Activo')
  563. ->where('USUA_NULI', '=', $line)
  564. ->get()
  565. ->all();
  566. } else {
  567. $employees = DB::table('S002V01TPERS')
  568. ->select([
  569. 'PERS_IDPE AS ID_EMPLOYEE',
  570. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  571. 'PERS_TICO AS CONTRACT_TYPE',
  572. 'PERS_ESPE AS SPECIALITY',
  573. 'PERS_EQTR AS TEAM_ID',
  574. 'EQMA_NOMB AS TEAM_NAME',
  575. 'PERS_FERE AS REGISTER_DATE',
  576. 'PERS_USRE AS REGISTERED_BY_USER',
  577. 'PERS_FEMO AS UPDATE_DATE',
  578. 'PERS_USMO AS UPDATED_BY_USER',
  579. ])
  580. ->join('S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS')
  581. ->leftJoin('S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ')
  582. ->where('PERS_ESTA', '=', 'Activo')
  583. ->where('USUA_NULI', '=', $line)
  584. ->where('PERS_IDPE', '!=', $idEmployee)
  585. ->get()
  586. ->all();
  587. }
  588. $now = $this->functionsController->now();
  589. $nowStr = $now->toDateTimeString();
  590. $actions = DB::getQueryLog();
  591. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  592. $idac = $this->functionsController->registerActivity(
  593. $line,
  594. 'S002V01M11GPRS',
  595. 'S002V01F01GEPE',
  596. 'S002V01P01COEM',
  597. 'Consulta',
  598. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados registrados.",
  599. $idUser,
  600. $nowStr,
  601. 'S002V01S02GEPE'
  602. );
  603. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  604. return $this->responseController->makeResponse(false, 'EXITO', $employees);
  605. }
  606. public function storeEmployee(Request $request) {
  607. DB::enableQueryLog();
  608. $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
  609. $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
  610. $request['CONTACT_NAME'] = $this->encryptionController->decrypt($request->CONTACT_NAME) ? $this->encryptionController->decrypt($request->CONTACT_NAME) : 'ENC_ERR';
  611. $request['CONTACT_TELEPHONE'] = $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) ? $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) : 'ENC_ERR';
  612. $request['CONTACT_LADA'] = $this->encryptionController->decrypt($request->CONTACT_LADA) ? $this->encryptionController->decrypt($request->CONTACT_LADA) : 'ENC_ERR';
  613. $request['CONTACT_ADDRESS'] = $this->encryptionController->decrypt($request->CONTACT_ADDRESS) ? $this->encryptionController->decrypt($request->CONTACT_ADDRESS) : 'ENC_ERR';
  614. $validator = Validator::make($request->all(), [
  615. 'id_user' => 'required|string',
  616. 'linea' => 'required|integer',
  617. 'USER_ID' => 'required|string',
  618. 'WORKTEAM_ID' => 'required|string',
  619. 'CONTRACT_TYPE' => 'required|string|in:Subcontratista,Interno',
  620. 'SUBCONTRATIST_ID' => 'required_if:CONTRACT_TYPE,=,Subcontratista|string',
  621. 'SPECIALITY' => 'required|json',
  622. 'FOREIGNER' => 'required|string|in:Si,No',
  623. 'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
  624. 'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
  625. 'COUNTRY' => 'required|string|max:75',
  626. 'FEDERAL_ENTITY' => 'required|string|max:75',
  627. 'CITY' => 'string|max:75',
  628. 'TOWN' => 'string|max:75',
  629. 'SUBURB' => 'required|string|max:75',
  630. 'POSTAL_CODE' => 'required|string|max:5',
  631. 'STREET' => 'required|string|max:150',
  632. 'EXTERIOR_NUMBER' => 'required|integer',
  633. 'INTERIOR_NUMBER' => 'integer',
  634. 'CONTACT_NAME' => 'required|string|max:150',
  635. 'CONTACT_LADA' => 'required|string|max:10',
  636. 'CONTACT_TELEPHONE' => 'required|string|max:11',
  637. 'CONTACT_ADDRESS' => 'required|string|max:250',
  638. 'ATTACHED' => 'required|json',
  639. ]);
  640. if($validator->fails()){
  641. return $this->responseController->makeResponse(
  642. TRUE,
  643. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  644. $this->responseController->makeErrors($validator->errors()->messages()),
  645. 400
  646. );
  647. }
  648. $form = $request->all();
  649. foreach($form as $k=>$v){
  650. if($k == 'INTERIOR_NUMBER' && $v == '0'){
  651. unset($form[$k]);
  652. }else if($v == '-'){
  653. unset($form[$k]);
  654. }
  655. }
  656. $idUser = $this->encryptionController->decrypt($form['id_user']);
  657. if(!$idUser){
  658. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  659. }
  660. $usr = DB::table('S002V01TUSUA')->where([
  661. ['USUA_NULI', '=', $form['linea']],
  662. ['USUA_IDUS', '=', $idUser]
  663. ])->first();
  664. if(is_null($usr)){
  665. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  666. }
  667. $idUserReg = $this->encryptionController->decrypt($form['USER_ID']);
  668. if(!$idUserReg){
  669. return $this->responseController->makeResponse(true, 'El ID del usuario seleccionado no fue encriptado correctamente.', [], 400);
  670. }else if($idUser == $idUserReg){
  671. return $this->responseController->makeResponse(true, 'El usuario no puede registrarse a sí mismo.', [], 400);
  672. }
  673. $usrReg = DB::table('S002V01TUSUA')->where([
  674. ['USUA_NULI', '=', $form['linea']],
  675. ['USUA_IDUS', '=', $idUserReg]
  676. ])->first();
  677. if(is_null($usrReg)){
  678. return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404);
  679. }
  680. $idTeam = null;
  681. if(isset($form['WORKTEAM_ID'])){
  682. $idTeam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
  683. if(!$idTeam){
  684. return $this->responseController->makeResponse(true, 'El ID del equipo seleccionado encriptado correctamente.', [], 400);
  685. }
  686. $team = DB::table('S002V01TEQMA')->where([
  687. ['EQMA_IDEQ', '=', $idTeam],
  688. ['EQMA_NULI', '=', $form['linea']],
  689. ])->first();
  690. if(is_null($team)){
  691. return $this->responseController->makeResponse(true, 'El equipo seleccionado no existe.', [], 404);
  692. }else if($team->EQMA_ESTA == 'Eliminado'){
  693. return $this->responseController->makeResponse(true, 'El equipo seleccionado está eliminado.', [], 404);
  694. }
  695. }
  696. $idSubcontratist = null;
  697. if(isset($form['SUBCONTRATIST_ID'])){
  698. $idSubcontratist = $this->encryptionController->decrypt($form['SUBCONTRATIST_ID']);
  699. if(!$idSubcontratist){
  700. return $this->responseController->makeResponse(true, 'El ID del subcontratista seleccionado no fue encriptado correctamente.', [], 400);
  701. }
  702. $subcontratist = DB::table('S002V01TPESU')->where([
  703. ['PESU_IDPS', '=', $idSubcontratist],
  704. ['PESU_NULI', '=', $form['linea']],
  705. ])->first();
  706. if(is_null($subcontratist)){
  707. return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404);
  708. }
  709. }
  710. $rfcx = null;
  711. if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
  712. return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
  713. }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
  714. $rfcx = $form['RFC'];
  715. }
  716. $taid = null;
  717. if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
  718. return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
  719. }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
  720. $taid = $form['TAX'];
  721. }
  722. $country = DB::table('S002V01TPAIS')->where([
  723. ['PAIS_NULI', '=', $form['linea']],
  724. ['PAIS_IDPA', '=', $form['COUNTRY']],
  725. ])->first();
  726. if(is_null($country)){
  727. return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
  728. }
  729. $colo = null;
  730. $ciud = null;
  731. $loca = null;
  732. if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
  733. $state = DB::table('S002V01TESTA')->where([
  734. ['ESTA_NULI', '=', $form['linea']],
  735. ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
  736. ['ESTA_COPA', '=', $form['COUNTRY']],
  737. ])->first();
  738. if(is_null($state)){
  739. return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
  740. }
  741. if($form['COUNTRY'] == 'MEX'){
  742. if(isset($form['CITY'])){
  743. $city = DB::table('S002V01TMUNI')->where([
  744. ['MUNI_NULI', '=', $form['linea']],
  745. ['MUNI_COMU', '=', $form['CITY']],
  746. ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
  747. ])->first();
  748. if(is_null($city)){
  749. return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
  750. }else{
  751. $ciud = $form['CITY'];
  752. }
  753. }
  754. if(isset($form['TOWN'])){
  755. $town = DB::table('S002V01TLOCA')->where([
  756. ['LOCA_NULI', '=', $form['linea']],
  757. ['LOCA_COLO', '=', $form['TOWN']],
  758. ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
  759. ])->first();
  760. if(is_null($town)){
  761. return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
  762. }else{
  763. $loca = $form['TOWN'];
  764. }
  765. }
  766. $setting = DB::table('S002V01TCOLO')->where([
  767. ['COLO_NULI', '=', $form['linea']],
  768. ['COLO_COCO', '=', $form['SUBURB']],
  769. ['COLO_COPO', '=', $form['POSTAL_CODE']],
  770. ])->first();
  771. if(is_null($setting)){
  772. return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
  773. }else{
  774. $colo = $form['SUBURB'];
  775. }
  776. $zipCode = DB::table('S002V01TCOPO')->where([
  777. ['COPO_NULI', '=', $form['linea']],
  778. ['COPO_COPO', '=', $form['POSTAL_CODE']],
  779. ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
  780. ])->first();
  781. if(is_null($zipCode)){
  782. return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
  783. }
  784. }else{
  785. $colo = $form['SUBURB'];
  786. $ciud = $form['CITY'];
  787. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  788. }
  789. }else{
  790. $colo = $form['SUBURB'];
  791. $ciud = $form['CITY'];
  792. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  793. }
  794. $subArr = DB::table('S002V01TPERS')->where('PERS_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form, $idUserReg) {
  795. $query->where('PERS_IDUS', '=', $idUserReg)
  796. ->orWhere('PERS_XRFC', '=', $form['RFC']);
  797. })->where('PERS_ESTA', '=', 'Activo')->get()->all();
  798. if(count($subArr) > 0){
  799. return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
  800. }
  801. $ladasValues = [];
  802. $ladas = DB::table('S002V01TPAIS')->select([
  803. 'PAIS_LADA AS LADA'
  804. ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
  805. foreach($ladas as $lada){
  806. if($lada->LADA != '' && $lada->LADA != '0'){
  807. $ladasValues[] = $lada->LADA;
  808. }
  809. }
  810. if($form['CONTACT_LADA'] == 'ENC_ERR'){
  811. return $this->responseController->makeResponse(true, "La lada del contacto de emergencia no fue encriptada correctamente.", [], 400);
  812. }else if(!in_array($form['CONTACT_LADA'], $ladasValues)){
  813. return $this->responseController->makeResponse(true, "La lada $form[CONTACT_LADA] no está relacionada a ningún país.", [], 400);
  814. }else if($form['CONTACT_TELEPHONE'] == 'ENC_ERR'){
  815. return $this->responseController->makeResponse(true, 'El número telefónico del contacto de emergencia no fue encriptado correctamente.', [], 400);
  816. }
  817. if($form['CONTACT_ADDRESS'] == 'ENC_ERR'){
  818. return $this->responseController->makeResponse(true, "La dirección del contacto de emergencia no fue encriptada correctamente.", [], 400);
  819. }
  820. if($form['CONTACT_NAME'] == 'ENC_ERR'){
  821. return $this->responseController->makeResponse(true, "El nombre del contacto de emergencia no fue encriptada correctamente.", [], 400);
  822. }
  823. $docsArr = json_decode($form['ATTACHED'], true);
  824. if(count($docsArr) == 0){
  825. return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos está vacío.", [], 400);
  826. }
  827. $authCont = 0;
  828. foreach($docsArr as $doc){
  829. if($doc['type'] == 'AU') $authCont++;
  830. }
  831. if($authCont < 1){
  832. return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos debe contener al menos un documento de autorización.", [], 400);
  833. }
  834. $finalDocsArr = [];
  835. foreach($docsArr as $doc){
  836. $idFileDec = $this->encryptionController->decrypt($doc['id']);
  837. $tempFile = DB::table('S002V01TARTE')->where([
  838. ['ARTE_NULI', '=', $form['linea']],
  839. ['ARTE_IDAR', '=', $idFileDec],
  840. ])->first();
  841. if(is_null($tempFile)){
  842. return $this->responseController->makeResponse(true, "El archivo $doc[name] no está registrado.", [], 404);
  843. }
  844. $classifications = ["AU" => "IN", "OF" => "CO", "CE" => "CE"];
  845. $cldo = $classifications[$doc['type']];
  846. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], "GPRS", $cldo, $tempFile, $idUser);
  847. if(!$finalFile[0]){
  848. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  849. }else{
  850. $finalDocsArr[] = [
  851. 'CODE' => $finalFile[1],
  852. 'TYPE' => $doc['type']
  853. ];
  854. }
  855. }
  856. $specialtiesArr = json_decode($form['SPECIALITY'], true);
  857. foreach($specialtiesArr as $key=>$specialtyCode){
  858. $specialtyCode = $this->encryptionController->decrypt($specialtyCode);
  859. if(!$specialtyCode){
  860. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  861. }
  862. $specialtyObj = DB::table('S002V01TGEES')->where([
  863. ['GEES_NULI', '=', $form['linea']],
  864. ['GEES_COES', '=', $specialtyCode]
  865. ])->first();
  866. if(is_null($specialtyObj)){
  867. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades no existe.", [], 404);
  868. }else if($specialtyObj->GEES_ESTA == 'Eliminado'){
  869. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades está eliminado.", [], 404);
  870. }
  871. $specialtiesArr[$key] = $specialtyCode;
  872. }
  873. $specialtiesStr = json_encode($specialtiesArr);
  874. $now = $this->functionsController->now();
  875. $nowStr = $now->toDateTimeString();
  876. $doas = json_encode($finalDocsArr);
  877. $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
  878. $employeeID = DB::table('S002V01TPERS')->insertGetId([
  879. 'PERS_NULI' => $form['linea'],
  880. 'PERS_IDUS' => $idUserReg,
  881. 'PERS_EQTR' => $idTeam,
  882. 'PERS_TICO' => $form['CONTRACT_TYPE'],
  883. 'PERS_IDPS' => $idSubcontratist,
  884. 'PERS_ESPE' => $specialtiesStr,
  885. 'PERS_EXTR' => $form['FOREIGNER'],
  886. 'PERS_XRFC' => $rfcx,
  887. 'PERS_TAID' => $taid,
  888. 'PERS_IDPA' => $form['COUNTRY'],
  889. 'PERS_ENFE' => $form['FEDERAL_ENTITY'],
  890. 'PERS_CIUD' => $ciud,
  891. 'PERS_LOCA' => $loca,
  892. 'PERS_COLO' => $colo,
  893. 'PERS_COPO' => $form['POSTAL_CODE'],
  894. 'PERS_CALL' => $form['STREET'],
  895. 'PERS_NUEX' => $form['EXTERIOR_NUMBER'],
  896. 'PERS_NUIN' => $nuin,
  897. 'PERS_NOCE' => $form['CONTACT_NAME'],
  898. 'PERS_LCEM' => $form['CONTACT_LADA'],
  899. 'PERS_NUTC' => $form['CONTACT_TELEPHONE'],
  900. 'PERS_DCEM' => $form['CONTACT_ADDRESS'],
  901. 'PERS_DOAS' => $doas,
  902. 'PERS_USRE' => $idUser,
  903. 'PERS_FERE' => $nowStr,
  904. ]);
  905. if ( !is_null($form['EMPLOYEE_BOSS']) && $form['EMPLOYEE_BOSS'] !== '' && $form['EMPLOYEE_BOSS'] !== 'null') {
  906. try {
  907. $validateRegister = DB::table('S002V01TCREM')->insert([
  908. 'CREM_IDES' => $employeeID,
  909. 'CREM_IDEJ' => $form['EMPLOYEE_BOSS'],
  910. 'CREM_NULI' => $form['linea'],
  911. 'CREM_USRE' => $idUser,
  912. 'CREM_FERE' => $nowStr,
  913. 'CREM_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  914. ]);
  915. } catch (Throwable $th) {
  916. return $this->responseController->makeResponse(true, "Ocurrió un error al registrar el cronograma.", [], 400);
  917. }
  918. if (!$validateRegister) {
  919. return $this->responseController->makeResponse(true, "No se pudo registrar los empleados en el cronograma.", [], 400);
  920. }
  921. }
  922. $actions = DB::getQueryLog();
  923. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  924. $nameEmp = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  925. $idac = $this->functionsController->registerActivity(
  926. $form['linea'],
  927. 'S002V01M11GPRS',
  928. 'S002V01F01GEPE',
  929. 'S002V01P02REEM',
  930. 'Registro',
  931. "El usuario $name (" . $usr->USUA_IDUS . ") registró al empleado " . $nameEmp . "($employeeID).",
  932. $idUser,
  933. $nowStr,
  934. 'S002V01S02GEPE'
  935. );
  936. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  937. return $this->responseController->makeResponse(false, 'EXITO');
  938. }
  939. public function updateEmployee(Request $request) {
  940. DB::enableQueryLog();
  941. $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
  942. $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
  943. $request['CONTACT_NAME'] = $this->encryptionController->decrypt($request->CONTACT_NAME) ? $this->encryptionController->decrypt($request->CONTACT_NAME) : 'ENC_ERR';
  944. $request['CONTACT_TELEPHONE'] = $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) ? $this->encryptionController->decrypt($request->CONTACT_TELEPHONE) : 'ENC_ERR';
  945. $request['CONTACT_LADA'] = $this->encryptionController->decrypt($request->CONTACT_LADA) ? $this->encryptionController->decrypt($request->CONTACT_LADA) : 'ENC_ERR';
  946. $request['CONTACT_ADDRESS'] = $this->encryptionController->decrypt($request->CONTACT_ADDRESS) ? $this->encryptionController->decrypt($request->CONTACT_ADDRESS) : 'ENC_ERR';
  947. $validator = Validator::make($request->all(), [
  948. 'id_user' => 'required|string',
  949. 'linea' => 'required|integer',
  950. 'id_employee' => 'required|string',
  951. 'USER_ID' => 'required|string',
  952. 'WORKTEAM_ID' => 'required|string',
  953. 'CONTRACT_TYPE' => 'required|string|in:Subcontratista,Interno',
  954. 'SUBCONTRATIST_ID' => 'required_if:CONTRACT_TYPE,=,Subcontratista|string',
  955. 'SPECIALITY' => 'required|json',
  956. 'FOREIGNER' => 'required|string|in:Si,No',
  957. 'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
  958. 'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
  959. 'COUNTRY' => 'required|string|max:75',
  960. 'FEDERAL_ENTITY' => 'required|string|max:75',
  961. 'CITY' => 'string|max:75',
  962. 'TOWN' => 'string|max:75',
  963. 'SUBURB' => 'required|string|max:75',
  964. 'POSTAL_CODE' => 'required|string|max:5',
  965. 'STREET' => 'required|string|max:150',
  966. 'EXTERIOR_NUMBER' => 'required|integer',
  967. 'INTERIOR_NUMBER' => 'integer',
  968. 'CONTACT_NAME' => 'required|string|max:150',
  969. 'CONTACT_LADA' => 'required|string|max:10',
  970. 'CONTACT_TELEPHONE' => 'required|string|max:11',
  971. 'CONTACT_ADDRESS' => 'required|string|max:250',
  972. 'ATTACHED' => 'required|json',
  973. ]);
  974. if($validator->fails()){
  975. return $this->responseController->makeResponse(
  976. TRUE,
  977. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  978. $this->responseController->makeErrors($validator->errors()->messages()),
  979. 400
  980. );
  981. }
  982. $form = $request->all();
  983. foreach($form as $k=>$v){
  984. if($k == 'INTERIOR_NUMBER' && $v == '0'){
  985. unset($form[$k]);
  986. }else if($v == '-'){
  987. unset($form[$k]);
  988. }
  989. }
  990. $idUser = $this->encryptionController->decrypt($form['id_user']);
  991. if(!$idUser){
  992. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  993. }
  994. $usr = DB::table('S002V01TUSUA')->where([
  995. ['USUA_NULI', '=', $form['linea']],
  996. ['USUA_IDUS', '=', $idUser]
  997. ])->first();
  998. if(is_null($usr)){
  999. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1000. }
  1001. $idEmployee = $this->encryptionController->decrypt($form['id_employee']);
  1002. if(!$idEmployee){
  1003. return $this->responseController->makeResponse(true, 'El ID del empleado que desea actualizar no fue encriptado correctamente.', [], 400);
  1004. }
  1005. $employee = DB::table('S002V01TPERS')->where([
  1006. ['PERS_NULI', '=', $form['linea']],
  1007. ['PERS_IDPE', '=', $idEmployee]
  1008. ])->first();
  1009. if(is_null($employee)){
  1010. return $this->responseController->makeResponse(true, 'El empleado que desea actualizar no existe.', [], 404);
  1011. }
  1012. $idUserReg = $this->encryptionController->decrypt($form['USER_ID']);
  1013. if(!$idUserReg){
  1014. return $this->responseController->makeResponse(true, 'El ID del usuario seleccionado no fue encriptado correctamente.', [], 400);
  1015. }else if($idUser == $idUserReg){
  1016. return $this->responseController->makeResponse(true, 'El usuario no puede registrarse a sí mismo.', [], 400);
  1017. }
  1018. $usrReg = DB::table('S002V01TUSUA')->where([
  1019. ['USUA_NULI', '=', $form['linea']],
  1020. ['USUA_IDUS', '=', $idUserReg]
  1021. ])->first();
  1022. if(is_null($usrReg)){
  1023. return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404);
  1024. }
  1025. $idTeam = null;
  1026. if(isset($form['WORKTEAM_ID'])){
  1027. $idTeam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
  1028. if(!$idTeam){
  1029. return $this->responseController->makeResponse(true, 'El ID del equipo seleccionado encriptado correctamente.', [], 400);
  1030. }
  1031. $team = DB::table('S002V01TEQMA')->where([
  1032. ['EQMA_IDEQ', '=', $idTeam],
  1033. ['EQMA_NULI', '=', $form['linea']],
  1034. ])->first();
  1035. if(is_null($team)){
  1036. return $this->responseController->makeResponse(true, 'El equipo seleccionado no existe.', [], 404);
  1037. }else if($team->EQMA_ESTA == 'Eliminado'){
  1038. return $this->responseController->makeResponse(true, 'El equipo seleccionado está eliminado.', [], 404);
  1039. }
  1040. }
  1041. $idSubcontratist = null;
  1042. if(isset($form['SUBCONTRATIST_ID'])){
  1043. $idSubcontratist = $this->encryptionController->decrypt($form['SUBCONTRATIST_ID']);
  1044. if(!$idSubcontratist){
  1045. return $this->responseController->makeResponse(true, 'El ID del subcontratista seleccionado no fue encriptado correctamente.', [], 400);
  1046. }
  1047. $subcontratist = DB::table('S002V01TPESU')->where([
  1048. ['PESU_IDPS', '=', $idSubcontratist],
  1049. ['PESU_NULI', '=', $form['linea']],
  1050. ])->first();
  1051. if(is_null($subcontratist)){
  1052. return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404);
  1053. }
  1054. }
  1055. $rfcx = null;
  1056. if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
  1057. return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
  1058. }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
  1059. $rfcx = $form['RFC'];
  1060. }
  1061. $taid = null;
  1062. if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
  1063. return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
  1064. }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
  1065. $taid = $form['TAX'];
  1066. }
  1067. $country = DB::table('S002V01TPAIS')->where([
  1068. ['PAIS_NULI', '=', $form['linea']],
  1069. ['PAIS_IDPA', '=', $form['COUNTRY']],
  1070. ])->first();
  1071. if(is_null($country)){
  1072. return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
  1073. }
  1074. $colo = null;
  1075. $ciud = null;
  1076. $loca = null;
  1077. if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
  1078. $state = DB::table('S002V01TESTA')->where([
  1079. ['ESTA_NULI', '=', $form['linea']],
  1080. ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
  1081. ['ESTA_COPA', '=', $form['COUNTRY']],
  1082. ])->first();
  1083. if(is_null($state)){
  1084. return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
  1085. }
  1086. if($form['COUNTRY'] == 'MEX'){
  1087. if(isset($form['CITY'])){
  1088. $city = DB::table('S002V01TMUNI')->where([
  1089. ['MUNI_NULI', '=', $form['linea']],
  1090. ['MUNI_COMU', '=', $form['CITY']],
  1091. ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
  1092. ])->first();
  1093. if(is_null($city)){
  1094. return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
  1095. }else{
  1096. $ciud = $form['CITY'];
  1097. }
  1098. }
  1099. if(isset($form['TOWN'])){
  1100. $town = DB::table('S002V01TLOCA')->where([
  1101. ['LOCA_NULI', '=', $form['linea']],
  1102. ['LOCA_COLO', '=', $form['TOWN']],
  1103. ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
  1104. ])->first();
  1105. if(is_null($town)){
  1106. return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
  1107. }else{
  1108. $loca = $form['TOWN'];
  1109. }
  1110. }
  1111. $setting = DB::table('S002V01TCOLO')->where([
  1112. ['COLO_NULI', '=', $form['linea']],
  1113. ['COLO_COCO', '=', $form['SUBURB']],
  1114. ['COLO_COPO', '=', $form['POSTAL_CODE']],
  1115. ])->first();
  1116. if(is_null($setting)){
  1117. return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
  1118. }else{
  1119. $colo = $form['SUBURB'];
  1120. }
  1121. $zipCode = DB::table('S002V01TCOPO')->where([
  1122. ['COPO_NULI', '=', $form['linea']],
  1123. ['COPO_COPO', '=', $form['POSTAL_CODE']],
  1124. ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
  1125. ])->first();
  1126. if(is_null($zipCode)){
  1127. return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
  1128. }
  1129. }else{
  1130. $colo = $form['SUBURB'];
  1131. $ciud = $form['CITY'];
  1132. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  1133. }
  1134. }else{
  1135. $colo = $form['SUBURB'];
  1136. $ciud = $form['CITY'];
  1137. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  1138. }
  1139. $subArr = DB::table('S002V01TPERS')->where('PERS_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form, $idUserReg) {
  1140. $query->where('PERS_IDUS', '=', $idUserReg)
  1141. ->orWhere('PERS_XRFC', '=', $form['RFC']);
  1142. })->where([
  1143. ['PERS_ESTA', '=', 'Activo'],
  1144. ['PERS_IDPE', '!=', $idEmployee],
  1145. ])->get()->all();
  1146. if(count($subArr) > 0){
  1147. return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
  1148. }
  1149. $ladasValues = [];
  1150. $ladas = DB::table('S002V01TPAIS')->select([
  1151. 'PAIS_LADA AS LADA'
  1152. ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
  1153. foreach($ladas as $lada){
  1154. if($lada->LADA != '' && $lada->LADA != '0'){
  1155. $ladasValues[] = $lada->LADA;
  1156. }
  1157. }
  1158. if($form['CONTACT_LADA'] == 'ENC_ERR'){
  1159. return $this->responseController->makeResponse(true, "La lada del contacto de emergencia no fue encriptada correctamente.", [], 400);
  1160. }else if(!in_array($form['CONTACT_LADA'], $ladasValues)){
  1161. return $this->responseController->makeResponse(true, "La lada $form[CONTACT_LADA] no está relacionada a ningún país.", [], 400);
  1162. }else if($form['CONTACT_TELEPHONE'] == 'ENC_ERR'){
  1163. return $this->responseController->makeResponse(true, 'El número telefónico del contacto de emergencia no fue encriptado correctamente.', [], 400);
  1164. }
  1165. if($form['CONTACT_ADDRESS'] == 'ENC_ERR'){
  1166. return $this->responseController->makeResponse(true, "La dirección del contacto de emergencia no fue encriptada correctamente.", [], 400);
  1167. }
  1168. if($form['CONTACT_NAME'] == 'ENC_ERR'){
  1169. return $this->responseController->makeResponse(true, "El nombre del contacto de emergencia no fue encriptada correctamente.", [], 400);
  1170. }
  1171. $docsArr = json_decode($form['ATTACHED'], true);
  1172. if(count($docsArr) == 0){
  1173. return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos está vacío.", [], 400);
  1174. }
  1175. $authCont = 0;
  1176. foreach($docsArr as $doc){
  1177. if($doc['type'] == 'AU') $authCont++;
  1178. }
  1179. if($authCont < 1){
  1180. return $this->responseController->makeResponse(true, "El arreglo de archivos adjuntos debe contener al menos un documento de autorización.", [], 400);
  1181. }
  1182. $finalDocsArr = [];
  1183. foreach($docsArr as $doc){
  1184. if(!array_key_exists('isFinalFile', $doc)){
  1185. return $this->responseController->makeResponse(true, "La información del archivo $doc[name] no tiene un formato correcto.", [], 400);
  1186. }
  1187. if($doc['isFinalFile']){
  1188. $finalDocsArr[] = [
  1189. 'CODE' => $doc['name'],
  1190. 'TYPE' => $doc['type']
  1191. ];
  1192. }else{
  1193. $idFileDec = $this->encryptionController->decrypt($doc['id']);
  1194. $tempFile = DB::table('S002V01TARTE')->where([
  1195. ['ARTE_NULI', '=', $form['linea']],
  1196. ['ARTE_IDAR', '=', $idFileDec],
  1197. ])->first();
  1198. if(is_null($tempFile)){
  1199. return $this->responseController->makeResponse(true, "El archivo $doc[name] no está registrado.", [], 404);
  1200. }
  1201. $classifications = ["AU" => "IN", "OF" => "CO", "CE" => "CE"];
  1202. $cldo = $classifications[$doc['type']];
  1203. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], "GPRS", $cldo, $tempFile, $idUser);
  1204. if(!$finalFile[0]){
  1205. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  1206. }else{
  1207. $finalDocsArr[] = [
  1208. 'CODE' => $finalFile[1],
  1209. 'TYPE' => $doc['type']
  1210. ];
  1211. }
  1212. }
  1213. }
  1214. $doas = json_encode($finalDocsArr);
  1215. $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
  1216. $specialtiesArr = json_decode($form['SPECIALITY'], true);
  1217. foreach($specialtiesArr as $key=>$specialtyCode){
  1218. $specialtyCode = $this->encryptionController->decrypt($specialtyCode);
  1219. if(!$specialtyCode){
  1220. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  1221. }
  1222. $specialtyObj = DB::table('S002V01TGEES')->where([
  1223. ['GEES_NULI', '=', $form['linea']],
  1224. ['GEES_COES', '=', $specialtyCode]
  1225. ])->first();
  1226. if(is_null($specialtyObj)){
  1227. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades no existe.", [], 404);
  1228. }else if($specialtyObj->GEES_ESTA == 'Eliminado'){
  1229. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades está eliminado.", [], 404);
  1230. }
  1231. $specialtiesArr[$key] = $specialtyCode;
  1232. }
  1233. $specialtiesStr = json_encode($specialtiesArr);
  1234. $now = $this->functionsController->now();
  1235. $nowStr = $now->toDateTimeString();
  1236. DB::table('S002V01TPERS')->where([
  1237. ['PERS_NULI', '=', $form['linea']],
  1238. ['PERS_IDPE', '=', $idEmployee]
  1239. ])->update([
  1240. 'PERS_EQTR' => $idTeam,
  1241. 'PERS_TICO' => $form['CONTRACT_TYPE'],
  1242. 'PERS_IDPS' => $idSubcontratist,
  1243. 'PERS_ESPE' => $specialtiesStr,
  1244. 'PERS_EXTR' => $form['FOREIGNER'],
  1245. 'PERS_XRFC' => $rfcx,
  1246. 'PERS_TAID' => $taid,
  1247. 'PERS_IDPA' => $form['COUNTRY'],
  1248. 'PERS_ENFE' => $form['FEDERAL_ENTITY'],
  1249. 'PERS_CIUD' => $ciud,
  1250. 'PERS_LOCA' => $loca,
  1251. 'PERS_COLO' => $colo,
  1252. 'PERS_COPO' => $form['POSTAL_CODE'],
  1253. 'PERS_CALL' => $form['STREET'],
  1254. 'PERS_NUEX' => $form['EXTERIOR_NUMBER'],
  1255. 'PERS_NUIN' => $nuin,
  1256. 'PERS_NOCE' => $form['CONTACT_NAME'],
  1257. 'PERS_LCEM' => $form['CONTACT_LADA'],
  1258. 'PERS_NUTC' => $form['CONTACT_TELEPHONE'],
  1259. 'PERS_DCEM' => $form['CONTACT_ADDRESS'],
  1260. 'PERS_DOAS' => $doas,
  1261. 'PERS_USMO' => $idUser,
  1262. 'PERS_FEMO' => $nowStr,
  1263. ]);
  1264. if ( !is_null($form['EMPLOYEE_BOSS']) && $form['EMPLOYEE_BOSS'] !== '' && $form['EMPLOYEE_BOSS'] !== 'null') {
  1265. try {
  1266. $arrCronograma = (array) DB::table('S002V01TCREM')
  1267. ->where('CREM_IDES', '=', $idEmployee)
  1268. ->where('CREM_IDEJ', '=', $form['EMPLOYEE_BOSS'])
  1269. ->where('CREM_NULI', '=', $form['linea'])
  1270. ->first([
  1271. 'CREM_IDES AS ID_SUBORDINADO',
  1272. 'CREM_IDEJ AS IS_JEFE',
  1273. 'CREM_ESTA AS ESTADO',
  1274. ]);
  1275. } catch (\Throwable $th) {
  1276. return $this->responseController->makeResponse(true, "Ocurrió un error al obtener el cronograma.", [], 400);
  1277. }
  1278. if ( count($arrCronograma) === 0 ) {
  1279. try {
  1280. $validateRegister = DB::table('S002V01TCREM')->insert([
  1281. 'CREM_IDES' => $idEmployee,
  1282. 'CREM_IDEJ' => $form['EMPLOYEE_BOSS'],
  1283. 'CREM_NULI' => $form['linea'],
  1284. 'CREM_USRE' => $idUser,
  1285. 'CREM_FERE' => $nowStr,
  1286. 'CREM_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1287. ]);
  1288. } catch (Throwable $th) {
  1289. return $this->responseController->makeResponse(true, "Ocurrió un error al registrar el cronograma.", [], 400);
  1290. }
  1291. if (!$validateRegister) {
  1292. return $this->responseController->makeResponse(true, "No se pudo registrar los empleados en el cronograma.", [], 400);
  1293. }
  1294. } else {
  1295. try {
  1296. $validateUpdate = DB::table('S002V01TCREM')
  1297. ->where('CREM_IDES', '=', $idEmployee)
  1298. ->where('CREM_IDEJ', '=', $form['EMPLOYEE_BOSS'])
  1299. ->where('CREM_NULI', '=', $form['linea'])
  1300. ->update([
  1301. 'CREM_ESTA' => 'Activo',
  1302. 'CREM_USMO' => $idUser,
  1303. 'CREM_FEMO' => $nowStr,
  1304. 'CREM_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1305. ]);
  1306. } catch (\Throwable $th) {
  1307. return $this->responseController->makeResponse(true, "Ocurrió un error al modificar el cronograma.", [], 400);
  1308. }
  1309. if (!$validateUpdate) {
  1310. return $this->responseController->makeResponse(true, "No se pudo modificar los empleados en el cronograma.", [], 400);
  1311. }
  1312. }
  1313. }
  1314. $actions = DB::getQueryLog();
  1315. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1316. $nameEmp = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  1317. $idac = $this->functionsController->registerActivity(
  1318. $form['linea'],
  1319. 'S002V01M11GPRS',
  1320. 'S002V01F01GEPE',
  1321. 'S002V01P02REEM',
  1322. 'Actualización',
  1323. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó al empleado " . $nameEmp . "($idEmployee).",
  1324. $idUser,
  1325. $nowStr,
  1326. 'S002V01S02GEPE'
  1327. );
  1328. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1329. return $this->responseController->makeResponse(false, 'EXITO');
  1330. }
  1331. public function getScheduleActivitiesByEmployee($id, $user, $line) {
  1332. try {
  1333. $idEmployee = $this->encryptionController->decrypt($id);
  1334. } catch (\Throwable $th) {
  1335. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_GETACTIVITY000: Ocurrió un error al ibtener los datos.", $th->getMessage(), 404);
  1336. }
  1337. try {
  1338. $getSheduleActivities = DB::table('S002V01TCOAC')
  1339. ->where('COAC_NULI','=',$line)
  1340. ->where('COAC_ESTA','=','Activo')
  1341. ->where('COAC_IDPE','=',$idEmployee)
  1342. ->get([
  1343. 'COAC_IDAC AS ID_ACTIVIDAD',
  1344. 'COAC_IDPE AS ID_EMPLEADO',
  1345. 'COAC_ACTI AS ACTIVIDAD',
  1346. 'COAC_DESC AS DESCRIPCION',
  1347. 'COAC_TIPO AS TIPO_ACTIVIDAD',
  1348. 'COAC_OTPR AS ID_ORDEN_PREVENTIVO',
  1349. 'COAC_OTCO AS ID_ORDEN_CORRECTIVO',
  1350. 'COAC_FEIN AS FECHA_INICIO',
  1351. 'COAC_HOIN AS HORA_INICIO',
  1352. 'COAC_FEFE AS FECHA_FINAL',
  1353. 'COAC_HOFE AS HORA_FINAL',
  1354. 'COAC_FEFR AS FECHA_FINAL_REAL',
  1355. 'COAC_HOFR AS HORA_FINAL_REAL',
  1356. 'COAC_PERI AS PERIODICIDAD',
  1357. 'COAC_PEPE AS PERIODICIDAD_PERSONALIZADA',
  1358. 'COAC_CLAS AS CLASIFICACION',
  1359. 'COAC_COLO AS COLOR',
  1360. 'COAC_ESTA AS ESTADO',
  1361. 'COAC_FERE AS FECHA_REGISTRA',
  1362. 'COAC_USRE AS USUARIO_REGISTRA',
  1363. 'COAC_FEMO AS FECHA_MODIFICA',
  1364. 'COAC_USMO AS USUARIO_MODIFICA',
  1365. ]);
  1366. } catch (\Throwable $th) {
  1367. DB::rollBack();
  1368. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_GETACTIVITY001: Ocurrió un error al ibtener los datos.", $th->getMessage(), 404);
  1369. }
  1370. $arrSheduleActivities = json_decode(json_encode($getSheduleActivities), true);
  1371. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrSheduleActivities);
  1372. }
  1373. public function registerActivity(Request $request) {
  1374. $valitador = Validator::make($request->all(), [
  1375. 'ID_EMPLEADO' => 'required|string',
  1376. 'ACTIVIDAD' => 'required|string',
  1377. 'CLASIFICACION' => 'required|string',
  1378. 'DESCRIPCION' => 'required|string',
  1379. 'TIPO_ACTIVIDAD' => 'required|string',
  1380. 'ID_ORDEN' => 'nullable|string',
  1381. 'PERIODICIDAD' => 'nullable|string',
  1382. 'FECHA_INICIO' => 'required|string',
  1383. 'HORA_INICIO' => 'required|string',
  1384. 'FECHA_FINAL' => 'nullable|string',
  1385. 'HORA_FINAL' => 'nullable|string',
  1386. 'PERIODICIDAD_PERSONALIZADA' => 'nullable|string',
  1387. 'COLOR' => 'required|string',
  1388. 'USUARIO' => 'required|string',
  1389. 'NUMERO_LINEA' => 'required|integer',
  1390. ]);
  1391. if ($valitador->fails()) {
  1392. return $this->responseController->makeResponse(
  1393. true,
  1394. "ERR_EMPLOYEE_REGACTIVITY000: Se encontraron uno o más errores.",
  1395. $this->responseController->makeErrors($valitador->errors()->messages()),
  1396. 401
  1397. );
  1398. }
  1399. DB::beginTransaction();
  1400. $requestData = $request->all();
  1401. try {
  1402. $user = $this->encryptionController->decrypt($requestData['USUARIO']);
  1403. } catch (\Throwable $th) {
  1404. DB::rollBack();
  1405. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY001: Ocurrió un error al desencriptar los datos.", $th->getMessage(), 401);
  1406. }
  1407. try {
  1408. $validateUser = DB::table('S002V01TUSUA')
  1409. ->where('USUA_NULI', '=', $requestData['NUMERO_LINEA'])
  1410. ->where('USUA_IDUS', '=', $user)
  1411. ->exists();
  1412. } catch(\Throwable $th) {
  1413. DB::rollBack();
  1414. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY002: Ocurrió al verificar la existencia del usuario.", $th->getMessage(), 404);
  1415. }
  1416. if (!$validateUser) {
  1417. DB::rollBack();
  1418. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY003: El usuario no existe.", [], 404);
  1419. }
  1420. $idPreventiveMaintenance = null;
  1421. $idCorrectiveMaintenance = null;
  1422. if ($requestData['TIPO_ACTIVIDAD'] === 'MP') {
  1423. if (is_null($requestData['ID_ORDEN'])) {
  1424. DB::rollBack();
  1425. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY004: El ID de la orden de mantenimiento no viene incluida en los datos del formulario.", [], 404);
  1426. }
  1427. try {
  1428. $validateMaintenance = DB::table('S002V01TOTPR')
  1429. ->where('OTPR_IDOT', '=', $requestData['ID_ORDEN'])
  1430. ->where('OTPR_NULI', '=', $requestData['NUMERO_LINEA'])
  1431. ->exists();
  1432. } catch (\Throwable $th) {
  1433. DB::rollBack();
  1434. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY005: Ocurrió un error al validar la orden de mantenimiento.", $th->getMessage(), 404);
  1435. }
  1436. if (!$validateMaintenance) {
  1437. DB::rollBack();
  1438. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY006: La orden de trabajo no existe en la lista de mantenimientos preventivos.", [], 404);
  1439. }
  1440. $idPreventiveMaintenance = $requestData['ID_ORDEN'];
  1441. } else if ($requestData['TIPO_ACTIVIDAD'] === 'MC') {
  1442. if (is_null($requestData['ID_ORDEN'])) {
  1443. DB::rollBack();
  1444. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY007: El ID de la orden de mantenimiento no viene incluida en los datos del formulario.", [], 404);
  1445. }
  1446. try {
  1447. $validateMaintenance = DB::table('S002V01TOTCO')
  1448. ->where('OTCO_IDOT ', '=', $requestData['ID_ORDEN'])
  1449. ->where('OTCO_NULI ', '=', $requestData['NUMERO_LINEA'])
  1450. ->exists();
  1451. } catch (\Throwable $th) {
  1452. DB::rollBack();
  1453. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY008: Ocurrió un error al validar la orden de mantenimiento.", $th->getMessage(), 404);
  1454. }
  1455. if (!$validateMaintenance) {
  1456. DB::rollBack();
  1457. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY009: La orden de trabajo no existe en la lista de mantenimientos correctivo.", [], 404);
  1458. }
  1459. $idCorrectiveMaintenance = $requestData['ID_ORDEN'];
  1460. } else if ($requestData['TIPO_ACTIVIDAD'] === 'NA' && is_null($requestData['ID_ORDEN']) && !is_null($requestData['PERIODICIDAD']) ) {
  1461. if ($requestData['PERIODICIDAD'] === 'PE' && is_null($requestData['PERIODICIDAD_PERSONALIZADA'])) {
  1462. DB::rollBack();
  1463. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY010: El tipo de periodicidad personalizada debe estar incluida si el tipo de periodicidad está selecciona como Personalizada.", [], 404);
  1464. }
  1465. if ($requestData['PERIODICIDAD'] === 'NR' && (is_null($requestData['FECHA_FINAL']) | is_null($requestData['HORA_FINAL'])) ) {
  1466. DB::rollBack();
  1467. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY011: La fecha y la hora final esperada debe estar incluida en el formulario si la periodicidad está seleccionada como No se repite.", [], 404);
  1468. }
  1469. } else {
  1470. DB::rollBack();
  1471. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY012: El tipo de actividad no es correcto.", [], 404);
  1472. }
  1473. $now = $this->functionsController->now();
  1474. $currentDate = $now->toDateTimeString();
  1475. try {
  1476. $validateInsert = DB::table('S002V01TCOAC')->insert([
  1477. 'COAC_NULI' => $requestData['NUMERO_LINEA'],
  1478. 'COAC_IDPE' => $requestData['ID_EMPLEADO'],
  1479. 'COAC_ACTI' => $requestData['ACTIVIDAD'],
  1480. 'COAC_DESC' => $requestData['DESCRIPCION'],
  1481. 'COAC_TIPO' => $requestData['TIPO_ACTIVIDAD'],
  1482. 'COAC_OTPR' => $idPreventiveMaintenance,
  1483. 'COAC_OTCO' => $idCorrectiveMaintenance,
  1484. 'COAC_FEIN' => $requestData['FECHA_INICIO'],
  1485. 'COAC_HOIN' => $requestData['HORA_INICIO'],
  1486. 'COAC_FEFE' => $requestData['FECHA_FINAL'],
  1487. 'COAC_HOFE' => $requestData['HORA_FINAL'],
  1488. // 'COAC_FEFR' => $requestData[''],
  1489. // 'COAC_HOFR' => $requestData[''],
  1490. 'COAC_PERI' => $requestData['PERIODICIDAD'],
  1491. 'COAC_PEPE' => $requestData['PERIODICIDAD_PERSONALIZADA'],
  1492. 'COAC_CLAS' => $requestData['CLASIFICACION'],
  1493. 'COAC_COLO' => $requestData['COLOR'],
  1494. 'COAC_FERE' => $currentDate,
  1495. 'COAC_USRE' => $user,
  1496. 'COAC_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1497. ]);
  1498. } catch (\Throwable $th) {
  1499. DB::rollBack();
  1500. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY013: Ocurrió un error al insertar los datos.", $th->getMessage(), 404);
  1501. }
  1502. if (!$validateInsert) {
  1503. DB::rollBack();
  1504. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_REGACTIVITY014: No se pudo insertar los datos en la base de datos.", [], 404);
  1505. }
  1506. DB::commit();
  1507. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  1508. }
  1509. public function updateActivity(Request $request, $idActivity) {
  1510. $valitador = Validator::make($request->all(), [
  1511. // 'ID_ACTIVIDAD' => 'required|integer',
  1512. 'ID_EMPLEADO' => 'required|string',
  1513. 'ACTIVIDAD' => 'required|string',
  1514. 'CLASIFICACION' => 'required|string',
  1515. 'DESCRIPCION' => 'required|string',
  1516. 'TIPO_ACTIVIDAD' => 'required|string',
  1517. 'ID_ORDEN' => 'nullable|string',
  1518. 'PERIODICIDAD' => 'nullable|string',
  1519. 'FECHA_INICIO' => 'required|string',
  1520. 'HORA_INICIO' => 'required|string',
  1521. 'FECHA_FINAL' => 'nullable|string',
  1522. 'HORA_FINAL' => 'nullable|string',
  1523. 'PERIODICIDAD_PERSONALIZADA' => 'nullable|string',
  1524. 'COLOR' => 'required|string',
  1525. 'USUARIO' => 'required|string',
  1526. 'NUMERO_LINEA' => 'required|integer',
  1527. ]);
  1528. if ($valitador->fails()) {
  1529. return $this->responseController->makeResponse(
  1530. true,
  1531. "ERR_EMPLOYEE_UPDACTIVITY000: Se encontraron uno o más errores.",
  1532. $this->responseController->makeErrors($valitador->errors()->messages()),
  1533. 401
  1534. );
  1535. }
  1536. DB::beginTransaction();
  1537. $requestData = $request->all();
  1538. try {
  1539. $idActivity = $this->encryptionController->decrypt($idActivity);
  1540. } catch (\Throwable $th) {
  1541. DB::rollBack();
  1542. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY001: Ocurrió un error al desencriptar los datos de la actividad.", $th->getMessage(), 401);
  1543. }
  1544. try {
  1545. $user = $this->encryptionController->decrypt($requestData['USUARIO']);
  1546. } catch (\Throwable $th) {
  1547. DB::rollBack();
  1548. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY002: Ocurrió un error al desencriptar los datos.", $th->getMessage(), 401);
  1549. }
  1550. try {
  1551. $validateUser = DB::table('S002V01TUSUA')
  1552. ->where('USUA_NULI', '=', $requestData['NUMERO_LINEA'])
  1553. ->where('USUA_IDUS', '=', $user)
  1554. ->exists();
  1555. } catch(\Throwable $th) {
  1556. DB::rollBack();
  1557. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY003: Ocurrió al verificar la existencia del usuario.", $th->getMessage(), 404);
  1558. }
  1559. if (!$validateUser) {
  1560. DB::rollBack();
  1561. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY004: El usuario no existe.", [], 404);
  1562. }
  1563. $idPreventiveMaintenance = null;
  1564. $idCorrectiveMaintenance = null;
  1565. if ($requestData['TIPO_ACTIVIDAD'] === 'MP') {
  1566. if (is_null($requestData['ID_ORDEN'])) {
  1567. DB::rollBack();
  1568. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY005: El ID de la orden de mantenimiento no viene incluida en los datos del formulario.", [], 404);
  1569. }
  1570. try {
  1571. $validateMaintenance = DB::table('S002V01TOTPR')
  1572. ->where('OTPR_IDOT', '=', $requestData['ID_ORDEN'])
  1573. ->where('OTPR_NULI', '=', $requestData['NUMERO_LINEA'])
  1574. ->exists();
  1575. } catch (\Throwable $th) {
  1576. DB::rollBack();
  1577. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY006: Ocurrió un error al validar la orden de mantenimiento.", $th->getMessage(), 404);
  1578. }
  1579. if (!$validateMaintenance) {
  1580. DB::rollBack();
  1581. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY007: La orden de trabajo no existe en la lista de mantenimientos preventivos.", [], 404);
  1582. }
  1583. $idPreventiveMaintenance = $requestData['ID_ORDEN'];
  1584. } else if ($requestData['TIPO_ACTIVIDAD'] === 'MC') {
  1585. if (is_null($requestData['ID_ORDEN'])) {
  1586. DB::rollBack();
  1587. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY008: El ID de la orden de mantenimiento no viene incluida en los datos del formulario.", [], 404);
  1588. }
  1589. try {
  1590. $validateMaintenance = DB::table('S002V01TOTCO')
  1591. ->where('OTCO_IDOT ', '=', $requestData['ID_ORDEN'])
  1592. ->where('OTCO_NULI ', '=', $requestData['NUMERO_LINEA'])
  1593. ->exists();
  1594. } catch (\Throwable $th) {
  1595. DB::rollBack();
  1596. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY009: Ocurrió un error al validar la orden de mantenimiento.", $th->getMessage(), 404);
  1597. }
  1598. if (!$validateMaintenance) {
  1599. DB::rollBack();
  1600. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY010: La orden de trabajo no existe en la lista de mantenimientos correctivo.", [], 404);
  1601. }
  1602. $idCorrectiveMaintenance = $requestData['ID_ORDEN'];
  1603. } else if ($requestData['TIPO_ACTIVIDAD'] === 'NA' && is_null($requestData['ID_ORDEN']) && !is_null($requestData['PERIODICIDAD']) ) {
  1604. if ($requestData['PERIODICIDAD'] === 'PE' && is_null($requestData['PERIODICIDAD_PERSONALIZADA'])) {
  1605. DB::rollBack();
  1606. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY011: El tipo de periodicidad personalizada debe estar incluida si el tipo de periodicidad está selecciona como Personalizada.", [], 404);
  1607. }
  1608. if ($requestData['PERIODICIDAD'] === 'NR' && (is_null($requestData['FECHA_FINAL']) | is_null($requestData['HORA_FINAL'])) ) {
  1609. DB::rollBack();
  1610. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY012: La fecha y la hora final esperada debe estar incluida en el formulario si la periodicidad está seleccionada como No se repite.", [], 404);
  1611. }
  1612. } else {
  1613. DB::rollBack();
  1614. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY013: El tipo de actividad no es correcto.", [], 404);
  1615. }
  1616. $now = $this->functionsController->now();
  1617. $currentDate = $now->toDateTimeString();
  1618. try {
  1619. $validateInsert = DB::table('S002V01TCOAC')
  1620. ->where('COAC_IDAC','=',$idActivity)
  1621. ->where('COAC_NULI','=',$requestData['NUMERO_LINEA'])
  1622. ->where('COAC_IDPE','=',$requestData['ID_EMPLEADO'])
  1623. ->update([
  1624. 'COAC_ACTI' => $requestData['ACTIVIDAD'],
  1625. 'COAC_DESC' => $requestData['DESCRIPCION'],
  1626. 'COAC_TIPO' => $requestData['TIPO_ACTIVIDAD'],
  1627. 'COAC_OTPR' => $idPreventiveMaintenance,
  1628. 'COAC_OTCO' => $idCorrectiveMaintenance,
  1629. 'COAC_FEIN' => $requestData['FECHA_INICIO'],
  1630. 'COAC_HOIN' => $requestData['HORA_INICIO'],
  1631. 'COAC_FEFE' => $requestData['FECHA_FINAL'],
  1632. 'COAC_HOFE' => $requestData['HORA_FINAL'],
  1633. // 'COAC_FEFR' => $requestData[''],
  1634. // 'COAC_HOFR' => $requestData[''],
  1635. 'COAC_PERI' => $requestData['PERIODICIDAD'],
  1636. 'COAC_PEPE' => $requestData['PERIODICIDAD_PERSONALIZADA'],
  1637. 'COAC_CLAS' => $requestData['CLASIFICACION'],
  1638. 'COAC_COLO' => $requestData['COLOR'],
  1639. 'COAC_FEMO' => $currentDate,
  1640. 'COAC_USMO' => $user,
  1641. 'COAC_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1642. ]);
  1643. } catch (\Throwable $th) {
  1644. DB::rollBack();
  1645. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY014: Ocurrió un error al insertar los datos.", $th->getMessage(), 404);
  1646. }
  1647. if (!$validateInsert) {
  1648. DB::rollBack();
  1649. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_UPDACTIVITY015: No se pudo insertar los datos en la base de datos.", [], 404);
  1650. }
  1651. DB::commit();
  1652. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  1653. }
  1654. public function deleteActivity(Request $request, $idActivity) {
  1655. $valitador = Validator::make($request->all(), [
  1656. 'USUARIO' => 'required|string',
  1657. 'NUMERO_LINEA' => 'required|integer',
  1658. ]);
  1659. if ($valitador->fails()) {
  1660. return $this->responseController->makeResponse(
  1661. true,
  1662. "ERR_EMPLOYEE_DELACTIVITY000: Se encontraron uno o más errores.",
  1663. $this->responseController->makeErrors($valitador->errors()->messages()),
  1664. 401
  1665. );
  1666. }
  1667. DB::beginTransaction();
  1668. $requestData = $request->all();
  1669. try {
  1670. $idActivity = $this->encryptionController->decrypt($idActivity);
  1671. } catch (\Throwable $th) {
  1672. DB::rollBack();
  1673. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_DELACTIVITY001: Ocurrió un error al desencriptar los datos.", $th->getMessage(), 401);
  1674. }
  1675. try {
  1676. $user = $this->encryptionController->decrypt($requestData['USUARIO']);
  1677. } catch (\Throwable $th) {
  1678. DB::rollBack();
  1679. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_DELACTIVITY002: Ocurrió un error al desencriptar los datos.", $th->getMessage(), 401);
  1680. }
  1681. $now = $this->functionsController->now();
  1682. $currentDate = $now->toDateTimeString();
  1683. try {
  1684. $validateDelete = DB::table('S002V01TCOAC')
  1685. ->where('COAC_NULI', '=', $requestData['NUMERO_LINEA'])
  1686. ->where('COAC_IDAC', '=', $idActivity)
  1687. ->update([
  1688. 'COAC_ESTA' => 'Eliminado',
  1689. 'COAC_FEMO' => $currentDate,
  1690. 'COAC_USMO' => $user,
  1691. 'COAC_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1692. ]);
  1693. } catch (\Throwable $th) {
  1694. DB::rollBack();
  1695. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_DELACTIVITY003: Ocurrió un error al eliminar la actividad.", $th->getMessage(), 401);
  1696. }
  1697. if (!$validateDelete) {
  1698. DB::rollBack();
  1699. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_DELACTIVITY004: No se pudo eliminar la actividad.", [], 401);
  1700. }
  1701. DB::commit();
  1702. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  1703. }
  1704. public function getScheduleActivitiesByActivity($id, $user, $line) {
  1705. try {
  1706. $idActivity = $this->encryptionController->decrypt($id);
  1707. } catch (\Throwable $th) {
  1708. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_GETACTIVITY000: Ocurrió un error al ibtener los datos.", $th->getMessage(), 404);
  1709. }
  1710. try {
  1711. $arrSheduleActivities = (array) DB::table('S002V01TCOAC')
  1712. ->where('COAC_NULI','=',$line)
  1713. ->where('COAC_ESTA','=','Activo')
  1714. ->where('COAC_IDAC','=',$idActivity)
  1715. ->first([
  1716. 'COAC_IDPE AS ID_EMPLEADO',
  1717. 'COAC_ACTI AS ACTIVIDAD',
  1718. 'COAC_DESC AS DESCRIPCION',
  1719. 'COAC_TIPO AS TIPO_ACTIVIDAD',
  1720. 'COAC_OTPR AS ID_ORDEN_PREVENTIVO',
  1721. 'COAC_OTCO AS ID_ORDEN_CORRECTIVO',
  1722. 'COAC_FEIN AS FECHA_INICIO',
  1723. 'COAC_HOIN AS HORA_INICIO',
  1724. 'COAC_FEFE AS FECHA_FINAL',
  1725. 'COAC_HOFE AS HORA_FINAL',
  1726. 'COAC_FEFR AS FECHA_FINAL_REAL',
  1727. 'COAC_HOFR AS HORA_FINAL_REAL',
  1728. 'COAC_PERI AS PERIODICIDAD',
  1729. 'COAC_PEPE AS PERIODICIDAD_PERSONALIZADA',
  1730. 'COAC_CLAS AS CLASIFICACION',
  1731. 'COAC_COLO AS COLOR',
  1732. 'COAC_ESTA AS ESTADO',
  1733. 'COAC_FERE AS FECHA_REGISTRA',
  1734. 'COAC_USRE AS USUARIO_REGISTRA',
  1735. 'COAC_FEMO AS FECHA_MODIFICA',
  1736. 'COAC_USMO AS USUARIO_MODIFICA',
  1737. ]);
  1738. } catch (\Throwable $th) {
  1739. DB::rollBack();
  1740. return $this->responseController->makeResponse(true, "ERR_EMPLOYEE_GETACTIVITY001: Ocurrió un error al ibtener los datos.", $th->getMessage(), 404);
  1741. }
  1742. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrSheduleActivities);
  1743. }
  1744. public function getConsultOfSubcontratists($idUser, $line) {
  1745. DB::enableQueryLog();
  1746. $idUser = $this->encryptionController->decrypt($idUser);
  1747. if(!$idUser){
  1748. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  1749. }
  1750. $usr = DB::table('S002V01TUSUA')->where([
  1751. ['USUA_NULI', '=', $line],
  1752. ['USUA_IDUS', '=', $idUser],
  1753. ])->first();
  1754. if(is_null($usr)){
  1755. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  1756. }
  1757. $subcontratists = DB::table('S002V01TPESU')->select([
  1758. 'PESU_IDPS as ID_SUBCONTRATIST',
  1759. DB::raw('CONCAT(PESU_RASO, " (" , COALESCE(PESU_REFI, ""), ")") AS NAME'),
  1760. 'PESU_EXTR AS TIPO',
  1761. 'PESU_ESPE AS SPECIALTY',
  1762. 'PESU_FERE AS REGISTER_DATE',
  1763. 'PESU_FEMO AS UPDATE_DATE',
  1764. 'PESU_USRE AS REGISTERED_BY_USER',
  1765. 'PESU_USMO AS UPDATED_BY_USER',
  1766. 'PESU_ESTA AS STATUS'
  1767. ])->where('PESU_NULI', '=', $line)->get()->all();
  1768. foreach($subcontratists as $subcontratist){
  1769. $regUsr = DB::table('S002V01TUSUA')->where([
  1770. ['USUA_NULI', '=', $line],
  1771. ['USUA_IDUS', '=', $subcontratist->REGISTERED_BY_USER],
  1772. ])->first();
  1773. if(!is_null($regUsr)){
  1774. $subcontratist->REGISTERED_BY_USER = $this->functionsController->joinName($regUsr->USUA_NOMB, $regUsr->USUA_APPA, $regUsr->USUA_APMA) . " (" . $subcontratist->REGISTERED_BY_USER . ")";
  1775. }else{
  1776. $subcontratist->REGISTERED_BY_USER = "DESCONOCIDO (" . $subcontratist->REGISTERED_BY_USER . ")";
  1777. }
  1778. if(!is_null($subcontratist->UPDATED_BY_USER)){
  1779. $modUsr = DB::table('S002V01TUSUA')->where([
  1780. ['USUA_NULI', '=', $line],
  1781. ['USUA_IDUS', '=', $subcontratist->UPDATED_BY_USER],
  1782. ])->first();
  1783. if(!is_null($modUsr)){
  1784. $subcontratist->UPDATED_BY_USER = $this->functionsController->joinName($modUsr->USUA_NOMB, $modUsr->USUA_APPA, $modUsr->USUA_APMA) . " (" . $subcontratist->UPDATED_BY_USER . ")";
  1785. }else{
  1786. $subcontratist->UPDATED_BY_USER = "DESCONOCIDO (" . $subcontratist->UPDATED_BY_USER . ")";
  1787. }
  1788. }
  1789. if($subcontratist->TIPO == 'No'){
  1790. $subcontratist->TIPO = 'Nacional';
  1791. }else{
  1792. $subcontratist->TIPO = 'Extranjero';
  1793. }
  1794. $preventiveInterventions = DB::select("
  1795. SELECT
  1796. DISTINCT(S002V01TOTPR.OTPR_IDOT),
  1797. OPPR.*
  1798. FROM
  1799. S002V01TOTPR,
  1800. JSON_TABLE(OTPR_OPPR, '$[*]' COLUMNS(
  1801. OTPR_OPPR_ID INT PATH '$.ID',
  1802. OTPR_OPPR_TYPE VARCHAR(100) PATH '$.TYPE'
  1803. )) OPPR
  1804. WHERE
  1805. OPPR.OTPR_OPPR_TYPE = :emp_type
  1806. AND OPPR.OTPR_OPPR_ID = :emp_id
  1807. ", ['emp_type' => 'SU', 'emp_id' => $subcontratist->ID_SUBCONTRATIST]);
  1808. //PENDIENTE IMPLEMENTAR INTERVENCIONES DE MANTENIMIENTO CORRECTIVO
  1809. $subcontratist->INTERVENTIONS_COUNT = count($preventiveInterventions);
  1810. $subcontratist->ID_SUBCONTRATIST = $this->encryptionController->encrypt($subcontratist->ID_SUBCONTRATIST);
  1811. }
  1812. $now = $this->functionsController->now();
  1813. $nowStr = $now->toDateTimeString();
  1814. $actions = DB::getQueryLog();
  1815. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1816. $idac = $this->functionsController->registerActivity(
  1817. $line,
  1818. 'S002V01M11GPRS',
  1819. 'S002V01F01GESU',
  1820. 'S002V01P01COSU',
  1821. 'Consulta',
  1822. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los subcontratistas registrados.",
  1823. $idUser,
  1824. $nowStr,
  1825. 'S002V01S01GESU'
  1826. );
  1827. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1828. return $this->responseController->makeResponse(false, 'EXITO', $subcontratists);
  1829. }
  1830. public function storeSubcontratist(Request $request) {
  1831. DB::enableQueryLog();
  1832. $request['TELEPHONE1'] = $this->encryptionController->decrypt($request->TELEPHONE1) ? $this->encryptionController->decrypt($request->TELEPHONE1) : 'ENC_ERR';
  1833. $request['TELEPHONE2'] = $this->encryptionController->decrypt($request->TELEPHONE2) ? $this->encryptionController->decrypt($request->TELEPHONE2) : 'ENC_ERR';
  1834. $request['EMAIL'] = $this->encryptionController->decrypt($request->EMAIL) ? $this->encryptionController->decrypt($request->EMAIL) : 'ENC_ERR';
  1835. if ( !is_null($request->RFC) ) {
  1836. $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
  1837. }
  1838. if ( !is_null($request->TAX) ) {
  1839. $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
  1840. }
  1841. $validator = Validator::make($request->all(), [
  1842. 'id_user' => 'required|string',
  1843. 'linea' => 'required|integer',
  1844. 'SOCIAL_REASON' => 'required|string|max:150',
  1845. 'TAX_REFERENCE' => 'required|string|max:15',
  1846. 'CONTRACT_TYPE' => 'required|string|in:Persona moral,Persona física',
  1847. 'FOREIGNER' => 'required|string|in:Si,No',
  1848. 'RFC' => 'required_if:FOREIGNER,=,No',
  1849. 'TAX' => 'required_if:FOREIGNER,=,Si',
  1850. 'EMAIL' => 'required|string|max:150',
  1851. 'COUNTRY' => 'required|string|max:75',
  1852. 'FEDERAL_ENTITY' => 'required|string|max:75',
  1853. 'CITY' => 'string|max:75',
  1854. 'TOWN' => 'string|max:75',
  1855. 'SUBURB' => 'required|string|max:75',
  1856. 'POSTAL_CODE' => 'required|string|max:5',
  1857. 'STREET' => 'required|string|max:150',
  1858. 'EXTERIOR_NUMBER' => 'required|string',
  1859. 'INTERIOR_NUMBER' => 'string',
  1860. 'LADA1' => 'required|string|max:15',
  1861. 'TELEPHONE1' => 'required|string|min:7|max:11',
  1862. 'LADA2' => 'string|max:15',
  1863. 'TELEPHONE2' => 'string|min:7|max:11',
  1864. 'SPECIALTY' => 'required|json',
  1865. 'PROVIDER' => 'string|max:10'
  1866. ]);
  1867. if($validator->fails()){
  1868. return $this->responseController->makeResponse(
  1869. true,
  1870. "Se encontraron uno o más errores.",
  1871. $this->responseController->makeErrors($validator->errors()->messages()),
  1872. 401
  1873. );
  1874. }
  1875. $form = $request->all();
  1876. foreach($form as $k=>$v){
  1877. if($k == 'INTERIOR_NUMBER' && $v == '0'){
  1878. unset($form[$k]);
  1879. }else if($v == '-'){
  1880. unset($form[$k]);
  1881. }
  1882. }
  1883. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1884. if(!$idUser){
  1885. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1886. }
  1887. $usr = DB::table('S002V01TUSUA')->where([
  1888. ['USUA_NULI', '=', $form['linea']],
  1889. ['USUA_IDUS', '=', $idUser]
  1890. ])->first();
  1891. if(is_null($usr)){
  1892. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1893. }
  1894. $ladasValues = [];
  1895. $ladas = DB::table('S002V01TPAIS')->select([
  1896. 'PAIS_LADA AS LADA'
  1897. ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
  1898. foreach($ladas as $lada){
  1899. if($lada->LADA != '' && $lada->LADA != '0'){
  1900. $ladasValues[] = $lada->LADA;
  1901. }
  1902. }
  1903. if(!in_array($form['LADA1'], $ladasValues)){
  1904. return $this->responseController->makeResponse(true, "La lada $form[LADA1] no está relacionada a ningún país.", [], 400);
  1905. }else if($form['TELEPHONE1'] == 'ENC_ERR'){
  1906. return $this->responseController->makeResponse(true, 'El número telefónico 1 no fue encriptado correctamente.', [], 400);
  1907. }
  1908. $lada2 = null;
  1909. $phone2 = null;
  1910. if(isset($form['LADA2'])){
  1911. if(!in_array($form['LADA2'], $ladasValues)){
  1912. return $this->responseController->makeResponse(true, "La lada $form[LADA2] no está relacionada a ningún país.", [], 400);
  1913. }else if($form['TELEPHONE2'] == 'ENC_ERR'){
  1914. return $this->responseController->makeResponse(true, 'El número telefónico 2 no fue encriptado correctamente.', [], 400);
  1915. }
  1916. $lada2 = $form['LADA2'];
  1917. $phone2 = $form['TELEPHONE2'];
  1918. }
  1919. if($form['EMAIL'] == 'ENC_ERR'){
  1920. return $this->responseController->makeResponse(true, 'El email no fue encriptado correctamente.', [], 400);
  1921. }
  1922. $rfcx = null;
  1923. if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
  1924. return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
  1925. }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
  1926. $rfcx = $form['RFC'];
  1927. }
  1928. $taid = null;
  1929. if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
  1930. return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
  1931. }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
  1932. $taid = $form['TAX'];
  1933. }
  1934. $country = DB::table('S002V01TPAIS')->where([
  1935. ['PAIS_NULI', '=', $form['linea']],
  1936. ['PAIS_IDPA', '=', $form['COUNTRY']],
  1937. ])->first();
  1938. if(is_null($country)){
  1939. return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
  1940. }
  1941. $taxRegime = DB::table('S002V01TREFI')->where([
  1942. ['REFI_NULI', '=', $form['linea']],
  1943. ['REFI_CRFI', '=', $form['TAX_REFERENCE']],
  1944. ])->first();
  1945. if(is_null($taxRegime)){
  1946. return $this->responseController->makeResponse(true, 'El régimen fiscal seleccionado no existe.', [], 404);
  1947. }
  1948. $colo = null;
  1949. $ciud = null;
  1950. $loca = null;
  1951. if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
  1952. $state = DB::table('S002V01TESTA')->where([
  1953. ['ESTA_NULI', '=', $form['linea']],
  1954. ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
  1955. ['ESTA_COPA', '=', $form['COUNTRY']],
  1956. ])->first();
  1957. if(is_null($state)){
  1958. return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
  1959. }
  1960. if($form['COUNTRY'] == 'MEX'){
  1961. if(isset($form['CITY'])){
  1962. $city = DB::table('S002V01TMUNI')->where([
  1963. ['MUNI_NULI', '=', $form['linea']],
  1964. ['MUNI_COMU', '=', $form['CITY']],
  1965. ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
  1966. ])->first();
  1967. if(is_null($city)){
  1968. return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
  1969. }else{
  1970. $ciud = $form['CITY'];
  1971. }
  1972. }
  1973. if(isset($form['TOWN'])){
  1974. $town = DB::table('S002V01TLOCA')->where([
  1975. ['LOCA_NULI', '=', $form['linea']],
  1976. ['LOCA_COLO', '=', $form['TOWN']],
  1977. ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
  1978. ])->first();
  1979. if(is_null($town)){
  1980. return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
  1981. }else{
  1982. $loca = $form['TOWN'];
  1983. }
  1984. }
  1985. if ($form['FOREIGNER'] === 'No') {
  1986. $setting = DB::table('S002V01TCOLO')->where([
  1987. ['COLO_NULI', '=', $form['linea']],
  1988. ['COLO_COCO', '=', $form['SUBURB']],
  1989. ['COLO_COPO', '=', $form['POSTAL_CODE']],
  1990. ])->first();
  1991. if(is_null($setting)){
  1992. return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
  1993. }else{
  1994. $colo = $form['SUBURB'];
  1995. }
  1996. } else {
  1997. $colo = $form['SUBURB'];
  1998. }
  1999. $zipCode = DB::table('S002V01TCOPO')->where([
  2000. ['COPO_NULI', '=', $form['linea']],
  2001. ['COPO_COPO', '=', $form['POSTAL_CODE']],
  2002. ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
  2003. ])->first();
  2004. if(is_null($zipCode)){
  2005. return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
  2006. }
  2007. }else{
  2008. $colo = $form['SUBURB'];
  2009. $ciud = $form['CITY'];
  2010. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  2011. }
  2012. }else{
  2013. $colo = $form['SUBURB'];
  2014. $ciud = $form['CITY'];
  2015. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  2016. }
  2017. if (!is_null($form['RFC'])) {
  2018. $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
  2019. $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
  2020. ->orWhere('PESU_XRFC', '=', $form['RFC'])
  2021. ->orWhere('PESU_CORR', '=', $form['EMAIL']);
  2022. })->where('PESU_ESTA', '=', 'Activo')->get()->all();
  2023. if(count($subArr) > 0){
  2024. return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados. 1', [], 401);
  2025. }
  2026. }
  2027. if (!is_null($form['TAX'])) {
  2028. $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
  2029. $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
  2030. ->orWhere('PESU_TAID', '=', $form['TAX'])
  2031. ->orWhere('PESU_CORR', '=', $form['EMAIL']);
  2032. })->where('PESU_ESTA', '=', 'Activo')->get()->all();
  2033. if(count($subArr) > 0){
  2034. return $this->responseController->makeResponse(true, 'La razón social, el Tax ID o el correo electrónico ya fueron registrados. 2', [], 401);
  2035. }
  2036. }
  2037. $idProvider = null;
  2038. if ( array_key_exists('PROVIDER', $form) ) {
  2039. $idProvider = $form['PROVIDER'];
  2040. try {
  2041. $validateExist = DB::table('S002V01TPROV')
  2042. ->where('PROV_NUPR', '=', $idProvider)
  2043. ->where('PROV_NULI', '=', $form['linea'])
  2044. ->exists();
  2045. } catch (\Throwable $th) {
  2046. DB::rollBack();
  2047. return $this->responseController->makeResponse(true, "Ocurrió un error al obtener el proveedor.", $th->getMessage(), 500);
  2048. }
  2049. if (!$validateExist) {
  2050. DB::rollBack();
  2051. return $this->responseController->makeResponse(true, "El número del proveedor no existe.", [], 500);
  2052. }
  2053. }
  2054. $specialtiesArr = json_decode($form['SPECIALTY'], true);
  2055. foreach($specialtiesArr as $key=>$specialtyCode){
  2056. $specialtyCode = $this->encryptionController->decrypt($specialtyCode);
  2057. if(!$specialtyCode){
  2058. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  2059. }
  2060. $specialtyObj = DB::table('S002V01TGEES')->where([
  2061. ['GEES_NULI', '=', $form['linea']],
  2062. ['GEES_COES', '=', $specialtyCode]
  2063. ])->first();
  2064. if(is_null($specialtyObj)){
  2065. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades no existe.", [], 404);
  2066. }else if($specialtyObj->GEES_ESTA == 'Eliminado'){
  2067. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades está eliminado.", [], 404);
  2068. }
  2069. $specialtiesArr[$key] = $specialtyCode;
  2070. }
  2071. $specialtiesStr = json_encode($specialtiesArr);
  2072. $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
  2073. $now = $this->functionsController->now();
  2074. $nowStr = $now->toDateTimeString();
  2075. $subcontratistID = DB::table('S002V01TPESU')->insertGetId([
  2076. 'PESU_NULI' => $form['linea'],
  2077. 'PESU_NUPR' => $idProvider,
  2078. 'PESU_RASO' => $form['SOCIAL_REASON'],
  2079. 'PESU_REFI' => $form['TAX_REFERENCE'],
  2080. 'PESU_XRFC' => $rfcx === '' ? null : $rfcx,
  2081. 'PESU_TIPO' => $form['CONTRACT_TYPE'],
  2082. 'PESU_CORR' => $form['EMAIL'],
  2083. 'PESU_EXTR' => $form['FOREIGNER'],
  2084. 'PESU_TAID' => $taid === '' ? null : $taid,
  2085. 'PESU_CALL' => $form['STREET'],
  2086. 'PESU_NUEX' => $form['EXTERIOR_NUMBER'],
  2087. 'PESU_NUIN' => $nuin,
  2088. 'PESU_COLO' => $colo,
  2089. 'PESU_CIUD' => $ciud,
  2090. 'PESU_LOCA' => $loca,
  2091. 'PESU_COPO' => $form['POSTAL_CODE'],
  2092. 'PESU_ENFE' => $form['FEDERAL_ENTITY'],
  2093. 'PESU_IDPA' => $form['COUNTRY'],
  2094. 'PESU_TEL1' => $form['TELEPHONE1'],
  2095. 'PESU_LAT1' => $form['LADA1'],
  2096. 'PESU_TEL2' => $phone2,
  2097. 'PESU_LAT2' => $lada2,
  2098. 'PESU_ESPE' => $specialtiesStr,
  2099. 'PESU_USRE' => $idUser,
  2100. 'PESU_FERE' => $nowStr,
  2101. ]);
  2102. if (!is_null($idProvider)) {
  2103. try {
  2104. $validateUpdate = DB::table('S002V01TPROV')
  2105. ->where('PROV_NUPR', '=', $idProvider)
  2106. ->where('PROV_NULI', '=', $form['linea'])
  2107. ->update([
  2108. 'PROV_IDPS' => $subcontratistID,
  2109. 'PROV_USMO' => $idUser,
  2110. 'PROV_FEMO' => $nowStr,
  2111. 'PROV_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  2112. ]);
  2113. } catch (\Throwable $th) {
  2114. DB::rollBack();
  2115. return $this->responseController->makeResponse(true, "Ocurrió un error al modificar el proveedor.", $th->getMessage(), 500);
  2116. }
  2117. if (!$validateUpdate) {
  2118. DB::rollBack();
  2119. return $this->responseController->makeResponse(true, "No se pudo modificar el proveedor.", [], 500);
  2120. }
  2121. }
  2122. $response = array( 'idSubcontract' => $subcontratistID );
  2123. $actions = DB::getQueryLog();
  2124. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2125. $idac = $this->functionsController->registerActivity(
  2126. $form['linea'],
  2127. 'S002V01M11GPRS',
  2128. 'S002V01F01GESU',
  2129. 'S002V01P02RESU',
  2130. 'Registro',
  2131. "El usuario $name (" . $usr->USUA_IDUS . ") registró al subcontratista $form[SOCIAL_REASON] ($subcontratistID).",
  2132. $idUser,
  2133. $nowStr,
  2134. 'S002V01S01GESU'
  2135. );
  2136. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2137. return $this->responseController->makeResponse(false, 'EXITO', $response);
  2138. }
  2139. public function getSubcontratistById($idSub, $idUser, $line) {
  2140. DB::enableQueryLog();
  2141. $idUser = $this->encryptionController->decrypt($idUser);
  2142. if(!$idUser){
  2143. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la consulta no está encriptado correctamente.', [], 400);
  2144. }
  2145. $usr = DB::table('S002V01TUSUA')->where([
  2146. ['USUA_IDUS', '=', $idUser],
  2147. ['USUA_NULI', '=', $line]
  2148. ])->first();
  2149. if(is_null($usr)){
  2150. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  2151. }
  2152. $idSub = $this->encryptionController->decrypt($idSub);
  2153. if(!$idSub){
  2154. return $this->responseController->makeResponse(true, 'El ID del subcontratista consultado no está encriptado correctamente.', [], 400);
  2155. }
  2156. $subcontratists_info = DB::table('S002V01TPESU')->select([
  2157. 'PESU_IDPS as ID_SUBCONTRATIST',
  2158. 'PESU_RASO as SOCIAL_REASON',
  2159. 'PESU_REFI as TAX_REFERENCE',
  2160. 'PESU_XRFC as RFC',
  2161. 'PESU_TIPO as CONTRACT_TYPE',
  2162. 'PESU_CORR as EMAIL',
  2163. 'PESU_EXTR as FOREIGNER',
  2164. 'PESU_TAID as TAX',
  2165. 'PESU_CALL as STREET',
  2166. 'PESU_NUEX as EXTERIOR_NUMBER',
  2167. 'PESU_NUIN as INTERIOR_NUMBER',
  2168. 'PESU_COLO as SUBURB',
  2169. 'PESU_CIUD as CITY',
  2170. 'PESU_LOCA as TOWN',
  2171. 'PESU_COPO as POSTAL_CODE',
  2172. 'PESU_ENFE as FEDERAL_ENTITY',
  2173. 'PESU_IDPA as COUNTRY',
  2174. 'PESU_TEL1 as TELEPHONE1',
  2175. 'PESU_LAT1 as LADA1',
  2176. 'PESU_TEL2 as TELEPHONE2',
  2177. 'PESU_LAT2 as LADA2',
  2178. 'PESU_ESPE as SPECIALTY',
  2179. 'PESU_ESTA as STATUS'
  2180. ])->where([
  2181. ['PESU_NULI', '=', $line],
  2182. ['PESU_IDPS', '=', $idSub],
  2183. ])->first();
  2184. $taxRegime = DB::table('S002V01TREFI')->where([
  2185. ['REFI_NULI', '=', $line],
  2186. ['REFI_CRFI', '=', $subcontratists_info->TAX_REFERENCE],
  2187. ])->first();
  2188. $subcontratists_info->TAX_REFERENCE = $taxRegime->REFI_DRFI . " (" . $subcontratists_info->TAX_REFERENCE . ")";
  2189. $country = DB::table('S002V01TPAIS')->where([
  2190. ['PAIS_NULI', '=', $line],
  2191. ['PAIS_IDPA', '=', $subcontratists_info->COUNTRY],
  2192. ])->first();
  2193. $state = DB::table('S002V01TESTA')->where([
  2194. ['ESTA_NULI', '=', $line],
  2195. ['ESTA_COES', '=', $subcontratists_info->FEDERAL_ENTITY],
  2196. ['ESTA_COPA', '=', $subcontratists_info->COUNTRY],
  2197. ])->first();
  2198. $city = DB::table('S002V01TMUNI')->where([
  2199. ['MUNI_NULI', '=', $line],
  2200. ['MUNI_COMU', '=', $subcontratists_info->CITY],
  2201. ['MUNI_COES', '=', $subcontratists_info->FEDERAL_ENTITY],
  2202. ])->first();
  2203. $town = DB::table('S002V01TLOCA')->where([
  2204. ['LOCA_NULI', '=', $line],
  2205. ['LOCA_COLO', '=', $subcontratists_info->TOWN],
  2206. ['LOCA_COES', '=', $subcontratists_info->FEDERAL_ENTITY],
  2207. ])->first();
  2208. $setting = DB::table('S002V01TCOLO')->where([
  2209. ['COLO_NULI', '=', $line],
  2210. ['COLO_COCO', '=', $subcontratists_info->SUBURB],
  2211. ['COLO_COPO', '=', $subcontratists_info->POSTAL_CODE],
  2212. ])->first();
  2213. if(!is_null($country)){
  2214. $subcontratists_info->COUNTRY = trim($country->PAIS_NOMB) . " (" . $subcontratists_info->COUNTRY . ")";
  2215. }
  2216. if(!is_null($state)){
  2217. $subcontratists_info->FEDERAL_ENTITY = trim($state->ESTA_NOES) . " (" . $subcontratists_info->FEDERAL_ENTITY . ")";
  2218. }
  2219. if(!is_null($city)){
  2220. $subcontratists_info->CITY = trim($city->MUNI_NOMU) . " (" . $subcontratists_info->CITY . ")";
  2221. }
  2222. if(!is_null($town)){
  2223. $subcontratists_info->TOWN = trim($town->LOCA_NOLO) . " (" . $subcontratists_info->TOWN . ")";
  2224. }
  2225. if(!is_null($setting)){
  2226. $subcontratists_info->SUBURB = trim($setting->COLO_NOCO) . " (" . $subcontratists_info->SUBURB . ")";
  2227. }
  2228. $specialtiesArr = json_decode($subcontratists_info->SPECIALTY, true);
  2229. foreach($specialtiesArr as $key=>$specialtyCode){
  2230. $specialty = DB::table('S002V01TGEES')->where([
  2231. ['GEES_NULI', '=', $line],
  2232. ['GEES_COES', '=', $specialtyCode]
  2233. ])->first();
  2234. $specialty = $specialtyCode . " - " . $specialty->GEES_NOES;
  2235. $specialtyCode = $this->encryptionController->encrypt($specialty);
  2236. $specialtiesArr[$key] = $specialtyCode;
  2237. }
  2238. $subcontratists_info->SPECIALTY = json_encode($specialtiesArr);
  2239. $now = $this->functionsController->now();
  2240. $nowStr = $now->toDateTimeString();
  2241. $actions = DB::getQueryLog();
  2242. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2243. $idac = $this->functionsController->registerActivity(
  2244. $line,
  2245. 'S002V01M11GPRS',
  2246. 'S002V01F01GESU',
  2247. 'S002V01P03DESU',
  2248. 'Consulta',
  2249. "El usuario $name (" . $usr->USUA_IDUS . ") consultó al subcontratista " . $subcontratists_info->SOCIAL_REASON . " ($idSub).",
  2250. $idUser,
  2251. $nowStr,
  2252. 'S002V01S01GESU'
  2253. );
  2254. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2255. return $this->responseController->makeResponse(false, 'EXITO', $subcontratists_info);
  2256. }
  2257. public function updateSubcontratist(Request $request) {
  2258. DB::enableQueryLog();
  2259. $request['TELEPHONE1'] = $this->encryptionController->decrypt($request->TELEPHONE1) ? $this->encryptionController->decrypt($request->TELEPHONE1) : 'ENC_ERR';
  2260. $request['TELEPHONE2'] = $this->encryptionController->decrypt($request->TELEPHONE2) ? $this->encryptionController->decrypt($request->TELEPHONE2) : 'ENC_ERR';
  2261. $request['EMAIL'] = $this->encryptionController->decrypt($request->EMAIL) ? $this->encryptionController->decrypt($request->EMAIL) : 'ENC_ERR';
  2262. if (!is_null($request->RFC)) {
  2263. $request['RFC'] = $this->encryptionController->decrypt($request->RFC) ? $this->encryptionController->decrypt($request->RFC) : 'ENC_ERR';
  2264. } else {
  2265. $request['RFC'] = '';
  2266. }
  2267. if (!is_null($request->TAX)) {
  2268. $request['TAX'] = $this->encryptionController->decrypt($request->TAX) ? $this->encryptionController->decrypt($request->TAX) : 'ENC_ERR';
  2269. } else {
  2270. $request['TAX'] = '';
  2271. }
  2272. $validator = Validator::make($request->all(), [
  2273. 'id_user' => 'required|string',
  2274. 'linea' => 'required|integer',
  2275. 'id_subcontratist' => 'required|string',
  2276. 'SOCIAL_REASON' => 'required|string|max:150',
  2277. 'TAX_REFERENCE' => 'required|string|max:15',
  2278. 'CONTRACT_TYPE' => 'required|string|in:Persona moral,Persona física',
  2279. 'FOREIGNER' => 'required|string|in:Si,No',
  2280. 'RFC' => 'required_if:FOREIGNER,=,No|string|max:13',
  2281. 'TAX' => 'required_if:FOREIGNER,=,Si|string|max:13',
  2282. 'EMAIL' => 'required|string|max:150',
  2283. 'COUNTRY' => 'required|string|max:75',
  2284. 'FEDERAL_ENTITY' => 'required|string|max:75',
  2285. 'CITY' => 'string|max:75',
  2286. 'TOWN' => 'string|max:75',
  2287. 'SUBURB' => 'required|string|max:75',
  2288. 'POSTAL_CODE' => 'required|string|max:5',
  2289. 'STREET' => 'required|string|max:150',
  2290. 'EXTERIOR_NUMBER' => 'required|string',
  2291. // 'INTERIOR_NUMBER' => 'string',
  2292. 'LADA1' => 'required|string|max:15',
  2293. 'TELEPHONE1' => 'required|string|min:7|max:11',
  2294. 'LADA2' => 'string|max:15',
  2295. 'TELEPHONE2' => 'string|min:7|max:11',
  2296. 'SPECIALTY' => 'required|json'
  2297. ]);
  2298. if($validator->fails()){
  2299. return $this->responseController->makeResponse(
  2300. true,
  2301. "Se encontraron uno o más errores.",
  2302. $this->responseController->makeErrors(
  2303. $validator->errors()->messages()
  2304. ),
  2305. 401
  2306. );
  2307. }
  2308. $form = $request->all();
  2309. foreach($form as $k=>$v){
  2310. if($k == 'INTERIOR_NUMBER' && $v == '0'){
  2311. unset($form[$k]);
  2312. }else if($v == '-'){
  2313. unset($form[$k]);
  2314. }
  2315. }
  2316. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2317. if(!$idUser){
  2318. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2319. }
  2320. $usr = DB::table('S002V01TUSUA')->where([
  2321. ['USUA_NULI', '=', $form['linea']],
  2322. ['USUA_IDUS', '=', $idUser]
  2323. ])->first();
  2324. if(is_null($usr)){
  2325. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  2326. }
  2327. $idSub = $this->encryptionController->decrypt($form['id_subcontratist']);
  2328. if(!$idSub){
  2329. return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
  2330. }
  2331. $sub = DB::table('S002V01TPESU')->where([
  2332. ['PESU_NULI', '=', $form['linea']],
  2333. ['PESU_IDPS', '=', $idSub],
  2334. ])->first();
  2335. if(is_null($sub)){
  2336. return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
  2337. }
  2338. $ladasValues = [];
  2339. $ladas = DB::table('S002V01TPAIS')->select([
  2340. 'PAIS_LADA AS LADA'
  2341. ])->where('PAIS_NULI', '=', $form['linea'])->get()->all();
  2342. foreach($ladas as $lada){
  2343. if($lada->LADA != '' && $lada->LADA != '0'){
  2344. $ladasValues[] = $lada->LADA;
  2345. }
  2346. }
  2347. if(!in_array($form['LADA1'], $ladasValues)){
  2348. return $this->responseController->makeResponse(true, "La lada $form[LADA1] no está relacionada a ningún país.", [], 400);
  2349. }else if($form['TELEPHONE1'] == 'ENC_ERR'){
  2350. return $this->responseController->makeResponse(true, 'El número telefónico 1 no fue encriptado correctamente.', [], 400);
  2351. }
  2352. $lada2 = null;
  2353. $phone2 = null;
  2354. if(isset($form['LADA2'])){
  2355. if(!in_array($form['LADA2'], $ladasValues)){
  2356. return $this->responseController->makeResponse(true, "La lada $form[LADA2] no está relacionada a ningún país.", [], 400);
  2357. }else if($form['TELEPHONE2'] == 'ENC_ERR'){
  2358. return $this->responseController->makeResponse(true, 'El número telefónico 2 no fue encriptado correctamente.', [], 400);
  2359. }
  2360. $lada2 = $form['LADA2'];
  2361. $phone2 = $form['TELEPHONE2'];
  2362. }
  2363. if($form['EMAIL'] == 'ENC_ERR'){
  2364. return $this->responseController->makeResponse(true, 'El email no fue encriptado correctamente.', [], 400);
  2365. }
  2366. $rfcx = null;
  2367. if(isset($form['RFC']) && $form['FOREIGNER'] == 'No' && $form['RFC'] == 'ENC_ERR'){
  2368. return $this->responseController->makeResponse(true, 'El RFC no fue encriptado correctamente.', [], 400);
  2369. }else if(isset($form['RFC']) && $form['RFC'] != 'ENC_ERR'){
  2370. $rfcx = $form['RFC'];
  2371. }
  2372. $taid = null;
  2373. if(isset($form['TAX']) && $form['FOREIGNER'] == 'Si' && $form['TAX'] == 'ENC_ERR'){
  2374. return $this->responseController->makeResponse(true, 'El TAX ID no fue encriptado correctamente.', [], 400);
  2375. }else if(isset($form['TAX']) && $form['TAX'] != 'ENC_ERR'){
  2376. $taid = $form['TAX'];
  2377. }
  2378. $country = DB::table('S002V01TPAIS')->where([
  2379. ['PAIS_NULI', '=', $form['linea']],
  2380. ['PAIS_IDPA', '=', $form['COUNTRY']],
  2381. ])->first();
  2382. if(is_null($country)){
  2383. return $this->responseController->makeResponse(true, 'El país seleccionado no existe.', [], 404);
  2384. }
  2385. $taxRegime = DB::table('S002V01TREFI')->where([
  2386. ['REFI_NULI', '=', $form['linea']],
  2387. ['REFI_CRFI', '=', $form['TAX_REFERENCE']],
  2388. ])->first();
  2389. if(is_null($taxRegime)){
  2390. return $this->responseController->makeResponse(true, 'El régimen fiscal seleccionado no existe.', [], 404);
  2391. }
  2392. $colo = null;
  2393. $ciud = null;
  2394. $loca = null;
  2395. if($form['COUNTRY'] == 'MEX' || $form['COUNTRY'] == 'USA' || $form['COUNTRY'] == 'CAN'){
  2396. $state = DB::table('S002V01TESTA')->where([
  2397. ['ESTA_NULI', '=', $form['linea']],
  2398. ['ESTA_COES', '=', $form['FEDERAL_ENTITY']],
  2399. ['ESTA_COPA', '=', $form['COUNTRY']],
  2400. ])->first();
  2401. if(is_null($state)){
  2402. return $this->responseController->makeResponse(true, 'El estado seleccionado no existe.', [], 404);
  2403. }
  2404. if($form['COUNTRY'] == 'MEX'){
  2405. if(isset($form['CITY'])){
  2406. $city = DB::table('S002V01TMUNI')->where([
  2407. ['MUNI_NULI', '=', $form['linea']],
  2408. ['MUNI_COMU', '=', $form['CITY']],
  2409. ['MUNI_COES', '=', $form['FEDERAL_ENTITY']],
  2410. ])->first();
  2411. if(is_null($city)){
  2412. return $this->responseController->makeResponse(true, 'El municipio seleccionado no existe.', [], 404);
  2413. }else{
  2414. $ciud = $form['CITY'];
  2415. }
  2416. }
  2417. if(isset($form['TOWN'])){
  2418. $town = DB::table('S002V01TLOCA')->where([
  2419. ['LOCA_NULI', '=', $form['linea']],
  2420. ['LOCA_COLO', '=', $form['TOWN']],
  2421. ['LOCA_COES', '=', $form['FEDERAL_ENTITY']],
  2422. ])->first();
  2423. if(is_null($town)){
  2424. return $this->responseController->makeResponse(true, 'La localidad seleccionada no existe.', [], 404);
  2425. }else{
  2426. $loca = $form['TOWN'];
  2427. }
  2428. }
  2429. $setting = DB::table('S002V01TCOLO')->where([
  2430. ['COLO_NULI', '=', $form['linea']],
  2431. ['COLO_COCO', '=', $form['SUBURB']],
  2432. ['COLO_COPO', '=', $form['POSTAL_CODE']],
  2433. ])->first();
  2434. if(is_null($setting)){
  2435. return $this->responseController->makeResponse(true, 'La colonia seleccionada no existe.', [], 404);
  2436. }else{
  2437. $colo = $form['SUBURB'];
  2438. }
  2439. $zipCode = DB::table('S002V01TCOPO')->where([
  2440. ['COPO_NULI', '=', $form['linea']],
  2441. ['COPO_COPO', '=', $form['POSTAL_CODE']],
  2442. ['COPO_COES', '=', $form['FEDERAL_ENTITY']],
  2443. ])->first();
  2444. if(is_null($zipCode)){
  2445. return $this->responseController->makeResponse(true, 'El código postal seleccionado no existe.', [], 404);
  2446. }
  2447. }else{
  2448. $colo = $form['SUBURB'];
  2449. $ciud = $form['CITY'];
  2450. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  2451. }
  2452. }else{
  2453. $colo = $form['SUBURB'];
  2454. $ciud = $form['CITY'];
  2455. $loca = isset($form['TOWN']) ? $form['TOWN'] : null;
  2456. }
  2457. /* $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
  2458. $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
  2459. ->orWhere('PESU_XRFC', '=', $form['RFC'])
  2460. ->orWhere('PESU_CORR', '=', $form['EMAIL']);
  2461. })->where([
  2462. ['PESU_IDPS', '!=', $idSub],
  2463. ['PESU_ESTA', '=', 'Activo'],
  2464. ])->get()->all();
  2465. if(count($subArr) > 0){
  2466. return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
  2467. } */
  2468. if (!is_null($form['RFC'])) {
  2469. $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
  2470. $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
  2471. ->orWhere('PESU_XRFC', '=', $form['RFC'])
  2472. ->orWhere('PESU_CORR', '=', $form['EMAIL']);
  2473. })->where([
  2474. ['PESU_IDPS', '!=', $idSub],
  2475. ['PESU_ESTA', '=', 'Activo'],
  2476. ])->get()->all();
  2477. if(count($subArr) > 0){
  2478. return $this->responseController->makeResponse(true, 'La razón social, el RFC o el correo electrónico ya fueron registrados.', [], 401);
  2479. }
  2480. }
  2481. if (!is_null($form['TAX'])) {
  2482. $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
  2483. $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
  2484. ->orWhere('PESU_XRFC', '=', $form['TAX'])
  2485. ->orWhere('PESU_CORR', '=', $form['EMAIL']);
  2486. })->where([
  2487. ['PESU_IDPS', '!=', $idSub],
  2488. ['PESU_ESTA', '=', 'Activo'],
  2489. ])->get()->all();
  2490. if(count($subArr) > 0){
  2491. return $this->responseController->makeResponse(true, 'La razón social, el Tax ID o el correo electrónico ya fueron registrados.', [], 401);
  2492. }
  2493. /* $subArr = DB::table('S002V01TPESU')->where('PESU_NULI', '=', $form['linea'])->where(function(Builder $query) use ($form) {
  2494. $query->where('PESU_RASO', '=', $form['SOCIAL_REASON'])
  2495. ->orWhere('PESU_TAID', '=', $form['TAX'])
  2496. ->orWhere('PESU_CORR', '=', $form['EMAIL']);
  2497. })->where('PESU_ESTA', '=', 'Activo')->get()->all();
  2498. if(count($subArr) > 0){
  2499. return $this->responseController->makeResponse(true, 'La razón social, el Tax ID o el correo electrónico ya fueron registrados. 2', [], 401);
  2500. } */
  2501. }
  2502. $specialtiesArr = json_decode($form['SPECIALTY'], true);
  2503. foreach($specialtiesArr as $key=>$specialtyCode){
  2504. $specialtyCode = $this->encryptionController->decrypt($specialtyCode);
  2505. if(!$specialtyCode){
  2506. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  2507. }
  2508. $specialtyObj = DB::table('S002V01TGEES')->where([
  2509. ['GEES_NULI', '=', $form['linea']],
  2510. ['GEES_COES', '=', $specialtyCode]
  2511. ])->first();
  2512. if(is_null($specialtyObj)){
  2513. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades no existe.", [], 404);
  2514. }else if($specialtyObj->GEES_ESTA == 'Eliminado'){
  2515. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades está eliminado.", [], 404);
  2516. }
  2517. $specialtiesArr[$key] = $specialtyCode;
  2518. }
  2519. $specialtiesStr = json_encode($specialtiesArr);
  2520. $nuin = isset($form['INTERIOR_NUMBER']) ? $form['INTERIOR_NUMBER'] : null;
  2521. $now = $this->functionsController->now();
  2522. $nowStr = $now->toDateTimeString();
  2523. DB::table('S002V01TPESU')->where([
  2524. ['PESU_NULI', '=', $form['linea']],
  2525. ['PESU_IDPS', '=', $idSub],
  2526. ])->update([
  2527. 'PESU_RASO' => $form['SOCIAL_REASON'],
  2528. 'PESU_REFI' => $form['TAX_REFERENCE'],
  2529. 'PESU_XRFC' => $rfcx,
  2530. 'PESU_TIPO' => $form['CONTRACT_TYPE'],
  2531. 'PESU_CORR' => $form['EMAIL'],
  2532. 'PESU_EXTR' => $form['FOREIGNER'],
  2533. 'PESU_TAID' => $taid,
  2534. 'PESU_CALL' => $form['STREET'],
  2535. 'PESU_NUEX' => $form['EXTERIOR_NUMBER'],
  2536. 'PESU_NUIN' => $nuin,
  2537. 'PESU_COLO' => $colo,
  2538. 'PESU_CIUD' => $ciud,
  2539. 'PESU_LOCA' => $loca,
  2540. 'PESU_COPO' => $form['POSTAL_CODE'],
  2541. 'PESU_ENFE' => $form['FEDERAL_ENTITY'],
  2542. 'PESU_IDPA' => $form['COUNTRY'],
  2543. 'PESU_TEL1' => $form['TELEPHONE1'],
  2544. 'PESU_LAT1' => $form['LADA1'],
  2545. 'PESU_TEL2' => $phone2,
  2546. 'PESU_LAT2' => $lada2,
  2547. 'PESU_ESPE' => $specialtiesStr,
  2548. 'PESU_USMO' => $idUser,
  2549. 'PESU_FEMO' => $nowStr,
  2550. ]);
  2551. $response = array('idSubcontract' => $idSub);
  2552. try {
  2553. $getProvider = (array) DB::table('S002V01TPROV')
  2554. ->where('PROV_IDPS', '=', $idSub)
  2555. ->where('PROV_NULI', '=', $form['linea'])
  2556. ->first();
  2557. } catch (\Throwable $th) {
  2558. DB::rollBack();
  2559. return $this->responseController->makeResponse(true, "Ocurrió un error al válidar si existe en proveedor.", $th->getMessage(), 500);
  2560. }
  2561. if ( !empty($getProvider) ) {
  2562. try {
  2563. $validateUpdateInformation = DB::table('S002V01TPROV')
  2564. ->where('PROV_NUPR', '=', $getProvider['PROV_NUPR'])
  2565. ->where('PROV_NULI', '=', $form['linea'])
  2566. ->update([
  2567. 'PROV_NOCO' => $form['SOCIAL_REASON'],
  2568. 'PROV_CORR' => $form['EMAIL'],
  2569. 'PROV_LAD1' => $form['LADA1'],
  2570. 'PROV_TEL1' => $form['TELEPHONE1'],
  2571. 'PROV_LAD2' => $lada2,
  2572. 'PROV_TEL2' => $phone2,
  2573. 'PROV_TICO' => $form['CONTRACT_TYPE'],
  2574. 'PROV_XRFC' => $rfcx,
  2575. 'PROV_XTAX' => $taid,
  2576. 'PROV_CRFI' => $form['TAX_REFERENCE'],
  2577. 'PROV_TIPO' => $form['FOREIGNER'] === 'No' ? 'Nacional' : 'Extranjero',
  2578. 'PROV_CALL' => $form['STREET'],
  2579. 'PROV_NUEX' => $form['EXTERIOR_NUMBER'],
  2580. 'PROV_NUIN' => $nuin,
  2581. 'PROV_COPO' => $form['POSTAL_CODE'],
  2582. 'PROV_COLO' => $colo,
  2583. 'PROV_LOCA' => $loca,
  2584. 'PROV_MUNI' => $ciud,
  2585. 'PROV_ENTI' => $form['FEDERAL_ENTITY'],
  2586. 'PROV_PAIS' => $form['COUNTRY'],
  2587. 'PROV_USMO' => $idUser,
  2588. 'PROV_FEMO' => $nowStr,
  2589. 'PROV_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  2590. ]);
  2591. } catch (\Throwable $th) {
  2592. DB::rollBack();
  2593. return $this->responseController->makeResponse(true, "Ocurrió un error al modificar al proveedor", $th->getMessage(), 500);
  2594. }
  2595. if (!$validateUpdateInformation) {
  2596. DB::rollBack();
  2597. return $this->responseController->makeResponse(true, "No se pudo modificar el proveedor.", [], 500);
  2598. }
  2599. $response['provider'] = $getProvider;
  2600. }
  2601. $actions = DB::getQueryLog();
  2602. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2603. $idac = $this->functionsController->registerActivity(
  2604. $form['linea'],
  2605. 'S002V01M11GPRS',
  2606. 'S002V01F01GESU',
  2607. 'S002V01P02RESU',
  2608. 'Actualización',
  2609. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó al subcontratista $idSub.",
  2610. $idUser,
  2611. $nowStr,
  2612. 'S002V01S01GESU'
  2613. );
  2614. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2615. return $this->responseController->makeResponse(false, 'EXITO', $response);
  2616. }
  2617. public function updateToInactiveStatusSubcontract(Request $request) {
  2618. DB::enableQueryLog();
  2619. $validator = Validator::make($request->all(), [
  2620. 'id_user' => 'required|string',
  2621. 'linea' => 'required|integer',
  2622. 'id_subcontratist' => 'required|string',
  2623. ]);
  2624. if($validator->fails()){
  2625. return $this->responseController->makeResponse(
  2626. true,
  2627. "Se encontraron uno o más errores.",
  2628. $this->responseController->makeErrors(
  2629. $validator->errors()->messages()
  2630. ),
  2631. 401
  2632. );
  2633. }
  2634. $form = $request->all();
  2635. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2636. if(!$idUser){
  2637. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2638. }
  2639. $usr = DB::table('S002V01TUSUA')->where([
  2640. ['USUA_NULI', '=', $form['linea']],
  2641. ['USUA_IDUS', '=', $idUser]
  2642. ])->first();
  2643. if(is_null($usr)){
  2644. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  2645. }
  2646. $idSub = $this->encryptionController->decrypt($form['id_subcontratist']);
  2647. if(!$idSub){
  2648. return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
  2649. }
  2650. $sub = DB::table('S002V01TPESU')->where([
  2651. ['PESU_NULI', '=', $form['linea']],
  2652. ['PESU_IDPS', '=', $idSub],
  2653. ])->first();
  2654. if(is_null($sub)){
  2655. return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
  2656. }
  2657. $users = DB::table('S002V01TPERS')->where([
  2658. ['PERS_NULI', '=', $form['linea']],
  2659. ['PERS_ESTA', '=', 'Activo'],
  2660. ])->join('S002V01TPESU', 'PERS_IDPS', '=', 'PESU_IDPS')->get()->all();
  2661. if(count($users) > 0){
  2662. return $this->responseController->makeResponse(true, 'El subcontratista que desea eliminar tiene usuarios relacionados.', [], 401);
  2663. }
  2664. $now = $this->functionsController->now();
  2665. $nowStr = $now->toDateTimeString();
  2666. DB::table('S002V01TPESU')->where([
  2667. ['PESU_NULI', '=', $form['linea']],
  2668. ['PESU_IDPS', '=', $idSub],
  2669. ])->update([
  2670. 'PESU_ESTA' => 'Eliminado',
  2671. 'PESU_USMO' => $idUser,
  2672. 'PESU_FEMO' => $nowStr
  2673. ]);
  2674. $actions = DB::getQueryLog();
  2675. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2676. $idac = $this->functionsController->registerActivity(
  2677. $form['linea'],
  2678. 'S002V01M11GPRS',
  2679. 'S002V01F01GESU',
  2680. 'S002V01P02RESU',
  2681. 'Eliminación',
  2682. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó al subcontratista $idSub.",
  2683. $idUser,
  2684. $nowStr,
  2685. 'S002V01S01GESU'
  2686. );
  2687. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2688. return $this->responseController->makeResponse(false, 'EXITO');
  2689. }
  2690. public function getContractsOfEverySubcontratist($idUser, $line) {
  2691. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($idUser, $line);
  2692. if ($arrResponseCheckUser['error']) {
  2693. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  2694. }
  2695. try {
  2696. $arrSubcontratists = DB::table('S002V01TPERS')
  2697. ->where([
  2698. ['PERS_NULI', '=', $line],
  2699. ['PERS_TICO', '=', 'Subcontratista'],
  2700. ])
  2701. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  2702. ->join('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  2703. ->get([
  2704. 'PERS_IDPE AS ID_EMPLEADO',
  2705. 'USUA_IDUS AS ID_USUARIO',
  2706. 'USUA_NOMB AS NOMBRE',
  2707. 'USUA_APPA AS APELLIDO_PATERNO',
  2708. 'USUA_APMA AS APELLIDO_MATERNO',
  2709. 'PESU_IDPS AS ID_SUBCONTRATISTA',
  2710. 'PESU_RASO AS RAZON_SOCIAL',
  2711. 'PESU_REFI AS REFERENCIA_FISCAL',
  2712. ]);
  2713. $arrSubcontratists = json_decode(json_encode($arrSubcontratists), true);
  2714. } catch (\Throwable $th) {
  2715. return $this->responseController->makeResponse(true, 'Ocurrió un error al recuperar los subcontratistas', $th->getMessage(), 404);
  2716. }
  2717. $contractsBySubcontratists = array();
  2718. foreach ($arrSubcontratists as $key => $subcontratist) {
  2719. try {
  2720. $countSubcontract = DB::table('S002V01TCONT')
  2721. ->where([
  2722. ['CONT_IDEM', '=', $subcontratist['ID_EMPLEADO']],
  2723. ['CONT_NULI', '=', $line],
  2724. ['CONT_ESTA', '=', 'Activo'],
  2725. ])
  2726. ->count();
  2727. } catch (\Throwable $th) {
  2728. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los contratos', $th->getMessage(), 404);
  2729. }
  2730. $employee = trim("{$subcontratist['NOMBRE']} {$subcontratist['APELLIDO_PATERNO']} {$subcontratist['APELLIDO_MATERNO']}");
  2731. $contractsBySubcontratists[] = [
  2732. 'ID_EMPLEADO' => $this->encryptionController->encrypt($subcontratist['ID_EMPLEADO']),
  2733. 'ID_USUARIO' => $this->encryptionController->encrypt($subcontratist['ID_USUARIO']),
  2734. 'ID_SUBCONTRATISTA' => $this->encryptionController->encrypt($subcontratist['ID_SUBCONTRATISTA']),
  2735. 'EMPLEADO' => "{$employee} ({$subcontratist['ID_EMPLEADO']}) <{$subcontratist['ID_USUARIO']}>",
  2736. 'RAZON_SOCIAL' => "{$subcontratist['RAZON_SOCIAL']} ({$subcontratist['ID_SUBCONTRATISTA']})",
  2737. 'NUMERO_CONTRATOS' => $countSubcontract === 1 ? "{$countSubcontract} contrato" : "{$countSubcontract} contratos",
  2738. ];
  2739. }
  2740. return $this->responseController->makeResponse(false, 'EXITO', $contractsBySubcontratists);
  2741. }
  2742. public function getContractsOfEverySubcontratistOld($idUser, $line) {
  2743. DB::enableQueryLog();
  2744. $idUser = $this->encryptionController->decrypt($idUser);
  2745. if(!$idUser){
  2746. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  2747. }
  2748. $usr = DB::table('S002V01TUSUA')->where([
  2749. ['USUA_NULI', '=', $line],
  2750. ['USUA_IDUS', '=', $idUser],
  2751. ])->first();
  2752. if(is_null($usr)){
  2753. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  2754. }
  2755. $contractsBySubcontratists = DB::table('S002V01TPERS')->select([
  2756. DB::raw("
  2757. TRIM(CONCAT(
  2758. USUA_NOMB,
  2759. ' ',
  2760. USUA_APPA,
  2761. IF(ISNULL(USUA_APMA), '', CONCAT(' ', USUA_APMA)),
  2762. ' <(',
  2763. PERS_IDPE,
  2764. ')> (',
  2765. PERS_IDUS,
  2766. ')'
  2767. )) AS EMPLOYEE
  2768. "),
  2769. DB::raw("COUNT(CONT_IDCO) AS CONTRACTS")
  2770. ])->leftJoin('S002V01TCONT', 'CONT_IDEM', '=', 'PERS_IDPE')
  2771. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  2772. ->groupBy('EMPLOYEE')->where([
  2773. ['PERS_NULI', '=', $line],
  2774. ['PERS_TICO', '=', 'Subcontratista'],
  2775. ])->get()->all();
  2776. foreach($contractsBySubcontratists as $key=>$val){
  2777. $employeeArr = explode('<', $val->EMPLOYEE);
  2778. $employeeName = $employeeArr[0];
  2779. $employeeArr = array_reverse($employeeArr);
  2780. $employeeArr = explode('>', $employeeArr[0]);
  2781. $employeeID = str_replace('(', '', $employeeArr[0]);
  2782. $employeeID = str_replace(')', '', $employeeID);
  2783. $subcontratist = DB::table('S002V01TPESU')->where([
  2784. ['PESU_NULI', '=', $line],
  2785. ['PESU_IDPS', '=', $employeeID],
  2786. ])->first();
  2787. if (is_null($subcontratist)) {
  2788. var_dump($employeeID);
  2789. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los datos del proveedor.', [], 404);
  2790. }
  2791. $val->ID_EMPLOYEE = $this->encryptionController->encrypt($employeeID);
  2792. $val->EMPLOYEE = $employeeName . join('', $employeeArr);
  2793. $val->ID_SUBCONTRATIST = $this->encryptionController->encrypt($employeeID);
  2794. $val->SUBCONTRATIST = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ")";
  2795. $contractsBySubcontratists[$key] = $val;
  2796. }
  2797. $now = $this->functionsController->now();
  2798. $nowStr = $now->toDateTimeString();
  2799. $actions = DB::getQueryLog();
  2800. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2801. $idac = $this->functionsController->registerActivity(
  2802. $line,
  2803. 'S002V01M11GPRS',
  2804. 'S002V01F02ADCO',
  2805. 'S002V01P01HCSU',
  2806. 'Consulta',
  2807. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos por subcontratista.",
  2808. $idUser,
  2809. $nowStr,
  2810. 'S002V01S01GESU'
  2811. );
  2812. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2813. return $this->responseController->makeResponse(false, 'EXITO', $contractsBySubcontratists);
  2814. }
  2815. public function getContractsBySubcontratist($idSubcontratist, $idUser, $line) {
  2816. DB::enableQueryLog();
  2817. $idUser = $this->encryptionController->decrypt($idUser);
  2818. if(!$idUser){
  2819. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2820. }
  2821. $usr = DB::table('S002V01TUSUA')->where([
  2822. ['USUA_NULI', '=', $line],
  2823. ['USUA_IDUS', '=', $idUser]
  2824. ])->first();
  2825. if(is_null($usr)){
  2826. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  2827. }
  2828. $idSubcontratist = $this->encryptionController->decrypt($idSubcontratist);
  2829. if(!$idSubcontratist){
  2830. return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
  2831. }
  2832. $sub = DB::table('S002V01TPERS')->where([
  2833. ['PERS_NULI', '=', $line],
  2834. ['PERS_IDPE', '=', $idSubcontratist],
  2835. ['PERS_TICO', '=', 'Subcontratista'],
  2836. ])->first();
  2837. if(is_null($sub)){
  2838. return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
  2839. }
  2840. $contracts = DB::table('S002V01TCONT')->select([
  2841. 'CONT_NOCO AS CONTRACT_NAME',
  2842. 'CONT_FEIN AS START_DATE',
  2843. 'CONT_FEFI AS END_DATE',
  2844. 'CONT_COST AS COST',
  2845. ])->where([
  2846. ['CONT_NULI', '=', $line],
  2847. ['CONT_IDEM', '=', $idSubcontratist],
  2848. ['CONT_TIPO', '=', 'Subcontratista'],
  2849. ])->get()->all();
  2850. $now = $this->functionsController->now();
  2851. $nowStr = $now->toDateTimeString();
  2852. $actions = DB::getQueryLog();
  2853. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2854. $idac = $this->functionsController->registerActivity(
  2855. $line,
  2856. 'S002V01M11GPRS',
  2857. 'S002V01F02ADCO',
  2858. 'S002V01P01HCSU',
  2859. 'Consulta',
  2860. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos del subcontratista #$idSubcontratist.",
  2861. $idUser,
  2862. $nowStr,
  2863. 'S002V01S01GESU'
  2864. );
  2865. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2866. return $this->responseController->makeResponse(false, 'EXITO', $contracts);
  2867. }
  2868. public function downloadSubcontractInfoOnExcel($idSubcontratist, $idUser, $line){
  2869. DB::enableQueryLog();
  2870. $idUser = $this->encryptionController->decrypt($idUser);
  2871. if(!$idUser){
  2872. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2873. }
  2874. $usr = DB::table('S002V01TUSUA')->where([
  2875. ['USUA_NULI', '=', $line],
  2876. ['USUA_IDUS', '=', $idUser]
  2877. ])->first();
  2878. if(is_null($usr)){
  2879. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  2880. }
  2881. $idSubcontratist = $this->encryptionController->decrypt($idSubcontratist);
  2882. if(!$idSubcontratist){
  2883. return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
  2884. }
  2885. $sub = DB::table('S002V01TPERS')->where([
  2886. ['PERS_NULI', '=', $line],
  2887. ['PERS_IDPE', '=', $idSubcontratist],
  2888. ['PERS_TICO', '=', 'Subcontratista'],
  2889. ])->first();
  2890. if(is_null($sub)){
  2891. return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
  2892. }
  2893. $contracts = DB::table('S002V01TCONT')->select([
  2894. 'CONT_IDCO AS IDCONTRATO',
  2895. 'CONT_NOCO AS NOMBRECONTRATO',
  2896. 'CONT_IDOT AS IDORDEN',
  2897. 'CONT_TOTR AS TIPOORDEN',
  2898. 'PERS_ESPE AS ESPECIALIDAD',
  2899. 'CONT_FEIN AS FECHAINICIO',
  2900. 'CONT_FEFI AS FECHAFIN',
  2901. 'CONT_COST AS COSTO',
  2902. ])->join('S002V01TPERS', 'PERS_IDPE', '=', 'CONT_IDEM')->where([
  2903. ['CONT_NULI', '=', $line],
  2904. ['CONT_IDEM', '=', $idSubcontratist],
  2905. ['CONT_TIPO', '=', 'Subcontratista'],
  2906. ])->get()->all();
  2907. $document = $this->generateDocument($contracts, $line);
  2908. $now = $this->functionsController->now();
  2909. $nowStr = $now->toDateTimeString();
  2910. $dateTimeArr = explode(" ", $nowStr);
  2911. $dateArr = explode("-", $dateTimeArr[0]);
  2912. $year = substr($dateArr[0], 2);
  2913. $como = 'GPRS';
  2914. $cldo = 'IN';
  2915. $fecr = $year . $dateArr[1] . $dateArr[2];
  2916. $sec = DB::table('S002V01TAFAL')->where([
  2917. ['AFAL_NULI', '=', $line],
  2918. ['AFAL_COMO', '=', $como],
  2919. ['AFAL_CLDO', '=', $cldo],
  2920. ])->orderBy('AFAL_NUSE', 'desc')->first();
  2921. $nuse = "";
  2922. if(is_null($sec)){
  2923. $nuse = '000001';
  2924. }else{
  2925. $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
  2926. $nuse = "";
  2927. for($i = strlen($secu); $i < 6; $i++){
  2928. $nuse .= "0";
  2929. }
  2930. $nuse = $nuse . $secu;
  2931. }
  2932. $noar = "ficha_de_subcontratacion_del_subcontratista_$idSubcontratist";
  2933. $exte = "xlsx";
  2934. $ver = DB::table('S002V01TAFAL')->where([
  2935. ['AFAL_NULI', '=', $line],
  2936. ['AFAL_COMO', '=', $como],
  2937. ['AFAL_CLDO', '=', $cldo],
  2938. ['AFAL_NOAR', '=', $noar],
  2939. ['AFAL_EXTE', '=', $exte],
  2940. ])->orderBy('AFAL_NUVE', 'desc')->first();
  2941. $nuve = "";
  2942. if(is_null($ver)){
  2943. $nuve = "01";
  2944. }else{
  2945. $vers = intval($ver->AFAL_NUVE) + 1;
  2946. $nuve = $vers < 10 ? "0$vers" : "$vers";
  2947. }
  2948. $line = $line < 10 ? "0$line" : "$line";
  2949. $filePath = $this->resourcesController->pathService.'\\public_files\\';
  2950. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  2951. $tempFile = $filePath . $fileName;
  2952. if(file_exists($tempFile)){
  2953. unlink($tempFile);
  2954. }
  2955. $writer = IOFactory::createWriter($document, 'Xlsx');
  2956. $writer->save($tempFile);
  2957. $ubic = Storage::putFile('files', new File($tempFile));
  2958. $ubic = str_replace("/", "\\", $ubic);
  2959. $ubic = $this->resourcesController->pathService."\storage\app\\" . $ubic;
  2960. $tama = filesize($ubic);
  2961. $usac = json_encode([$idUser]);
  2962. unlink($tempFile);
  2963. DB::table('S002V01TAFAL')->insert([
  2964. 'AFAL_NULI' => $line,
  2965. 'AFAL_COMO' => $como,
  2966. 'AFAL_CLDO' => $cldo,
  2967. 'AFAL_FECR' => $fecr,
  2968. 'AFAL_NUSE' => $nuse,
  2969. 'AFAL_NUVE' => $nuve,
  2970. 'AFAL_NOAR' => $noar,
  2971. 'AFAL_EXTE' => $exte,
  2972. 'AFAL_TAMA' => $tama,
  2973. 'AFAL_UBIC' => $ubic,
  2974. 'AFAL_USAC' => $usac,
  2975. 'AFAL_USRE' => $idUser,
  2976. 'AFAL_FERE' => $nowStr,
  2977. ]);
  2978. $actions = DB::getQueryLog();
  2979. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2980. $idac = $this->functionsController->registerActivity(
  2981. $line,
  2982. 'S002V01M11GPRS',
  2983. 'S002V01F02ADCO',
  2984. 'S002V01P02FISU',
  2985. 'Registro',
  2986. "El usuario $name (" . $usr->USUA_IDUS . ") generó la ficha de subcontratación del subcontratista #$idSubcontratist para Excel.",
  2987. $idUser,
  2988. $nowStr,
  2989. 'S002V01S01GESU'
  2990. );
  2991. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2992. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  2993. }
  2994. public function downloadSubcontractInfoOnPdf($idSubcontratist, $idUser, $line) {
  2995. DB::enableQueryLog();
  2996. $idUser = $this->encryptionController->decrypt($idUser);
  2997. if(!$idUser){
  2998. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2999. }
  3000. $usr = DB::table('S002V01TUSUA')->where([
  3001. ['USUA_NULI', '=', $line],
  3002. ['USUA_IDUS', '=', $idUser]
  3003. ])->first();
  3004. if(is_null($usr)){
  3005. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  3006. }
  3007. $idSubcontratist = $this->encryptionController->decrypt($idSubcontratist);
  3008. if(!$idSubcontratist){
  3009. return $this->responseController->makeResponse(true, 'El ID del subcontratista no fue encriptado correctamente.', [], 400);
  3010. }
  3011. $sub = DB::table('S002V01TPERS')->where([
  3012. ['PERS_NULI', '=', $line],
  3013. ['PERS_IDPE', '=', $idSubcontratist],
  3014. ['PERS_TICO', '=', 'Subcontratista'],
  3015. ])->first();
  3016. if(is_null($sub)){
  3017. return $this->responseController->makeResponse(true, 'El subcontratista solicitado no existe.', [], 404);
  3018. }
  3019. $contracts = DB::table('S002V01TCONT')->select([
  3020. 'CONT_IDCO AS IDCONTRATO',
  3021. 'CONT_NOCO AS NOMBRECONTRATO',
  3022. 'CONT_IDOT AS IDORDEN',
  3023. 'CONT_TOTR AS TIPOORDEN',
  3024. 'PERS_ESPE AS ESPECIALIDAD',
  3025. 'CONT_FEIN AS FECHAINICIO',
  3026. 'CONT_FEFI AS FECHAFIN',
  3027. 'CONT_COST AS COSTO',
  3028. ])->join('S002V01TPERS', 'PERS_IDPE', '=', 'CONT_IDEM')->where([
  3029. ['CONT_NULI', '=', $line],
  3030. ['CONT_IDEM', '=', $idSubcontratist],
  3031. ['CONT_TIPO', '=', 'Subcontratista'],
  3032. ])->get()->all();
  3033. $document = $this->generateDocument($contracts, $line);
  3034. $now = $this->functionsController->now();
  3035. $nowStr = $now->toDateTimeString();
  3036. $dateTimeArr = explode(" ", $nowStr);
  3037. $dateArr = explode("-", $dateTimeArr[0]);
  3038. $year = substr($dateArr[0], 2);
  3039. $como = 'GPRS';
  3040. $cldo = 'IN';
  3041. $fecr = $year . $dateArr[1] . $dateArr[2];
  3042. $sec = DB::table('S002V01TAFAL')->where([
  3043. ['AFAL_NULI', '=', $line],
  3044. ['AFAL_COMO', '=', $como],
  3045. ['AFAL_CLDO', '=', $cldo],
  3046. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3047. $nuse = "";
  3048. if(is_null($sec)){
  3049. $nuse = '000001';
  3050. }else{
  3051. $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
  3052. $nuse = "";
  3053. for($i = strlen($secu); $i < 6; $i++){
  3054. $nuse .= "0";
  3055. }
  3056. $nuse = $nuse . $secu;
  3057. }
  3058. $noar = "ficha_de_subcontratacion_del_subcontratista_$idSubcontratist";
  3059. $exte = "pdf";
  3060. $ver = DB::table('S002V01TAFAL')->where([
  3061. ['AFAL_NULI', '=', $line],
  3062. ['AFAL_COMO', '=', $como],
  3063. ['AFAL_CLDO', '=', $cldo],
  3064. ['AFAL_NOAR', '=', $noar],
  3065. ['AFAL_EXTE', '=', $exte],
  3066. ])->orderBy('AFAL_NUVE', 'desc')->first();
  3067. $nuve = "";
  3068. if(is_null($ver)){
  3069. $nuve = "01";
  3070. }else{
  3071. $vers = intval($ver->AFAL_NUVE) + 1;
  3072. $nuve = $vers < 10 ? "0$vers" : "$vers";
  3073. }
  3074. $line = $line < 10 ? "0$line" : "$line";
  3075. $filePath = $this->resourcesController->pathService.'\\public_files\\';
  3076. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  3077. $tempFile = $filePath . $fileName;
  3078. if(file_exists($tempFile)){
  3079. unlink($tempFile);
  3080. }
  3081. $writer = IOFactory::createWriter($document, 'Mpdf');
  3082. $writer->save($tempFile);
  3083. $ubic = Storage::putFile('files', new File($tempFile));
  3084. $ubic = str_replace("/", "\\", $ubic);
  3085. $ubic = $this->resourcesController->pathService."\storage\app\\" . $ubic;
  3086. $tama = filesize($ubic);
  3087. $usac = json_encode([$idUser]);
  3088. unlink($tempFile);
  3089. DB::table('S002V01TAFAL')->insert([
  3090. 'AFAL_NULI' => $line,
  3091. 'AFAL_COMO' => $como,
  3092. 'AFAL_CLDO' => $cldo,
  3093. 'AFAL_FECR' => $fecr,
  3094. 'AFAL_NUSE' => $nuse,
  3095. 'AFAL_NUVE' => $nuve,
  3096. 'AFAL_NOAR' => $noar,
  3097. 'AFAL_EXTE' => $exte,
  3098. 'AFAL_TAMA' => $tama,
  3099. 'AFAL_UBIC' => $ubic,
  3100. 'AFAL_USAC' => $usac,
  3101. 'AFAL_USRE' => $idUser,
  3102. 'AFAL_FERE' => $nowStr,
  3103. ]);
  3104. $actions = DB::getQueryLog();
  3105. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3106. $idac = $this->functionsController->registerActivity(
  3107. $line,
  3108. 'S002V01M11GPRS',
  3109. 'S002V01F02ADCO',
  3110. 'S002V01P02FISU',
  3111. 'Registro',
  3112. "El usuario $name (" . $usr->USUA_IDUS . ") generó la ficha de subcontratación del subcontratista #$idSubcontratist para Excel.",
  3113. $idUser,
  3114. $nowStr,
  3115. 'S002V01S01GESU'
  3116. );
  3117. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3118. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  3119. }
  3120. private function generateDocument($contracts, $line) : Spreadsheet {
  3121. $spreadsheet = new Spreadsheet;
  3122. $spreadsheet->getProperties()
  3123. ->setCreator('STC')
  3124. ->setTitle('Historial de contratos por subcontratista.')
  3125. ->setSubject('Historial documento')
  3126. ->setKeywords('Subcontratista Contratos Historial')
  3127. ->setCategory('Historial archivo');
  3128. $worksheet = $spreadsheet->getActiveSheet();
  3129. $worksheet->setTitle('HISTORIAL DE CONTRATOS');
  3130. $columns = ['# DE CONTRATO', 'NOMBRE DEL CONTRATO', 'ORDEN DE TRABAJO', 'TIPO DE ORDEN', 'ESPECIALIDAD', 'FECHA DE INICIO', 'FECHA DE TÉRMINO', 'COSTO'];
  3131. $startRow = 2;
  3132. $startCol = 2;
  3133. $maxRow = $startRow + count($contracts) + 1;
  3134. $maxCol = $startCol + 7;
  3135. for($row = $startRow; $row <= $maxRow; $row++){
  3136. $startColStr = Coordinate::stringFromColumnIndex($startCol);
  3137. $maxColStr = Coordinate::stringFromColumnIndex($maxCol);
  3138. if($row == 2){
  3139. $worksheet->mergeCells($startColStr . $row . ':' . $maxColStr . $row);
  3140. $worksheet->setCellValue($startColStr . $row, 'FICHA DE SUBCONTRATACIÓN')->getStyle($startColStr . $row)->getFill()
  3141. ->setFillType(Fill::FILL_SOLID)
  3142. ->getStartColor()->setRGB('B7BCC4');
  3143. $worksheet->getStyle($startColStr . $row)->getFont()->setBold(true);
  3144. $worksheet->getStyle($startColStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3145. }else if($row == 3){
  3146. for($col = $startCol; $col <= $maxCol; $col++){
  3147. $colStr = Coordinate::stringFromColumnIndex($col);
  3148. $colInd = $col - 2;
  3149. $column = $columns[$colInd];
  3150. $worksheet->setCellValue($colStr . $row, $column);
  3151. $worksheet->getColumnDimension($colStr)->setAutoSize(true);
  3152. $worksheet->getStyle($colStr . $row)->getFont()->setBold(true);
  3153. $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3154. }
  3155. }else if($row > 3){
  3156. $rowInd = $row - 4;
  3157. $contract = (array) $contracts[$rowInd];
  3158. $keys = array_keys($contract);
  3159. for($col = $startCol; $col <= $maxCol; $col++){
  3160. $colInd = $col - 2;
  3161. $key = $keys[$colInd];
  3162. $value = $contract[$key];
  3163. $colStr = Coordinate::stringFromColumnIndex($col);
  3164. if($key == 'IDORDEN'){
  3165. $value = "Orden #$value";
  3166. }else if($key == 'FECHAINICIO' || $key == 'FECHAFIN'){
  3167. $value = $this->functionsController->formatDateTime($value);
  3168. }else if($key == 'COSTO'){
  3169. $worksheet->getStyle($colStr . $row)->getNumberFormat()->setFormatCode(NumberFormat::FORMAT_CURRENCY_USD);
  3170. }else if($key == 'ESPECIALIDAD'){
  3171. $specialtiesArr = json_decode($value, true);
  3172. $valueStr = "";
  3173. foreach($specialtiesArr as $val0){
  3174. $specialty = DB::table('S002V01TGEES')->where([
  3175. ['GEES_NULI', '=', $line],
  3176. ['GEES_COES', '=', $val0]
  3177. ])->first();
  3178. $valueStr .= $val0 . " - " . $specialty->GEES_NOES . ", ";
  3179. }
  3180. $value = substr($valueStr, 0, -2);
  3181. }
  3182. $worksheet->setCellValue($colStr . $row, $value);
  3183. }
  3184. }
  3185. }
  3186. if(count($contracts) == 0){
  3187. $startColStr = Coordinate::stringFromColumnIndex($startCol);
  3188. $maxColStr = Coordinate::stringFromColumnIndex($maxCol);
  3189. $maxRow++;
  3190. $worksheet->mergeCells($startColStr . $maxRow . ':' . $maxColStr . $maxRow);
  3191. $worksheet->setCellValue($startColStr . $maxRow, 'Aún no se han asociado contratos al subcontratista.');
  3192. $worksheet->getStyle($startColStr . $maxRow)->getFont()->setBold(true);
  3193. $worksheet->getStyle($startColStr . $maxRow)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  3194. }
  3195. $worksheet->getStyle($startColStr . $startRow . ':' . $maxColStr . $maxRow)
  3196. ->getBorders()
  3197. ->getAllBorders()
  3198. ->setBorderStyle(Border::BORDER_MEDIUM);
  3199. return $spreadsheet;
  3200. }
  3201. public function storeWorkteam(Request $request) {
  3202. DB::enableQueryLog();
  3203. $validator = Validator::make($request->all(), [
  3204. 'id_user' => 'required|string',
  3205. 'linea' => 'required|integer',
  3206. 'NAME' => 'required|string|max:75',
  3207. 'SPECIALITY' => 'required|json',
  3208. ]);
  3209. if($validator->fails()){
  3210. return $this->responseController->makeResponse(
  3211. TRUE,
  3212. 'ERR_PERSONAL_REG001: Uno o más errores encontrados',
  3213. $this->responseController->makeErrors($validator->errors()->messages()),
  3214. 400
  3215. );
  3216. }
  3217. $form = $request->all();
  3218. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3219. if(!$idUser){
  3220. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3221. }
  3222. $usr = DB::table('S002V01TUSUA')->where([
  3223. ['USUA_NULI', '=', $form['linea']],
  3224. ['USUA_IDUS', '=', $idUser],
  3225. ])->first();
  3226. if(is_null($usr)){
  3227. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3228. }
  3229. $specialtiesArr = json_decode($form['SPECIALITY'], true);
  3230. foreach($specialtiesArr as $key=>$specialty){
  3231. $specialtyCode = $this->encryptionController->decrypt($specialty);
  3232. if(!$specialtyCode){
  3233. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  3234. }
  3235. $specialtyObj = DB::table('S002V01TGEES')->where([
  3236. ['GEES_NULI', '=', $form['linea']],
  3237. ['GEES_COES', '=', $specialtyCode]
  3238. ])->first();
  3239. if(is_null($specialtyObj)){
  3240. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades no existe.", [], 404);
  3241. }else if($specialtyObj->GEES_ESTA == 'Eliminado'){
  3242. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades está eliminado.", [], 404);
  3243. }
  3244. $specialtiesArr[$key] = $specialtyCode;
  3245. }
  3246. $specialtiesStr = json_encode($specialtiesArr);
  3247. $team = DB::table('S002V01TEQMA')->where([
  3248. ['EQMA_NOMB', '=', $form['NAME']],
  3249. ['EQMA_NULI', '=', $form['linea']],
  3250. ['EQMA_ESTA', '=', 'Activo'],
  3251. ])->get()->all();
  3252. if(count($team) > 0){
  3253. return $this->responseController->makeResponse(true, "El nombre $form[NAME] ya fue tomado", [], 401);
  3254. }
  3255. $now = $this->functionsController->now();
  3256. $nowStr = $now->toDateTimeString();
  3257. DB::table('S002V01TEQMA')->insert([
  3258. "EQMA_NULI" => $form['linea'],
  3259. "EQMA_NOMB" => $form['NAME'],
  3260. "EQMA_ESPE" => $specialtiesStr,
  3261. "EQMA_USRE" => $idUser,
  3262. "EQMA_FERE" => $nowStr,
  3263. ]);
  3264. $actions = DB::getQueryLog();
  3265. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3266. $idac = $this->functionsController->registerActivity(
  3267. $form['linea'],
  3268. 'S002V01M11GPRS',
  3269. 'S002V01F01AETR',
  3270. 'S002V01P02REET',
  3271. 'Registro',
  3272. "El usuario $name (" . $usr->USUA_IDUS . ") registró el equipo de trabajo $form[NAME].",
  3273. $idUser,
  3274. $nowStr,
  3275. 'S002V01S04GETR'
  3276. );
  3277. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3278. return $this->responseController->makeResponse(false, 'EXITO.');
  3279. }
  3280. public function getConsultOfWorkteams($idUser, $line) {
  3281. DB::enableQueryLog();
  3282. $idUser = $this->encryptionController->decrypt($idUser);
  3283. if(!$idUser){
  3284. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3285. }
  3286. $usr = DB::table('S002V01TUSUA')->where([
  3287. ['USUA_NULI', '=', $line],
  3288. ['USUA_IDUS', '=', $idUser],
  3289. ])->first();
  3290. if(is_null($usr)){
  3291. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3292. }
  3293. $workteams = DB::table('S002V01TEQMA')->select([
  3294. 'EQMA_IDEQ as WORKTEAM_ID',
  3295. 'EQMA_NOMB as NAME',
  3296. 'EQMA_ESPE as SPECIALITY',
  3297. 'EQMA_ESTA as STATUS'
  3298. ])->where('EQMA_NULI', '=', $line)->get()->all();
  3299. foreach($workteams as $workteam){
  3300. $workteam->WORKTEAM_ID = $this->encryptionController->encrypt($workteam->WORKTEAM_ID);
  3301. $specialtiesArr = json_decode($workteam->SPECIALITY, true);
  3302. foreach($specialtiesArr as $key=>$specialtyCode){
  3303. $specialty = DB::table('S002V01TGEES')->where([
  3304. ['GEES_NULI', '=', $line],
  3305. ['GEES_COES', '=', $specialtyCode],
  3306. ])->first();
  3307. $specialtyName = $specialtyCode . " - " . $specialty->GEES_NOES;
  3308. $specialtyCode = $this->encryptionController->encrypt($specialtyName);
  3309. $specialtiesArr[$key] = $specialtyCode;
  3310. }
  3311. $workteam->SPECIALITY = json_encode($specialtiesArr);
  3312. }
  3313. $now = $this->functionsController->now();
  3314. $nowStr = $now->toDateTimeString();
  3315. $actions = DB::getQueryLog();
  3316. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3317. $idac = $this->functionsController->registerActivity(
  3318. $line,
  3319. 'S002V01M11GPRS',
  3320. 'S002V01F01AETR',
  3321. 'S002V01P01CETR',
  3322. 'Consulta',
  3323. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipos de trabajo registrados.",
  3324. $idUser,
  3325. $nowStr,
  3326. 'S002V01S04GETR'
  3327. );
  3328. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3329. return $this->responseController->makeResponse(false, 'EXITO.', $workteams);
  3330. }
  3331. public function getWorkteamById($workteam, $idUser, $line) {
  3332. DB::enableQueryLog();
  3333. $idUser = $this->encryptionController->decrypt($idUser);
  3334. if(!$idUser){
  3335. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3336. }
  3337. $usr = DB::table('S002V01TUSUA')->where([
  3338. ['USUA_NULI', '=', $line],
  3339. ['USUA_IDUS', '=', $idUser],
  3340. ])->first();
  3341. if(is_null($usr)){
  3342. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3343. }
  3344. $workteam = $this->encryptionController->decrypt($workteam);
  3345. if(!$workteam){
  3346. return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
  3347. }
  3348. $team = DB::table('S002V01TEQMA')->select([
  3349. 'EQMA_IDEQ as WORKTEAM_ID',
  3350. 'EQMA_NOMB as NAME',
  3351. 'EQMA_ESPE as SPECIALITY',
  3352. 'EQMA_ESTA as STATUS'
  3353. ])->where([
  3354. ['EQMA_IDEQ', '=', $workteam],
  3355. ['EQMA_NULI', '=', $line],
  3356. ])->first();
  3357. if(is_null($team)){
  3358. return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
  3359. }
  3360. $now = $this->functionsController->now();
  3361. $nowStr = $now->toDateTimeString();
  3362. $actions = DB::getQueryLog();
  3363. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3364. $idac = $this->functionsController->registerActivity(
  3365. $line,
  3366. 'S002V01M11GPRS',
  3367. 'S002V01F01AETR',
  3368. 'S002V01P03DETR',
  3369. 'Consulta',
  3370. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles del equipo de trabajo " . $team->NAME . ".",
  3371. $idUser,
  3372. $nowStr,
  3373. 'S002V01S04GETR'
  3374. );
  3375. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3376. return $this->responseController->makeResponse(false, 'EXITO.', $team);
  3377. }
  3378. public function getMembersOfWorkteamById($workteam, $idUser, $line) {
  3379. DB::enableQueryLog();
  3380. $idUser = $this->encryptionController->decrypt($idUser);
  3381. if(!$idUser){
  3382. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3383. }
  3384. $usr = DB::table('S002V01TUSUA')->where([
  3385. ['USUA_NULI', '=', $line],
  3386. ['USUA_IDUS', '=', $idUser],
  3387. ])->first();
  3388. if(is_null($usr)){
  3389. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3390. }
  3391. $workteam = $this->encryptionController->decrypt($workteam);
  3392. if(!$workteam){
  3393. return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
  3394. }
  3395. $team = DB::table('S002V01TEQMA')->where([
  3396. ['EQMA_IDEQ', '=', $workteam],
  3397. ['EQMA_NULI', '=', $line],
  3398. ])->first();
  3399. if(is_null($team)){
  3400. return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
  3401. }
  3402. $members = DB::table('S002V01TPERS')->select([
  3403. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  3404. 'PERS_IDPE AS IDEMPLEADO',
  3405. 'PERS_IDUS AS IDUSUARIO'
  3406. ])->where([
  3407. ['EQMA_IDEQ', '=', $workteam],
  3408. ['EQMA_NULI', '=', $line],
  3409. ['PERS_ESTA', '=', 'Activo'],
  3410. ])->join(
  3411. 'S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS'
  3412. )->join(
  3413. 'S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ'
  3414. )->get()->all();
  3415. foreach($members as $key=>$member){
  3416. $member->IDEMPLEADO = $this->encryptionController->encrypt($member->IDEMPLEADO);
  3417. $member->IDUSUARIO = $this->encryptionController->encrypt($member->IDUSUARIO);
  3418. $members[$key] = $member;
  3419. }
  3420. $now = $this->functionsController->now();
  3421. $nowStr = $now->toDateTimeString();
  3422. $actions = DB::getQueryLog();
  3423. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3424. $idac = $this->functionsController->registerActivity(
  3425. $line,
  3426. 'S002V01M11GPRS',
  3427. 'S002V01F01AETR',
  3428. 'S002V01P03DETR',
  3429. 'Consulta',
  3430. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los integrantes del equipo de trabajo " . $team->EQMA_NOMB . ".",
  3431. $idUser,
  3432. $nowStr,
  3433. 'S002V01S04GETR'
  3434. );
  3435. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3436. return $this->responseController->makeResponse(false, 'EXITO.', $members);
  3437. }
  3438. public function updateWorkteam(Request $request) {
  3439. DB::enableQueryLog();
  3440. $validator = Validator::make($request->all(), [
  3441. 'id_user' => 'required|string',
  3442. 'linea' => 'required|integer',
  3443. 'WORKTEAM_ID' =>'required|string',
  3444. 'NAME' => 'required|string|max:75',
  3445. 'SPECIALITY' => 'required|json',
  3446. ]);
  3447. if($validator->fails()) {
  3448. return $this->responseController->makeResponse(
  3449. TRUE,
  3450. 'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
  3451. $this->responseController->makeErrors($validator->errors()->messages()),
  3452. 400
  3453. );
  3454. }
  3455. $form = $request->all();
  3456. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3457. if(!$idUser){
  3458. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3459. }
  3460. $usr = DB::table('S002V01TUSUA')->where([
  3461. ['USUA_NULI', '=', $form['linea']],
  3462. ['USUA_IDUS', '=', $idUser],
  3463. ])->first();
  3464. if(is_null($usr)){
  3465. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3466. }
  3467. $workteam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
  3468. if(!$workteam){
  3469. return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
  3470. }
  3471. $team = DB::table('S002V01TEQMA')->where([
  3472. ['EQMA_IDEQ', '=', $workteam],
  3473. ['EQMA_NULI', '=', $form['linea']],
  3474. ])->first();
  3475. if(is_null($team)){
  3476. return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
  3477. }
  3478. $teams = DB::table('S002V01TEQMA')->where([
  3479. ['EQMA_NOMB', '=', $form['NAME']],
  3480. ['EQMA_NULI', '=', $form['linea']],
  3481. ['EQMA_ESTA', '=', 'Activo'],
  3482. ])->get()->all();
  3483. if(count($teams) > 0){
  3484. return $this->responseController->makeResponse(true, "El nombre $form[NAME] ya fue tomado", [], 401);
  3485. }
  3486. $specialtiesArr = json_decode($form['SPECIALITY'], true);
  3487. foreach($specialtiesArr as $key=>$specialty){
  3488. $specialtyCode = $this->encryptionController->decrypt($specialty);
  3489. if(!$specialtyCode){
  3490. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  3491. }
  3492. $specialtyObj = DB::table('S002V01TGEES')->where([
  3493. ['GEES_NULI', '=', $form['linea']],
  3494. ['GEES_COES', '=', $specialtyCode]
  3495. ])->first();
  3496. if(is_null($specialtyObj)){
  3497. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades no existe.", [], 404);
  3498. }else if($specialtyObj->GEES_ESTA == 'Eliminado'){
  3499. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de especialidades está eliminado.", [], 404);
  3500. }
  3501. $specialtiesArr[$key] = $specialtyCode;
  3502. }
  3503. $specialtiesStr = json_encode($specialtiesArr);
  3504. $now = $this->functionsController->now();
  3505. $nowStr = $now->toDateTimeString();
  3506. DB::table('S002V01TEQMA')->where([
  3507. ["EQMA_IDEQ", '=', $workteam],
  3508. ['EQMA_NULI', '=', $form['linea']]
  3509. ])->update([
  3510. "EQMA_NOMB" => $form['NAME'],
  3511. "EQMA_ESPE" => $specialtiesStr,
  3512. "EQMA_USMO" => $idUser,
  3513. "EQMA_FEMO" => $nowStr,
  3514. ]);
  3515. $actions = DB::getQueryLog();
  3516. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3517. $idac = $this->functionsController->registerActivity(
  3518. $form['linea'],
  3519. 'S002V01M11GPRS',
  3520. 'S002V01F01AETR',
  3521. 'S002V01P02REET',
  3522. 'Actualización',
  3523. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el equipo de trabajo #$workteam.",
  3524. $idUser,
  3525. $nowStr,
  3526. 'S002V01S04GETR'
  3527. );
  3528. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3529. return $this->responseController->makeResponse(false, 'EXITO.');
  3530. }
  3531. public function updateToInactiveStatus(Request $request) {
  3532. DB::enableQueryLog();
  3533. $validator = Validator::make($request->all(), [
  3534. 'id_user' => 'required|string',
  3535. 'linea' => 'required|integer',
  3536. 'WORKTEAM_ID' =>'required|string',
  3537. ]);
  3538. if($validator->fails()) {
  3539. return $this->responseController->makeResponse(
  3540. TRUE,
  3541. 'ERR_EQUIPO_TRABAJO_REG001: Uno o más errores encontrados',
  3542. $this->responseController->makeErrors($validator->errors()->messages()),
  3543. 400
  3544. );
  3545. }
  3546. $form = $request->all();
  3547. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3548. if(!$idUser){
  3549. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3550. }
  3551. $usr = DB::table('S002V01TUSUA')->where([
  3552. ['USUA_NULI', '=', $form['linea']],
  3553. ['USUA_IDUS', '=', $idUser],
  3554. ])->first();
  3555. if(is_null($usr)){
  3556. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3557. }
  3558. $workteam = $this->encryptionController->decrypt($form['WORKTEAM_ID']);
  3559. if(!$workteam){
  3560. return $this->responseController->makeResponse(true, 'El ID equipo de trabajo solicitado no está encriptado correctamente', [], 400);
  3561. }
  3562. $team = DB::table('S002V01TEQMA')->where([
  3563. ['EQMA_IDEQ', '=', $workteam],
  3564. ['EQMA_NULI', '=', $form['linea']],
  3565. ])->first();
  3566. if(is_null($team)){
  3567. return $this->responseController->makeResponse(true, 'El equipo de trabajo consultado no está registrado', [], 404);
  3568. }
  3569. $members = DB::table('S002V01TPERS')->select([
  3570. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) as NAME'),
  3571. 'PERS_IDPE AS IDEMPLEADO',
  3572. 'PERS_IDUS AS IDUSUARIO'
  3573. ])->where([
  3574. ['EQMA_IDEQ', '=', $workteam],
  3575. ['EQMA_NULI', '=', $form['linea']],
  3576. ['PERS_ESTA', '=', 'Activo'],
  3577. ])->join(
  3578. 'S002V01TUSUA', 'PERS_IDUS', '=', 'USUA_IDUS'
  3579. )->join(
  3580. 'S002V01TEQMA', 'PERS_EQTR', '=', 'EQMA_IDEQ'
  3581. )->get()->all();
  3582. if(count($members) > 0){
  3583. return $this->responseController->makeResponse(true, 'El equipo de trabajo que desea eliminar tiene usuarios relacionados.', [], 401);
  3584. }
  3585. $now = $this->functionsController->now();
  3586. $nowStr = $now->toDateTimeString();
  3587. DB::table('S002V01TEQMA')->where([
  3588. ["EQMA_IDEQ", '=', $workteam],
  3589. ['EQMA_NULI', '=', $form['linea']]
  3590. ])->update([
  3591. "EQMA_ESTA" => 'Eliminado',
  3592. "EQMA_USMO" => $idUser,
  3593. "EQMA_FEMO" => $nowStr,
  3594. ]);
  3595. $actions = DB::getQueryLog();
  3596. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3597. $idac = $this->functionsController->registerActivity(
  3598. $form['linea'],
  3599. 'S002V01M11GPRS',
  3600. 'S002V01F01AETR',
  3601. 'S002V01P01CETR',
  3602. 'Eliminación',
  3603. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el equipo de trabajo #$workteam.",
  3604. $idUser,
  3605. $nowStr,
  3606. 'S002V01S04GETR'
  3607. );
  3608. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3609. return $this->responseController->makeResponse(false, 'EXITO.');
  3610. }
  3611. public function storeContract(Request $request) {
  3612. DB::enableQueryLog();
  3613. $validator = Validator::make($request->all(), [
  3614. 'id_user' => 'required|string',
  3615. 'linea' => 'required|integer',
  3616. 'CONTRACT_NAME' => 'required|string|max:100',
  3617. 'WORK_ORDER' => 'required|string',
  3618. 'CONTRACT_TYPE' => 'required|string|in:Subcontratista,Interno',
  3619. 'DENOMINATION' => 'required|string',
  3620. 'START_DATE' => 'required|date',
  3621. 'END_DATE' => 'required|date',
  3622. 'CONTRACT_COST' => 'required|string',
  3623. 'DOCUMENT' => 'required|json',
  3624. ]);
  3625. if ($validator->fails()) {
  3626. return $this->responseController->makeResponse(
  3627. TRUE,
  3628. 'ERR_CONTRATO_REG001: Uno o más errores encontrados',
  3629. $this->responseController->makeErrors($validator->errors()->messages()),
  3630. 400
  3631. );
  3632. }
  3633. $form = $request->all();
  3634. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3635. if(!$idUser){
  3636. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  3637. }
  3638. $usr = DB::table('S002V01TUSUA')->where([
  3639. ['USUA_NULI', '=', $form['linea']],
  3640. ['USUA_IDUS', '=', $idUser]
  3641. ])->first();
  3642. if(is_null($usr)){
  3643. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  3644. }
  3645. $workOrder = $this->encryptionController->decrypt($form['WORK_ORDER']);
  3646. if(!$workOrder){
  3647. return $this->responseController->makeResponse(true, 'La información de la orden seleccionada no está encriptada correctamente.', [], 400);
  3648. }
  3649. $workOrderArr = explode('|', $workOrder);
  3650. if(count($workOrderArr) != 3){
  3651. return $this->responseController->makeResponse(true, 'El formato de la orden seleccionada es incorrecto.', [], 400);
  3652. }
  3653. $idOrder = $this->encryptionController->decrypt($workOrderArr[0]);
  3654. if(!$idOrder){
  3655. return $this->responseController->makeResponse(true, 'El ID de la orden seleccionada no está encriptado correctamente.', [], 400);
  3656. }
  3657. $order = null;
  3658. $idOrderStr = null;
  3659. if($workOrderArr[1] == 'MP'){
  3660. $idOrderArr = explode('|', $idOrder);
  3661. $order = DB::table('S002V01TBEOT')->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')->where([
  3662. ['BEOT_NULI', '=', $form['linea']],
  3663. ['BEOT_IDRE', '=', $idOrderArr[0]]
  3664. ])->first();
  3665. $idOrderStr = $idOrderArr[0];
  3666. }else if($workOrderArr[1] == 'MC'){
  3667. if($workOrderArr[2] == 'S'){
  3668. $order = DB::table('S002V01TOTCO')->where([
  3669. ['OTCO_NULI', '=', $form['linea']],
  3670. ['OTCO_IDOT', '=', $idOrder],
  3671. ])->first();
  3672. }else if($workOrderArr[2] == 'N'){
  3673. $order = DB::table('S002V01TFCPE')->where([
  3674. ['FCPE_NULI', '=', $form['linea']],
  3675. ['FCPE_IDRE', '=', $idOrder]
  3676. ])->first();
  3677. }
  3678. $idOrderStr = $idOrder;
  3679. }
  3680. if(is_null($order)){
  3681. return $this->responseController->makeResponse(true, 'La orden seleccionada no existe.', [], 404);
  3682. }
  3683. $idEmployee = $this->encryptionController->decrypt($form['DENOMINATION']);
  3684. if(!$idEmployee){
  3685. return $this->responseController->makeResponse(true, 'El ID del empleado seleccionado no está encriptado correctamente.', [], 400);
  3686. }
  3687. $employee = DB::table('S002V01TPERS')->where([
  3688. ['PERS_NULI', '=', $form['linea']],
  3689. ['PERS_IDPE', '=', $idEmployee]
  3690. ])->first();
  3691. if(is_null($employee)){
  3692. return $this->responseController->makeResponse(true, 'El empleado seleccionado no existe.', [], 404);
  3693. }
  3694. $orderType = $workOrderArr[1] == 'MP' ? 'Preventivo' : 'Correctivo';
  3695. $contract = DB::table('S002V01TCONT')->where([
  3696. ['CONT_NULI', '=', $form['linea']],
  3697. ['CONT_IDEM', '=', $idEmployee],
  3698. ['CONT_IDOT', '=', $idOrder],
  3699. ['CONT_TOTR', '=', $orderType],
  3700. ])->first();
  3701. if(!is_null($contract)){
  3702. return $this->responseController->makeResponse(true, "El empleado #$idEmployee ya tiene un contrato relacionado a la orden de trabajo $orderType #$idOrder", [], 404);
  3703. }
  3704. $docsArr = json_decode($form['DOCUMENT'], true);
  3705. $finalDocsArr = [];
  3706. foreach($docsArr as $doc){
  3707. $idFileDec = $this->encryptionController->decrypt($doc['id']);
  3708. $tempFile = DB::table('S002V01TARTE')->where([
  3709. ['ARTE_NULI', '=', $form['linea']],
  3710. ['ARTE_IDAR', '=', $idFileDec],
  3711. ])->first();
  3712. if(is_null($tempFile)){
  3713. return $this->responseController->makeResponse(true, "El archivo $doc[name] no está registrado.", [], 404);
  3714. }
  3715. $cldo = "CO";
  3716. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], "GPRS", $cldo, $tempFile, $idUser);
  3717. if(!$finalFile[0]){
  3718. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  3719. }else{
  3720. $finalDocsArr[] = $finalFile[1];
  3721. }
  3722. }
  3723. $contractCostStr = $this->encryptionController->decrypt($form['CONTRACT_COST']);
  3724. if(!$contractCostStr){
  3725. return $this->responseController->makeResponse(true, 'El costo del contrato no fue encriptado correctamente.', [], 400);
  3726. }
  3727. $contractCostNum = floatval($contractCostStr);
  3728. $lido = json_encode($finalDocsArr);
  3729. $now = $this->functionsController->now();
  3730. $nowStr = $now->toDateTimeString();
  3731. $idContract = DB::table('S002V01TCONT')->insertGetId([
  3732. 'CONT_NULI' => $form['linea'],
  3733. 'CONT_NOCO' => $form['CONTRACT_NAME'],
  3734. 'CONT_IDEM' => $idEmployee,
  3735. 'CONT_IDOT' => $idOrderStr,
  3736. 'CONT_TOTR' => $orderType,
  3737. 'CONT_TIPO' => $form['CONTRACT_TYPE'],
  3738. 'CONT_FEIN' => $form['START_DATE'],
  3739. 'CONT_FEFI' => $form['END_DATE'],
  3740. 'CONT_COST' => $contractCostNum,
  3741. 'CONT_LIDO' => $lido,
  3742. 'CONT_USRE' => $idUser,
  3743. 'CONT_FERE' => $nowStr,
  3744. ]);
  3745. $actions = DB::getQueryLog();
  3746. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3747. $idac = $this->functionsController->registerActivity(
  3748. $form['linea'],
  3749. 'S002V01M11GPRS',
  3750. 'S002V01F02ADCN',
  3751. 'S002V01P02RECO',
  3752. 'Registro',
  3753. "El usuario $name (" . $usr->USUA_IDUS . ") registró el contrato #$idContract.",
  3754. $idUser,
  3755. $nowStr,
  3756. 'S002V01S03GEIN'
  3757. );
  3758. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3759. return $this->responseController->makeResponse(false, 'EXITO');
  3760. }
  3761. public function getConsultOfContracts($idUser, $line) {
  3762. DB::enableQueryLog();
  3763. $idUser = $this->encryptionController->decrypt($idUser);
  3764. if(!$idUser){
  3765. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3766. }
  3767. $usr = DB::table('S002V01TUSUA')->where([
  3768. ['USUA_NULI', '=', $line],
  3769. ['USUA_IDUS', '=', $idUser],
  3770. ])->first();
  3771. if(is_null($usr)){
  3772. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3773. }
  3774. $contracts = DB::table('S002V01TCONT')->select([
  3775. 'CONT_IDCO AS CONTRACT_ID',
  3776. 'CONT_NOCO AS CONTRACT_NAME',
  3777. 'CONT_IDEM AS DENOMINATION',
  3778. 'CONT_IDOT AS WORK_ORDER_ID',
  3779. 'CONT_TOTR AS WORK_ORDER_TYPE',
  3780. 'CONT_TIPO AS CONTRACT_TYPE',
  3781. 'CONT_FEIN AS START_DATE',
  3782. 'CONT_FEFI AS END_DATE',
  3783. 'CONT_COST AS CONTRACT_COST',
  3784. 'CONT_LIDO AS DOCUMENT',
  3785. 'CONT_USRE AS REGISTERED_BY',
  3786. 'CONT_FERE AS REGISTER_DATE',
  3787. 'CONT_USMO AS MODIFIED_BY',
  3788. 'CONT_FEMO AS MODIFICATION_DATE',
  3789. ])->where('CONT_NULI', '=', $line)->get()->all();
  3790. $now = $this->functionsController->now();
  3791. $nowStr = $now->toDateTimeString();
  3792. foreach($contracts as $key=>$contract){
  3793. $contract->CONTRACT_ID = $this->encryptionController->encrypt($contract->CONTRACT_ID);
  3794. $contract->CONTRACT_COST = $this->encryptionController->encrypt($contract->CONTRACT_COST);
  3795. $docsArr = json_decode($contract->DOCUMENT);
  3796. $docsFN = [];
  3797. foreach($docsArr as $keyDoc=>$doc){
  3798. $docIDArr = explode('=', $doc);
  3799. $codeArr = explode('-', $docIDArr[0]);
  3800. $file = DB::table('S002V01TAFAL')->where([
  3801. ['AFAL_NULI', '=', $line],
  3802. ['AFAL_COMO', '=', $codeArr[1]],
  3803. ['AFAL_CLDO', '=', $codeArr[2]],
  3804. ['AFAL_FECR', '=', $codeArr[3]],
  3805. ['AFAL_NUSE', '=', $codeArr[4]],
  3806. ['AFAL_NUVE', '=', $docIDArr[1]],
  3807. ])->first();
  3808. if (!is_null($file)) {
  3809. $docsFN[] = [
  3810. 'id' => $this->encryptionController->encrypt($doc),
  3811. 'name' => $doc,
  3812. 'size' => $file->AFAL_TAMA
  3813. ];
  3814. }
  3815. }
  3816. $contract->DOCUMENT = json_encode($docsFN);
  3817. $usrReg = DB::table('S002V01TUSUA')->where([
  3818. ['USUA_NULI', '=', $line],
  3819. ['USUA_IDUS', '=', $contract->REGISTERED_BY],
  3820. ])->first();
  3821. $contract->REGISTERED_BY = $this->functionsController->joinName(
  3822. $usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA
  3823. ) . " (" . $contract->REGISTERED_BY . ")";
  3824. if(!is_null($contract->MODIFIED_BY)){
  3825. $usrMod = DB::table('S002V01TUSUA')->where([
  3826. ['USUA_NULI', '=', $line],
  3827. ['USUA_IDUS', '=', $contract->MODIFIED_BY],
  3828. ])->first();
  3829. $contract->MODIFIED_BY = $this->functionsController->joinName(
  3830. $usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA
  3831. ) . " (" . $contract->MODIFIED_BY . ")";
  3832. }
  3833. $employee = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
  3834. ['PERS_NULI', '=', $line],
  3835. ['PERS_IDPE', '=', $contract->DENOMINATION],
  3836. ])->first();
  3837. $contract->DENOMINATION = $this->functionsController->joinName(
  3838. $employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA
  3839. ) . ' (' . $employee->PERS_IDPE . ') (' . $employee->PERS_IDUS . ')';
  3840. $contract->DURATION = $this->functionsController->getDatesDifference($contract->START_DATE, $contract->END_DATE);
  3841. $contracts[$key] = $contract;
  3842. $endDate = new Carbon($contract->END_DATE);
  3843. $status = $now->gt($endDate) ? 'Expirado' : 'Activo';
  3844. $contract->STATUS = $status;
  3845. }
  3846. $actions = DB::getQueryLog();
  3847. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3848. $idac = $this->functionsController->registerActivity(
  3849. $line,
  3850. 'S002V01M11GPRS',
  3851. 'S002V01F02ADCN',
  3852. 'S002V01P01COCO',
  3853. 'Consulta',
  3854. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los contratos registrados.",
  3855. $idUser,
  3856. $nowStr,
  3857. 'S002V01S03GEIN'
  3858. );
  3859. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3860. return $this->responseController->makeResponse(false, 'EXITO', $contracts);
  3861. }
  3862. public function getConsultOfInterventions($idUser, $line) {
  3863. DB::enableQueryLog();
  3864. $idUser = $this->encryptionController->decrypt($idUser);
  3865. if(!$idUser){
  3866. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3867. }
  3868. $usr = DB::table('S002V01TUSUA')->where([
  3869. ['USUA_NULI', '=', $line],
  3870. ['USUA_IDUS', '=', $idUser],
  3871. ])->first();
  3872. if(is_null($usr)){
  3873. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3874. }
  3875. $correctiveInterventions = DB::table('S002V01TOTCO')->select([
  3876. 'OTCO_IDOT AS IDREG',
  3877. 'OTCO_IDOT AS IDORDER',
  3878. DB::raw("CONCAT(
  3879. OTCO_EQIN, ' - ',
  3880. EQUI_TIPO, ' - ',
  3881. EQUI_MODE, ' (',
  3882. EQUI_IDEQ, ')'
  3883. ) AS EQUIPMENT"),
  3884. DB::raw("'C' AS ORDER_TYPE"),
  3885. 'OTCO_ESOR AS ACTION_TYPE',
  3886. 'OTCO_FIFA AS START_DATE',
  3887. 'OTCO_FTIN AS END_DATE'
  3888. ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN');
  3889. $maintenanceInterventions = DB::table('S002V01TBEOT')->select([
  3890. DB::raw('CONCAT(BEOT_IDRE, "|", BEOT_FEPR) AS IDREG'),
  3891. 'OTPR_IDOT AS IDORDER',
  3892. DB::raw("CONCAT(
  3893. OTPR_EQIN, ' - ',
  3894. EQUI_TIPO, ' - ',
  3895. EQUI_MODE, ' (',
  3896. EQUI_IDEQ, ')'
  3897. ) AS EQUIPMENT"),
  3898. DB::raw("'P' AS ORDER_TYPE"),
  3899. 'BEOT_TIAC AS ACTION_TYPE',
  3900. 'BEOT_FEEJ AS START_DATE',
  3901. 'BEOT_FEFI AS END_DATE'
  3902. ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')
  3903. ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')
  3904. ->union($correctiveInterventions)->orderBy('IDREG', 'desc')->get()->all();
  3905. foreach($maintenanceInterventions as $key=>$val){
  3906. $val->IDREG = $this->encryptionController->encrypt($val->IDREG);
  3907. $val->IDORDER = $this->encryptionController->encrypt($val->IDORDER);
  3908. $val->EQUIPMENT = $this->encryptionController->encrypt($val->EQUIPMENT);
  3909. $preventiveInterventions[$key] = $val;
  3910. }
  3911. $now = $this->functionsController->now();
  3912. $nowStr = $now->toDateTimeString();
  3913. $actions = DB::getQueryLog();
  3914. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3915. $idac = $this->functionsController->registerActivity(
  3916. $line,
  3917. 'S002V01M11GPRS',
  3918. 'S002V01F01ADIN',
  3919. '-',
  3920. 'Consulta',
  3921. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las intervenciones registradas.",
  3922. $idUser,
  3923. $nowStr,
  3924. 'S002V01S03GEIN'
  3925. );
  3926. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3927. return $this->responseController->makeResponse(false, 'EXITO', $preventiveInterventions);
  3928. }
  3929. public function getAllRegisteredSpecialties($idUser, $line) {
  3930. DB::enableQueryLog();
  3931. $idUser = $this->encryptionController->decrypt($idUser);
  3932. if(!$idUser){
  3933. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3934. }
  3935. $usr = DB::table('S002V01TUSUA')->where([
  3936. ['USUA_NULI', '=', $line],
  3937. ['USUA_IDUS', '=', $idUser],
  3938. ])->first();
  3939. if(is_null($usr)){
  3940. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3941. }
  3942. $specialties = DB::table('S002V01TGEES')->select([
  3943. 'GEES_COES AS CODIGO_ESPECIALIDAD',
  3944. 'GEES_NOES AS NOMBRE_ESPECIALIDAD',
  3945. 'GEES_ESTA AS ESTADO',
  3946. DB::raw("CONCAT(USRE.USUA_NOMB, ' ', USRE.USUA_APPA, IF(ISNULL(USRE.USUA_APMA), '', ' '), IF(ISNULL(USRE.USUA_APMA), '', USRE.USUA_APMA), ' (', GEES_USRE, ')') AS USRREG"),
  3947. 'GEES_FERE AS FECREG',
  3948. DB::raw("IF(ISNULL(USMO.USUA_NOMB), NULL, CONCAT(USMO.USUA_NOMB, ' ', USMO.USUA_APPA, IF(ISNULL(USMO.USUA_APMA), '', ' '), IF(ISNULL(USMO.USUA_APMA), '', USMO.USUA_APMA), ' (', GEES_USMO, ')')) AS USRMOD"),
  3949. 'GEES_FEMO AS FECMOD',
  3950. ])->join(DB::raw('S002V01TUSUA USRE'), 'USRE.USUA_IDUS', '=', 'GEES_USRE')
  3951. ->leftJoin(DB::raw('S002V01TUSUA USMO'), 'USMO.USUA_IDUS', '=', 'GEES_USMO')
  3952. ->where('GEES_NULI', '=', $line)->get()->all();
  3953. foreach($specialties as $key=>$specialty){
  3954. $specialty->CODIGO_ESPECIALIDAD = $this->encryptionController->encrypt($specialty->CODIGO_ESPECIALIDAD);
  3955. $specialties[$key] = $specialty;
  3956. }
  3957. $now = $this->functionsController->now();
  3958. $nowStr = $now->toDateTimeString();
  3959. $actions = DB::getQueryLog();
  3960. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3961. $idac = $this->functionsController->registerActivity(
  3962. $line,
  3963. 'S002V01M11GPRS',
  3964. '-',
  3965. '-',
  3966. 'Consulta',
  3967. "El usuario $name (" . $usr->USUA_IDUS . ") las especialidades registradas.",
  3968. $idUser,
  3969. $nowStr,
  3970. );
  3971. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3972. return $this->responseController->makeResponse(false, 'EXITO', $specialties);
  3973. }
  3974. public function registerSpecialty(Request $request) {
  3975. DB::enableQueryLog();
  3976. $validator = Validator::make($request->all(), [
  3977. 'id_user' => 'required|string',
  3978. 'linea' => 'required|integer',
  3979. 'specialty_code' => 'required|string',
  3980. 'spacialty_name' => 'required|string|max:100',
  3981. ]);
  3982. if ($validator->fails()) {
  3983. return $this->responseController->makeResponse(
  3984. TRUE,
  3985. 'ERR_CONTRATO_REG001: Uno o más errores encontrados',
  3986. $this->responseController->makeErrors($validator->errors()->messages()),
  3987. 400
  3988. );
  3989. }
  3990. $form = $request->all();
  3991. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3992. if(!$idUser){
  3993. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  3994. }
  3995. $usr = DB::table('S002V01TUSUA')->where([
  3996. ['USUA_NULI', '=', $form['linea']],
  3997. ['USUA_IDUS', '=', $idUser]
  3998. ])->first();
  3999. if(is_null($usr)){
  4000. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4001. }
  4002. $specialtyCode = $this->encryptionController->decrypt($form['specialty_code']);
  4003. if(!$specialtyCode){
  4004. return $this->responseController->makeResponse(true, 'El código de la especialidad no fue encriptado correctamente.', [], 400);
  4005. }
  4006. $filtCode = DB::table('S002V01TGEES')->where([
  4007. ['GEES_NULI', '=', $form['linea']],
  4008. ['GEES_COES', '=', $specialtyCode],
  4009. ['GEES_ESTA', '=', 'Activo']
  4010. ])->first();
  4011. if(!is_null($filtCode)){
  4012. return $this->responseController->makeResponse(true, 'El código ingresado ya se encuentra registrado.', [], 400);
  4013. }
  4014. $filtName = DB::table('S002V01TGEES')->where([
  4015. ['GEES_NULI', '=', $form['linea']],
  4016. ['GEES_NOES', '=', $form['spacialty_name']],
  4017. ['GEES_ESTA', '=', 'Activo']
  4018. ])->first();
  4019. if(!is_null($filtName)){
  4020. return $this->responseController->makeResponse(true, 'El nombre ingresado ya se encuentra registrado.', [], 400);
  4021. }
  4022. $now = $this->functionsController->now();
  4023. $nowStr = $now->toDateTimeString();
  4024. DB::table('S002V01TGEES')->insert([
  4025. 'GEES_NULI' => $form['linea'],
  4026. 'GEES_COES' => $specialtyCode,
  4027. 'GEES_NOES' => $form['spacialty_name'],
  4028. 'GEES_USRE' => $idUser,
  4029. 'GEES_FERE' => $nowStr
  4030. ]);
  4031. $actions = DB::getQueryLog();
  4032. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4033. $idac = $this->functionsController->registerActivity(
  4034. $form['linea'],
  4035. 'S002V01M11GPRS',
  4036. 'S002V01F02ADCN',
  4037. 'S002V01P02RECO',
  4038. 'Registro',
  4039. "El usuario $name (" . $usr->USUA_IDUS . ") registró la especialidad $form[spacialty_name]($specialtyCode).",
  4040. $idUser,
  4041. $nowStr,
  4042. 'S002V01S03GEIN'
  4043. );
  4044. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  4045. return $this->responseController->makeResponse(false, 'EXITO');
  4046. }
  4047. public function getSpecialtyByCode($code, $idUser, $line) {
  4048. DB::enableQueryLog();
  4049. $idUser = $this->encryptionController->decrypt($idUser);
  4050. if(!$idUser){
  4051. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4052. }
  4053. $usr = DB::table('S002V01TUSUA')->where([
  4054. ['USUA_NULI', '=', $line],
  4055. ['USUA_IDUS', '=', $idUser],
  4056. ])->first();
  4057. if(is_null($usr)){
  4058. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4059. }
  4060. $code = $this->encryptionController->decrypt($code);
  4061. if(!$code){
  4062. return $this->responseController->makeResponse(true, 'El código de la especialidad consultada no está encriptado correctamente', [], 400);
  4063. }
  4064. $specialty = DB::table('S002V01TGEES')->select([
  4065. 'GEES_COES AS CODIGO_ESPECIALIDAD',
  4066. 'GEES_NOES AS NOMBRE_ESPECIALIDAD',
  4067. 'GEES_ESTA AS ESTADO',
  4068. DB::raw("CONCAT(USRE.USUA_NOMB, ' ', USRE.USUA_APPA, IF(ISNULL(USRE.USUA_APMA), '', ' '), IF(ISNULL(USRE.USUA_APMA), '', USRE.USUA_APMA), ' (', GEES_USRE, ')') AS USRREG"),
  4069. 'GEES_FERE AS FECREG',
  4070. DB::raw("IF(ISNULL(USMO.USUA_NOMB), NULL, CONCAT(USMO.USUA_NOMB, ' ', USMO.USUA_APPA, IF(ISNULL(USMO.USUA_APMA), '', ' '), IF(ISNULL(USMO.USUA_APMA), '', USMO.USUA_APMA), ' (', GEES_USMO, ')')) AS USRMOD"),
  4071. 'GEES_FEMO AS FECMOD',
  4072. ])->join(DB::raw('S002V01TUSUA USRE'), 'USRE.USUA_IDUS', '=', 'GEES_USRE')
  4073. ->leftJoin(DB::raw('S002V01TUSUA USMO'), 'USMO.USUA_IDUS', '=', 'GEES_USMO')
  4074. ->where([
  4075. ['GEES_NULI', '=', $line],
  4076. ['GEES_COES', '=', $code]
  4077. ])->first();
  4078. if(is_null($specialty)){
  4079. return $this->responseController->makeResponse(true, 'La especialidad consultada no está registrada.', [], 404);
  4080. }
  4081. $specialty->CODIGO_ESPECIALIDAD = $this->encryptionController->encrypt($specialty->CODIGO_ESPECIALIDAD);
  4082. $now = $this->functionsController->now();
  4083. $nowStr = $now->toDateTimeString();
  4084. $actions = DB::getQueryLog();
  4085. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4086. $idac = $this->functionsController->registerActivity(
  4087. $line,
  4088. 'S002V01M11GPRS',
  4089. '-',
  4090. '-',
  4091. 'Consulta',
  4092. "El usuario $name (" . $usr->USUA_IDUS . ") la especialidad $code.",
  4093. $idUser,
  4094. $nowStr,
  4095. );
  4096. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4097. return $this->responseController->makeResponse(false, 'EXITO', $specialty);
  4098. }
  4099. public function updateSpecialty(Request $request) {
  4100. DB::enableQueryLog();
  4101. $validator = Validator::make($request->all(), [
  4102. 'id_user' => 'required|string',
  4103. 'linea' => 'required|integer',
  4104. 'specialty_code' => 'required|string',
  4105. 'spacialty_name' => 'required|string|max:75',
  4106. ]);
  4107. if ($validator->fails()) {
  4108. return $this->responseController->makeResponse(
  4109. TRUE,
  4110. 'ERR_CONTRATO_REG001: Uno o más errores encontrados',
  4111. $this->responseController->makeErrors($validator->errors()->messages()),
  4112. 400
  4113. );
  4114. }
  4115. $form = $request->all();
  4116. $idUser = $this->encryptionController->decrypt($form['id_user']);
  4117. if(!$idUser){
  4118. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  4119. }
  4120. $usr = DB::table('S002V01TUSUA')->where([
  4121. ['USUA_NULI', '=', $form['linea']],
  4122. ['USUA_IDUS', '=', $idUser]
  4123. ])->first();
  4124. if(is_null($usr)){
  4125. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4126. }
  4127. $specialtyCode = $this->encryptionController->decrypt($form['specialty_code']);
  4128. if(!$specialtyCode){
  4129. return $this->responseController->makeResponse(true, 'El código de la especialidad no fue encriptado correctamente.', [], 400);
  4130. }
  4131. $specialty = DB::table('S002V01TGEES')->where([
  4132. ['GEES_NULI', '=', $form['linea']],
  4133. ['GEES_COES', '=', $specialtyCode],
  4134. ])->first();
  4135. if(is_null($specialty)){
  4136. return $this->responseController->makeResponse(true, 'La especialidad que desea actualizar no existe.', [], 404);
  4137. }else if($specialty->GEES_ESTA == 'Eliminado'){
  4138. return $this->responseController->makeResponse(true, 'La especialidad que desea actualizar está eliminada.', [], 404);
  4139. }
  4140. $filtName = DB::table('S002V01TGEES')->where([
  4141. ['GEES_NULI', '=', $form['linea']],
  4142. ['GEES_NOES', '=', $form['spacialty_name']],
  4143. ['GEES_ESTA', '=', 'Activo']
  4144. ])->first();
  4145. if(!is_null($filtName)){
  4146. return $this->responseController->makeResponse(true, 'El nombre ingresado ya se encuentra registrado.', [], 400);
  4147. }
  4148. $now = $this->functionsController->now();
  4149. $nowStr = $now->toDateTimeString();
  4150. DB::table('S002V01TGEES')->where([
  4151. ['GEES_NULI', '=', $form['linea']],
  4152. ['GEES_COES', '=', $specialtyCode],
  4153. ])->update([
  4154. 'GEES_NOES' => $form['spacialty_name'],
  4155. 'GEES_USMO' => $idUser,
  4156. 'GEES_FEMO' => $nowStr
  4157. ]);
  4158. $actions = DB::getQueryLog();
  4159. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4160. $idac = $this->functionsController->registerActivity(
  4161. $form['linea'],
  4162. 'S002V01M11GPRS',
  4163. 'S002V01F02ADCN',
  4164. 'S002V01P02RECO',
  4165. 'Actualización',
  4166. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la especialidad $specialtyCode.",
  4167. $idUser,
  4168. $nowStr,
  4169. 'S002V01S03GEIN'
  4170. );
  4171. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  4172. return $this->responseController->makeResponse(false, 'EXITO');
  4173. }
  4174. public function deleteSpecialty(Request $request) {
  4175. DB::enableQueryLog();
  4176. $validator = Validator::make($request->all(), [
  4177. 'id_user' => 'required|string',
  4178. 'linea' => 'required|integer',
  4179. 'specialty_code' => 'required|string',
  4180. ]);
  4181. if ($validator->fails()) {
  4182. return $this->responseController->makeResponse(
  4183. TRUE,
  4184. 'ERR_CONTRATO_REG001: Uno o más errores encontrados',
  4185. $this->responseController->makeErrors($validator->errors()->messages()),
  4186. 400
  4187. );
  4188. }
  4189. $form = $request->all();
  4190. $idUser = $this->encryptionController->decrypt($form['id_user']);
  4191. if(!$idUser){
  4192. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  4193. }
  4194. $usr = DB::table('S002V01TUSUA')->where([
  4195. ['USUA_NULI', '=', $form['linea']],
  4196. ['USUA_IDUS', '=', $idUser]
  4197. ])->first();
  4198. if(is_null($usr)){
  4199. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4200. }
  4201. $specialtyCode = $this->encryptionController->decrypt($form['specialty_code']);
  4202. if(!$specialtyCode){
  4203. return $this->responseController->makeResponse(true, 'El código de la especialidad no fue encriptado correctamente.', [], 400);
  4204. }
  4205. $specialty = DB::table('S002V01TGEES')->where([
  4206. ['GEES_NULI', '=', $form['linea']],
  4207. ['GEES_COES', '=', $specialtyCode],
  4208. ])->first();
  4209. if(is_null($specialty)){
  4210. return $this->responseController->makeResponse(true, 'La especialidad que desea actualizar no existe.', [], 404);
  4211. }else if($specialty->GEES_ESTA == 'Eliminado'){
  4212. return $this->responseController->makeResponse(true, 'La especialidad que desea actualizar está eliminada.', [], 404);
  4213. }
  4214. $now = $this->functionsController->now();
  4215. $nowStr = $now->toDateTimeString();
  4216. DB::table('S002V01TGEES')->where([
  4217. ['GEES_NULI', '=', $form['linea']],
  4218. ['GEES_COES', '=', $specialtyCode],
  4219. ])->update([
  4220. 'GEES_ESTA' => 'Eliminado',
  4221. 'GEES_USMO' => $idUser,
  4222. 'GEES_FEMO' => $nowStr
  4223. ]);
  4224. $actions = DB::getQueryLog();
  4225. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4226. $idac = $this->functionsController->registerActivity(
  4227. $form['linea'],
  4228. 'S002V01M11GPRS',
  4229. 'S002V01F02ADCN',
  4230. 'S002V01P02RECO',
  4231. 'Eliminación',
  4232. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la especialidad $specialtyCode.",
  4233. $idUser,
  4234. $nowStr,
  4235. 'S002V01S03GEIN'
  4236. );
  4237. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  4238. return $this->responseController->makeResponse(false, 'EXITO');
  4239. }
  4240. }