PersonnelManagementController.php 210 KB

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