EquipmentManagementController.php 262 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Support\Carbon;
  7. use Dompdf\Dompdf;
  8. use Illuminate\Support\Facades\Storage;
  9. use Illuminate\Http\File;
  10. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  11. use PhpOffice\PhpSpreadsheet\IOFactory;
  12. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  13. use PhpOffice\PhpSpreadsheet\Style\Fill;
  14. use PhpOffice\PhpSpreadsheet\Style\Alignment;
  15. use PhpOffice\PhpSpreadsheet\Style\Border;
  16. use PhpOffice\PhpSpreadsheet\Style\Color;
  17. use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
  18. use PhpOffice\PhpSpreadsheet\Writer\Pdf\Mpdf;
  19. class EquipmentManagementController extends Controller{
  20. private $responseController;
  21. private $encryptionController;
  22. private $functionsController;
  23. private $templatesUbic;
  24. private $documentManagementController;
  25. private $pccValidElements;
  26. public function __construct(){
  27. $this->responseController = new ResponseController();
  28. $this->encryptionController = new EncryptionController();
  29. $this->functionsController = new FunctionsController();
  30. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  31. $this->templatesUbic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\public\pdf_templates\\01_05_GEEQ\\";
  32. } else {
  33. $this->templatesUbic = "C:\inetpub\wwwroot\sam\storage\app\public\pdf_templates\\01_05_GEEQ\\";
  34. }
  35. $this->documentManagementController = new DocumentManagementController();
  36. $this->pccValidElements = [
  37. ['coord' => '0N', 'element' => 'PDC', 'code' => 'PDCXX'],
  38. ['coord' => '1F', 'element' => 'BAT', 'code' => 'BATXX'],
  39. ['coord' => '1I', 'element' => 'BAT', 'code' => 'BATXX'],
  40. ['coord' => '1R', 'element' => 'SAP/IHM OA', 'code' => 'SAIOA'],
  41. ['coord' => '2F', 'element' => 'UPS', 'code' => 'UPSXX'],
  42. ['coord' => '2I', 'element' => 'UPS', 'code' => 'UPSXX'],
  43. ['coord' => '2R', 'element' => 'PIU/DDP', 'code' => 'PIUDD'],
  44. ['coord' => '2V', 'element' => 'ODF', 'code' => 'ODFXX'],
  45. ['coord' => '3F', 'element' => 'BAT', 'code' => 'BATXX'],
  46. ['coord' => '3I', 'element' => 'BAT', 'code' => 'BATXX'],
  47. ['coord' => '3Ñ', 'element' => 'SRV-COMMS PCC-A', 'code' => 'SRCPA'],
  48. ['coord' => '3R', 'element' => 'CCTV', 'code' => 'CCTVX'],
  49. ['coord' => '4F', 'element' => 'BAT', 'code' => 'BATXX'],
  50. ['coord' => '4I', 'element' => 'BAT', 'code' => 'BATXX'],
  51. ['coord' => '4Ñ', 'element' => 'SRV-COMMS PCC-B', 'code' => 'SRCPB'],
  52. ['coord' => '4R', 'element' => 'LTE', 'code' => 'LTEXX'],
  53. ['coord' => '4V', 'element' => 'AC', 'code' => 'ACXXX'],
  54. ['coord' => '5Ñ', 'element' => 'SRV-COMMS PCC-C', 'code' => 'SRCPC'],
  55. ['coord' => '6F', 'element' => 'UPS', 'code' => 'UPSXX'],
  56. ['coord' => '6I', 'element' => 'UPS', 'code' => 'UPSXX'],
  57. ['coord' => '6R', 'element' => 'TEL/GDA', 'code' => 'TELGD'],
  58. ['coord' => '6V', 'element' => 'AC', 'code' => 'ACXXX'],
  59. ['coord' => '7Ñ', 'element' => 'SCADA E&M', 'code' => 'SCAEM'],
  60. ['coord' => '7R', 'element' => 'CLK/CDA', 'code' => 'CLKCD'],
  61. ['coord' => '8B', 'element' => 'INTERRUPTOR ELECTROMAGNÉTICO 3x1600 AMP', 'code' => 'IE316'],
  62. ['coord' => '8R', 'element' => 'RMS', 'code' => 'RMSXX'],
  63. ['coord' => '9V', 'element' => 'LTE-B', 'code' => 'LTEBX'],
  64. ['coord' => '10B', 'element' => 'TRANSFORMADOR TIPO SECO 500 KVA', 'code' => 'TTS5K'],
  65. ['coord' => '11U', 'element' => 'ARMARIOS RECUPERACIÓN DE MANDO L1 A L6', 'code' => 'ARM16'],
  66. ['coord' => '11V', 'element' => 'ARMARIOS RECUPERACIÓN DE MANDO L1 A L6', 'code' => 'ARM16'],
  67. ['coord' => '11W', 'element' => 'MDF', 'code' => 'MDFXX'],
  68. ['coord' => '11Y', 'element' => 'ODF', 'code' => 'ODFXX'],
  69. ['coord' => '12F', 'element' => 'UPS', 'code' => 'UPSXX'],
  70. ['coord' => '12J', 'element' => 'COBRE', 'code' => 'COBRE'],
  71. ['coord' => '12L', 'element' => 'COBRE', 'code' => 'COBRE'],
  72. ['coord' => '12M', 'element' => 'COBRE', 'code' => 'COBRE'],
  73. ['coord' => '12Ñ', 'element' => 'RED', 'code' => 'REDXX'],
  74. ['coord' => '12O', 'element' => 'RED', 'code' => 'REDXX'],
  75. ['coord' => '12Q', 'element' => 'RED', 'code' => 'REDXX'],
  76. ['coord' => '13B', 'element' => 'TABLERO A', 'code' => 'TABLA'],
  77. ['coord' => '14F', 'element' => 'BAT', 'code' => 'BATXX'],
  78. ['coord' => '15F', 'element' => 'UPS', 'code' => 'UPSXX'],
  79. ['coord' => '15K', 'element' => 'CCTV L1 A L6', 'code' => 'CCT16'],
  80. ['coord' => '15Ñ', 'element' => 'RED C Y S L1 A L6', 'code' => 'RCS16'],
  81. ['coord' => '15W', 'element' => 'TRACCIÓN', 'code' => 'TRACC'],
  82. ['coord' => '16B', 'element' => 'TABLERO P', 'code' => 'TABLP'],
  83. ['coord' => '16F', 'element' => 'BAT', 'code' => 'BATXX'],
  84. ['coord' => '16K', 'element' => 'CCTV L1 A L6', 'code' => 'CCT16'],
  85. ['coord' => '16Ñ', 'element' => 'RED C Y S L1 A L6', 'code' => 'RCS16'],
  86. ['coord' => '16W', 'element' => 'TRACCIÓN', 'code' => 'TRACC'],
  87. ['coord' => '17W', 'element' => 'DISTRIBUCIÓN DE ENERGÍA L2', 'code' => 'DIEL2'],
  88. ['coord' => '19B', 'element' => 'TABLERO B', 'code' => 'TABLB'],
  89. ['coord' => '19K', 'element' => 'TELECOM L2', 'code' => 'TELL2'],
  90. ['coord' => '19Ñ', 'element' => 'SERVIDOR BASE DE DATOS L2', 'code' => 'SBDL2'],
  91. ['coord' => '19R', 'element' => 'SERVIDOR DE APLICACIONES L2', 'code' => 'SEAL2'],
  92. ['coord' => '19W', 'element' => 'DISTRIBUCIÓN DE ENERGÍA L3', 'code' => 'DIEL3'],
  93. ['coord' => '20F', 'element' => 'UPS', 'code' => 'UPSXX'],
  94. ['coord' => '20K', 'element' => 'TELECOM L3', 'code' => 'TELL3'],
  95. ['coord' => '20Ñ', 'element' => 'SERVIDOR BASE DE DATOS L3', 'code' => 'SBDL3'],
  96. ['coord' => '20R', 'element' => 'SERVIDOR DE APLICACIONES L3', 'code' => 'SEAL3'],
  97. ['coord' => '20W', 'element' => 'DISTRIBUCIÓN DE ENERGÍA L4', 'code' => 'DIEL4'],
  98. ['coord' => '21B', 'element' => 'TRANSFORMADOR TIPO SECO 500 KVA', 'code' => 'TTS5K'],
  99. ['coord' => '21F', 'element' => 'BAT', 'code' => 'BATXX'],
  100. ['coord' => '22F', 'element' => 'UPS', 'code' => 'UPSXX'],
  101. ['coord' => '22K', 'element' => 'TELECOM L4', 'code' => 'TELL4'],
  102. ['coord' => '22Ñ', 'element' => 'SERVIDOR BASE DE DATOS L4', 'code' => 'SBDL4'],
  103. ['coord' => '22R', 'element' => 'SERVIDOR DE APLICACIONES L4', 'code' => 'SEAL4'],
  104. ['coord' => '22W', 'element' => 'DISTRIBUCIÓN DE ENERGÍA L5', 'code' => 'DIEL5'],
  105. ['coord' => '23F', 'element' => 'BAT', 'code' => 'BATXX'],
  106. ['coord' => '23K', 'element' => 'TELECOM L5', 'code' => 'TELL5'],
  107. ['coord' => '23Ñ', 'element' => 'SERVIDOR BASE DE DATOS L5', 'code' => 'SBDL5'],
  108. ['coord' => '23R', 'element' => 'SERVIDOR DE APLICACIONES L5', 'code' => 'SEAL5'],
  109. ['coord' => '24B', 'element' => 'INTERRUPTOR ELECTROMAGNÉTICO 3x1600 AMP', 'code' => 'IE316'],
  110. ['coord' => '24K', 'element' => 'TELECOM L6', 'code' => 'TELL6'],
  111. ['coord' => '24Ñ', 'element' => 'SERVIDOR BASE DE DATOS L6', 'code' => 'SBDL6'],
  112. ['coord' => '24R', 'element' => 'SERVIDOR DE APLICACIONES L6', 'code' => 'SEAL6'],
  113. ['coord' => '24W', 'element' => 'DISTRIBUCIÓN DE ENERGÍA L6', 'code' => 'DIEL6'],
  114. ];
  115. }
  116. public function registerFamily(Request $request) {
  117. DB::enableQueryLog();
  118. $validator = Validator::make($request->all(), [
  119. 'id_user' => 'required|string',
  120. 'linea' => 'required|integer',
  121. 'family_code' => 'required|string',
  122. 'family_name' => 'required|string|max:50',
  123. ]);
  124. if($validator->fails()){
  125. return $this->responseController->makeResponse(
  126. true,
  127. "Se encontraron uno o más errores.",
  128. $this->responseController->makeErrors(
  129. $validator->errors()->messages()
  130. ),
  131. 401
  132. );
  133. }
  134. $form = $request->all();
  135. $idUser = $this->encryptionController->decrypt($form['id_user']);
  136. if(!$idUser){
  137. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  138. }
  139. $usr = DB::table('S002V01TUSUA')->where([
  140. ['USUA_NULI', '=', $form['linea']],
  141. ['USUA_IDUS', '=', $idUser]
  142. ])->first();
  143. if(is_null($usr)){
  144. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  145. }
  146. $familyCode = $this->encryptionController->decrypt($form['family_code']);
  147. if(!$familyCode){
  148. return $this->responseController->makeResponse(true, 'El código de la familia no fue encriptado correctamente.', [], 400);
  149. }
  150. $family = DB::table('S002V01TFAMI')->where([
  151. ['FAMI_NULI', '=', $form['linea']],
  152. ['FAMI_COFA', '=', $familyCode],
  153. ])->get()->all();
  154. if(count($family) > 0){
  155. return $this->responseController->makeResponse(true, 'El código de la familia ya se encuentra registrado.', [], 401);
  156. }
  157. $now = $this->functionsController->now();
  158. $nowStr = $now->toDateTimeString();
  159. DB::table('S002V01TFAMI')->insert([
  160. 'FAMI_NULI' => $form['linea'],
  161. 'FAMI_COFA' => $familyCode,
  162. 'FAMI_NOFA' => $form['family_name'],
  163. 'FAMI_USRE' => $idUser,
  164. 'FAMI_FERE' => $nowStr,
  165. ]);
  166. $actions = DB::getQueryLog();
  167. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  168. $idac = $this->functionsController->registerActivity(
  169. $form['linea'],
  170. 'S002V01M07GEEQ',
  171. 'S002V01F02DFSU',
  172. 'S002V01P02REFA',
  173. 'Registro',
  174. "El usuario $name (" . $usr->USUA_IDUS . ") registró la familia $form[family_name].",
  175. $idUser,
  176. $nowStr,
  177. );
  178. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  179. return $this->responseController->makeResponse(false, 'EXITO.');
  180. }
  181. public function getFamilies($idUser, $line) {
  182. DB::enableQueryLog();
  183. $idUser = $this->encryptionController->decrypt($idUser);
  184. if(!$idUser){
  185. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  186. }
  187. $usr = DB::table('S002V01TUSUA')->where([
  188. ['USUA_NULI', '=', $line],
  189. ['USUA_IDUS', '=', $idUser],
  190. ])->first();
  191. if(is_null($usr)){
  192. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  193. }
  194. $families = DB::table('S002V01TFAMI')->select([
  195. 'FAMI_COFA AS CODIGOFAMILIA',
  196. 'FAMI_NOFA AS NOMBREFAMILIA',
  197. 'FAMI_ICON AS ICONO',
  198. 'FAMI_ICPE AS ICONO_PERSONALIZADO',
  199. 'FAMI_ESTA AS ESTADO',
  200. 'FAMI_USRE AS USRREG',
  201. 'FAMI_FERE AS FECREG',
  202. 'FAMI_USMO AS USRMOD',
  203. 'FAMI_FEMO AS FECMOD'
  204. ])->where('FAMI_NULI', '=', $line)->get()->all();
  205. foreach($families as $key=>$val){
  206. $usrReg = DB::table('S002V01TUSUA')->where([
  207. ['USUA_NULI', '=', $line],
  208. ['USUA_IDUS', '=', $val->USRREG],
  209. ])->first();
  210. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  211. $val->USRREG = $nameReg . " (" . $val->USRREG . ")";
  212. if($val->USRMOD != null){
  213. $usrMod = DB::table('S002V01TUSUA')->where([
  214. ['USUA_NULI', '=', $line],
  215. ['USUA_IDUS', '=', $val->USRMOD],
  216. ])->first();
  217. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  218. $val->USRMOD = $nameMod . " (" . $val->USRMOD . ")";
  219. }
  220. $subfamilies = DB::table('S002V01TSUBF')->where([
  221. ['SUBF_NULI', '=', $line],
  222. ['SUBF_COFA', '=', $val->CODIGOFAMILIA],
  223. ])->get()->all();
  224. $val->SUBFAMILIAS = count($subfamilies);
  225. $val->CODIGOFAMILIA = $this->encryptionController->encrypt($val->CODIGOFAMILIA);
  226. $families[$key] = $val;
  227. }
  228. $now = $this->functionsController->now();
  229. $nowStr = $now->toDateTimeString();
  230. $actions = DB::getQueryLog();
  231. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  232. $idac = $this->functionsController->registerActivity(
  233. $line,
  234. 'S002V01M07GEEQ',
  235. 'S002V01F02DFSU',
  236. 'S002V01P01COFA',
  237. 'Consulta',
  238. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las familias registradas.",
  239. $idUser,
  240. $nowStr,
  241. );
  242. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  243. return $this->responseController->makeResponse(false, 'EXITO.', $families);
  244. }
  245. public function updateFamily(Request $request) {
  246. DB::enableQueryLog();
  247. $validator = Validator::make($request->all(), [
  248. 'id_user' => 'required|string',
  249. 'linea' => 'required|integer',
  250. 'family_code' => 'required|string',
  251. 'family_name' => 'required|string|max:50',
  252. ]);
  253. if($validator->fails()){
  254. return $this->responseController->makeResponse(
  255. true,
  256. "Se encontraron uno o más errores.",
  257. $this->responseController->makeErrors(
  258. $validator->errors()->messages()
  259. ),
  260. 401
  261. );
  262. }
  263. $form = $request->all();
  264. $idUser = $this->encryptionController->decrypt($form['id_user']);
  265. if(!$idUser){
  266. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  267. }
  268. $usr = DB::table('S002V01TUSUA')->where([
  269. ['USUA_NULI', '=', $form['linea']],
  270. ['USUA_IDUS', '=', $idUser]
  271. ])->first();
  272. if(is_null($usr)){
  273. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  274. }
  275. $familyCode = $this->encryptionController->decrypt($form['family_code']);
  276. if(!$familyCode){
  277. return $this->responseController->makeResponse(true, 'El código de la familia no fue encriptado correctamente.', [], 400);
  278. }
  279. $family = DB::table('S002V01TFAMI')->where([
  280. ['FAMI_NULI', '=', $form['linea']],
  281. ['FAMI_COFA', '=', $familyCode],
  282. ])->first();
  283. if(is_null($family)){
  284. return $this->responseController->makeResponse(true, 'La familia que desea actualizar no existe.', [], 404);
  285. }else if($family->FAMI_ESTA == 'Eliminado'){
  286. return $this->responseController->makeResponse(true, 'La familia que desea actualizar está eliminada.', [], 404);
  287. }
  288. $now = $this->functionsController->now();
  289. $nowStr = $now->toDateTimeString();
  290. DB::table('S002V01TFAMI')->where([
  291. ['FAMI_NULI', '=', $form['linea']],
  292. ['FAMI_COFA', '=', $familyCode],
  293. ])->update([
  294. 'FAMI_NOFA' => $form['family_name'],
  295. 'FAMI_USMO' => $idUser,
  296. 'FAMI_FEMO' => $nowStr,
  297. ]);
  298. $actions = DB::getQueryLog();
  299. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  300. $idac = $this->functionsController->registerActivity(
  301. $form['linea'],
  302. 'S002V01M07GEEQ',
  303. 'S002V01F02DFSU',
  304. 'S002V01P02REFA',
  305. 'Actualización',
  306. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la familia $familyCode.",
  307. $idUser,
  308. $nowStr,
  309. );
  310. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  311. return $this->responseController->makeResponse(false, 'EXITO.');
  312. }
  313. public function deleteFamily(Request $request) {
  314. DB::enableQueryLog();
  315. $validator = Validator::make($request->all(), [
  316. 'id_user' => 'required|string',
  317. 'linea' => 'required|integer',
  318. 'family_code' => 'required|string',
  319. ]);
  320. if($validator->fails()){
  321. return $this->responseController->makeResponse(
  322. true,
  323. "Se encontraron uno o más errores.",
  324. $this->responseController->makeErrors(
  325. $validator->errors()->messages()
  326. ),
  327. 401
  328. );
  329. }
  330. $form = $request->all();
  331. $idUser = $this->encryptionController->decrypt($form['id_user']);
  332. if(!$idUser){
  333. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  334. }
  335. $usr = DB::table('S002V01TUSUA')->where([
  336. ['USUA_NULI', '=', $form['linea']],
  337. ['USUA_IDUS', '=', $idUser]
  338. ])->first();
  339. if(is_null($usr)){
  340. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  341. }
  342. $familyCode = $this->encryptionController->decrypt($form['family_code']);
  343. if(!$familyCode){
  344. return $this->responseController->makeResponse(true, 'El código de la familia no fue encriptado correctamente.', [], 400);
  345. }
  346. $family = DB::table('S002V01TFAMI')->where([
  347. ['FAMI_NULI', '=', $form['linea']],
  348. ['FAMI_COFA', '=', $familyCode],
  349. ])->first();
  350. if(is_null($family)){
  351. return $this->responseController->makeResponse(true, 'La familia que desea eliminar no existe.', [], 404);
  352. }else if($family->FAMI_ESTA == 'Eliminado'){
  353. return $this->responseController->makeResponse(true, 'La familia que desea eliminar está eliminada.', [], 404);
  354. }
  355. $now = $this->functionsController->now();
  356. $nowStr = $now->toDateTimeString();
  357. DB::table('S002V01TFAMI')->where([
  358. ['FAMI_NULI', '=', $form['linea']],
  359. ['FAMI_COFA', '=', $familyCode],
  360. ])->update([
  361. 'FAMI_ESTA' => 'Eliminado',
  362. 'FAMI_USMO' => $idUser,
  363. 'FAMI_FEMO' => $nowStr,
  364. ]);
  365. $actions = DB::getQueryLog();
  366. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  367. $idac = $this->functionsController->registerActivity(
  368. $form['linea'],
  369. 'S002V01M07GEEQ',
  370. 'S002V01F02DFSU',
  371. 'S002V01P02REFA',
  372. 'Eliminación',
  373. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la familia $familyCode.",
  374. $idUser,
  375. $nowStr,
  376. );
  377. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  378. return $this->responseController->makeResponse(false, 'EXITO.');
  379. }
  380. public function registerSubfamily(Request $request) {
  381. DB::enableQueryLog();
  382. $validator = Validator::make($request->all(), [
  383. 'id_user' => 'required|string',
  384. 'linea' => 'required|integer',
  385. 'family_code' => 'required|string',
  386. 'subfamily_code' => 'required|string',
  387. 'subfamily_name' => 'required|string|max:50',
  388. ]);
  389. if($validator->fails()){
  390. return $this->responseController->makeResponse(
  391. true,
  392. "Se encontraron uno o más errores.",
  393. $this->responseController->makeErrors(
  394. $validator->errors()->messages()
  395. ),
  396. 401
  397. );
  398. }
  399. $form = $request->all();
  400. $idUser = $this->encryptionController->decrypt($form['id_user']);
  401. if(!$idUser){
  402. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  403. }
  404. $usr = DB::table('S002V01TUSUA')->where([
  405. ['USUA_NULI', '=', $form['linea']],
  406. ['USUA_IDUS', '=', $idUser]
  407. ])->first();
  408. if(is_null($usr)){
  409. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  410. }
  411. $familyCode = $this->encryptionController->decrypt($form['family_code']);
  412. if(!$familyCode){
  413. return $this->responseController->makeResponse(true, 'El código de la familia relacionada no fue encriptado correctamente.', [], 400);
  414. }
  415. $family = DB::table('S002V01TFAMI')->where([
  416. ['FAMI_NULI', '=', $form['linea']],
  417. ['FAMI_COFA', '=', $familyCode],
  418. ])->first();
  419. if(is_null($family)){
  420. return $this->responseController->makeResponse(true, 'La familia relacionada no existe.', [], 404);
  421. }else if($family->FAMI_ESTA == 'Eliminado'){
  422. return $this->responseController->makeResponse(true, 'La familia relacionada está eliminada.', [], 404);
  423. }
  424. $subfamilyCode = $this->encryptionController->decrypt($form['subfamily_code']);
  425. if(!$subfamilyCode){
  426. return $this->responseController->makeResponse(true, 'El código de la subfamilia no fue encriptado correctamente.', [], 400);
  427. }
  428. $subfamily = DB::table('S002V01TSUBF')->where([
  429. ['SUBF_NULI', '=', $form['linea']],
  430. ['SUBF_COFA', '=', $familyCode],
  431. ['SUBF_COSU', '=', $subfamilyCode],
  432. ])->get()->all();
  433. if(count($subfamily) > 0){
  434. return $this->responseController->makeResponse(true, 'El código de la subfamilia ya se encuentra registrado.', [], 401);
  435. }
  436. $now = $this->functionsController->now();
  437. $nowStr = $now->toDateTimeString();
  438. DB::table('S002V01TSUBF')->insert([
  439. 'SUBF_NULI' => $form['linea'],
  440. 'SUBF_COFA' => $familyCode,
  441. 'SUBF_COSU' => $subfamilyCode,
  442. 'SUBF_NOSU' => $form['subfamily_name'],
  443. 'SUBF_USRE' => $idUser,
  444. 'SUBF_FERE' => $nowStr,
  445. ]);
  446. $actions = DB::getQueryLog();
  447. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  448. $idac = $this->functionsController->registerActivity(
  449. $form['linea'],
  450. 'S002V01M07GEEQ',
  451. 'S002V01F02DFSU',
  452. 'S002V01P04RESU',
  453. 'Registro',
  454. "El usuario $name (" . $usr->USUA_IDUS . ") registró la subfamilia $form[subfamily_name].",
  455. $idUser,
  456. $nowStr,
  457. );
  458. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  459. return $this->responseController->makeResponse(false, 'EXITO.');
  460. }
  461. public function getSubfamilies($familyCode, $idUser, $line) {
  462. DB::enableQueryLog();
  463. $idUser = $this->encryptionController->decrypt($idUser);
  464. if(!$idUser){
  465. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  466. }
  467. $usr = DB::table('S002V01TUSUA')->where([
  468. ['USUA_NULI', '=', $line],
  469. ['USUA_IDUS', '=', $idUser],
  470. ])->first();
  471. if(is_null($usr)){
  472. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  473. }
  474. $familyCode = $this->encryptionController->decrypt($familyCode);
  475. if(!$familyCode){
  476. return $this->responseController->makeResponse(true, 'El código de la familia relacionada no fue encriptado correctamente.', [], 400);
  477. }
  478. $family = DB::table('S002V01TFAMI')->where([
  479. ['FAMI_NULI', '=', $line],
  480. ['FAMI_COFA', '=', $familyCode],
  481. ])->first();
  482. if(is_null($family)){
  483. return $this->responseController->makeResponse(true, 'La familia relacionada no existe.', [], 404);
  484. }else if($family->FAMI_ESTA == 'Eliminado'){
  485. return $this->responseController->makeResponse(true, 'La familia relacionada está eliminada.', [], 404);
  486. }
  487. $subfamilies = DB::table('S002V01TSUBF')->select([
  488. 'SUBF_COFA AS CODIGOFAMILIA',
  489. 'SUBF_COSU AS CODIGOSUBFAMILIA',
  490. 'SUBF_NOSU AS NOMBRESUBFAMILIA',
  491. 'SUBF_ICON AS ICONO',
  492. 'SUBF_ICPE AS ICONO_PERSONALIZADO',
  493. 'SUBF_ESTA AS ESTADO',
  494. 'SUBF_USRE AS USRREG',
  495. 'SUBF_FERE AS FECREG',
  496. 'SUBF_USMO AS USRMOD',
  497. 'SUBF_FEMO AS FECMOD'
  498. ])->where([
  499. ['SUBF_NULI', '=', $line],
  500. ['SUBF_COFA', '=', $familyCode],
  501. ])->get()->all();
  502. foreach($subfamilies as $key=>$val){
  503. $val->CODIGOFAMILIA = $this->encryptionController->encrypt($val->CODIGOFAMILIA);
  504. $val->CODIGOSUBFAMILIA = $this->encryptionController->encrypt($val->CODIGOSUBFAMILIA);
  505. $usrReg = DB::table('S002V01TUSUA')->where([
  506. ['USUA_NULI', '=', $line],
  507. ['USUA_IDUS', '=', $val->USRREG],
  508. ])->first();
  509. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  510. $val->USRREG = $nameReg . " (" . $val->USRREG . ")";
  511. if($val->USRMOD != null){
  512. $usrMod = DB::table('S002V01TUSUA')->where([
  513. ['USUA_NULI', '=', $line],
  514. ['USUA_IDUS', '=', $val->USRMOD],
  515. ])->first();
  516. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  517. $val->USRMOD = $nameMod . " (" . $val->USRMOD . ")";
  518. }
  519. $families[$key] = $val;
  520. }
  521. $now = $this->functionsController->now();
  522. $nowStr = $now->toDateTimeString();
  523. $actions = DB::getQueryLog();
  524. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  525. $idac = $this->functionsController->registerActivity(
  526. $line,
  527. 'S002V01M07GEEQ',
  528. 'S002V01F02DFSU',
  529. 'S002V01P03COSU',
  530. 'Consulta',
  531. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las subfamilias relacionadas a la familia $familyCode.",
  532. $idUser,
  533. $nowStr,
  534. );
  535. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  536. return $this->responseController->makeResponse(false, 'EXITO.', $subfamilies);
  537. }
  538. public function updateSubfamily(Request $request) {
  539. DB::enableQueryLog();
  540. $validator = Validator::make($request->all(), [
  541. 'id_user' => 'required|string',
  542. 'linea' => 'required|integer',
  543. 'family_code' => 'required|string',
  544. 'subfamily_code' => 'required|string',
  545. 'subfamily_name' => 'required|string|max:50',
  546. ]);
  547. if($validator->fails()){
  548. return $this->responseController->makeResponse(
  549. true,
  550. "Se encontraron uno o más errores.",
  551. $this->responseController->makeErrors(
  552. $validator->errors()->messages()
  553. ),
  554. 401
  555. );
  556. }
  557. $form = $request->all();
  558. $idUser = $this->encryptionController->decrypt($form['id_user']);
  559. if(!$idUser){
  560. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  561. }
  562. $usr = DB::table('S002V01TUSUA')->where([
  563. ['USUA_NULI', '=', $form['linea']],
  564. ['USUA_IDUS', '=', $idUser]
  565. ])->first();
  566. if(is_null($usr)){
  567. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  568. }
  569. $familyCode = $this->encryptionController->decrypt($form['family_code']);
  570. if(!$familyCode){
  571. return $this->responseController->makeResponse(true, 'El código de la familia relacionada no fue encriptado correctamente.', [], 400);
  572. }
  573. $family = DB::table('S002V01TFAMI')->where([
  574. ['FAMI_NULI', '=', $form['linea']],
  575. ['FAMI_COFA', '=', $familyCode],
  576. ])->first();
  577. if(is_null($family)){
  578. return $this->responseController->makeResponse(true, 'La familia relacionada no existe.', [], 404);
  579. }else if($family->FAMI_ESTA == 'Eliminado'){
  580. return $this->responseController->makeResponse(true, 'La familia relacionada está eliminada.', [], 404);
  581. }
  582. $subfamilyCode = $this->encryptionController->decrypt($form['subfamily_code']);
  583. if(!$subfamilyCode){
  584. return $this->responseController->makeResponse(true, 'El código de la subfamilia no fue encriptado correctamente.', [], 400);
  585. }
  586. $subfamily = DB::table('S002V01TSUBF')->where([
  587. ['SUBF_NULI', '=', $form['linea']],
  588. ['SUBF_COFA', '=', $familyCode],
  589. ['SUBF_COSU', '=', $subfamilyCode],
  590. ])->first();
  591. if(is_null($subfamily)){
  592. return $this->responseController->makeResponse(true, 'La subfamilia que desea actualizar no existe.', [], 404);
  593. }else if($subfamily->SUBF_ESTA == 'Eliminado'){
  594. return $this->responseController->makeResponse(true, 'La subfamilia que desea actualizar está eliminada.', [], 404);
  595. }
  596. $now = $this->functionsController->now();
  597. $nowStr = $now->toDateTimeString();
  598. DB::table('S002V01TSUBF')->where([
  599. 'SUBF_NULI' => $form['linea'],
  600. 'SUBF_COFA' => $familyCode,
  601. 'SUBF_COSU' => $subfamilyCode,
  602. ])->update([
  603. 'SUBF_NOSU' => $form['subfamily_name'],
  604. 'SUBF_USMO' => $idUser,
  605. 'SUBF_FEMO' => $nowStr,
  606. ]);
  607. $actions = DB::getQueryLog();
  608. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  609. $idac = $this->functionsController->registerActivity(
  610. $form['linea'],
  611. 'S002V01M07GEEQ',
  612. 'S002V01F02DFSU',
  613. 'S002V01P04RESU',
  614. 'Actualización',
  615. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la subfamilia $subfamilyCode de la familia $familyCode.",
  616. $idUser,
  617. $nowStr,
  618. );
  619. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  620. return $this->responseController->makeResponse(false, 'EXITO.');
  621. }
  622. public function deleteSubfamily(Request $request) {
  623. DB::enableQueryLog();
  624. $validator = Validator::make($request->all(), [
  625. 'id_user' => 'required|string',
  626. 'linea' => 'required|integer',
  627. 'family_code' => 'required|string',
  628. 'subfamily_code' => 'required|string',
  629. ]);
  630. if($validator->fails()){
  631. return $this->responseController->makeResponse(
  632. true,
  633. "Se encontraron uno o más errores.",
  634. $this->responseController->makeErrors(
  635. $validator->errors()->messages()
  636. ),
  637. 401
  638. );
  639. }
  640. $form = $request->all();
  641. $idUser = $this->encryptionController->decrypt($form['id_user']);
  642. if(!$idUser){
  643. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  644. }
  645. $usr = DB::table('S002V01TUSUA')->where([
  646. ['USUA_NULI', '=', $form['linea']],
  647. ['USUA_IDUS', '=', $idUser]
  648. ])->first();
  649. if(is_null($usr)){
  650. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  651. }
  652. $familyCode = $this->encryptionController->decrypt($form['family_code']);
  653. if(!$familyCode){
  654. return $this->responseController->makeResponse(true, 'El código de la familia relacionada no fue encriptado correctamente.', [], 400);
  655. }
  656. $family = DB::table('S002V01TFAMI')->where([
  657. ['FAMI_NULI', '=', $form['linea']],
  658. ['FAMI_COFA', '=', $familyCode],
  659. ])->first();
  660. if(is_null($family)){
  661. return $this->responseController->makeResponse(true, 'La familia relacionada no existe.', [], 404);
  662. }else if($family->FAMI_ESTA == 'Eliminado'){
  663. return $this->responseController->makeResponse(true, 'La familia relacionada está eliminada.', [], 404);
  664. }
  665. $subfamilyCode = $this->encryptionController->decrypt($form['subfamily_code']);
  666. if(!$subfamilyCode){
  667. return $this->responseController->makeResponse(true, 'El código de la subfamilia no fue encriptado correctamente.', [], 400);
  668. }
  669. $subfamily = DB::table('S002V01TSUBF')->where([
  670. ['SUBF_NULI', '=', $form['linea']],
  671. ['SUBF_COFA', '=', $familyCode],
  672. ['SUBF_COSU', '=', $subfamilyCode],
  673. ])->first();
  674. if(is_null($subfamily)){
  675. return $this->responseController->makeResponse(true, 'La subfamilia que desea eliminar no existe.', [], 404);
  676. }else if($subfamily->SUBF_ESTA == 'Eliminado'){
  677. return $this->responseController->makeResponse(true, 'La subfamilia que desea eliminar está eliminada.', [], 404);
  678. }
  679. $now = $this->functionsController->now();
  680. $nowStr = $now->toDateTimeString();
  681. DB::table('S002V01TSUBF')->where([
  682. 'SUBF_NULI' => $form['linea'],
  683. 'SUBF_COFA' => $familyCode,
  684. 'SUBF_COSU' => $subfamilyCode,
  685. ])->update([
  686. 'SUBF_ESTA' => 'Eliminado',
  687. 'SUBF_USMO' => $idUser,
  688. 'SUBF_FEMO' => $nowStr,
  689. ]);
  690. $actions = DB::getQueryLog();
  691. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  692. $idac = $this->functionsController->registerActivity(
  693. $form['linea'],
  694. 'S002V01M07GEEQ',
  695. 'S002V01F02DFSU',
  696. 'S002V01P04RESU',
  697. 'Eliminación',
  698. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la subfamilia $subfamilyCode de la familia $familyCode.",
  699. $idUser,
  700. $nowStr,
  701. );
  702. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  703. return $this->responseController->makeResponse(false, 'EXITO.');
  704. }
  705. public function getLocations($idUser, $line) {
  706. DB::enableQueryLog();
  707. $idUser = $this->encryptionController->decrypt($idUser);
  708. if(!$idUser){
  709. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  710. }
  711. $usr = DB::table('S002V01TUSUA')->where([
  712. ['USUA_NULI', '=', $line],
  713. ['USUA_IDUS', '=', $idUser],
  714. ])->first();
  715. if(is_null($usr)){
  716. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  717. }
  718. $ubic = $this->templatesUbic;
  719. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  720. $locationsEnc = file_get_contents($ubic . "locations.sam");
  721. $locationsDec = $this->encryptionController->decrypt($locationsEnc);
  722. $locationsArr = json_decode($locationsDec, true);
  723. $now = $this->functionsController->now();
  724. $nowStr = $now->toDateTimeString();
  725. $actions = DB::getQueryLog();
  726. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  727. $idac = $this->functionsController->registerActivity(
  728. $line,
  729. 'S002V01M07GEEQ',
  730. 'S002V01F01ADEQ',
  731. '-',
  732. 'Consulta',
  733. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el arreglo de ubicaciones de la línea.",
  734. $idUser,
  735. $nowStr,
  736. );
  737. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  738. return $this->responseController->makeResponse(false, 'EXITO.', $locationsArr);
  739. }
  740. public function getOccupationAreas($idUser, $line) {
  741. DB::enableQueryLog();
  742. $idUser = $this->encryptionController->decrypt($idUser);
  743. if(!$idUser){
  744. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  745. }
  746. $usr = DB::table('S002V01TUSUA')->where([
  747. ['USUA_NULI', '=', $line],
  748. ['USUA_IDUS', '=', $idUser],
  749. ])->first();
  750. if(is_null($usr)){
  751. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  752. }
  753. $ubic = $this->templatesUbic;
  754. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  755. $occupationAreasEnc = file_get_contents($ubic . "occupation-areas.sam");
  756. $occupationAreasDec = $this->encryptionController->decrypt($occupationAreasEnc);
  757. $occupationAreasArr = json_decode($occupationAreasDec, true);
  758. $now = $this->functionsController->now();
  759. $nowStr = $now->toDateTimeString();
  760. $actions = DB::getQueryLog();
  761. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  762. $idac = $this->functionsController->registerActivity(
  763. $line,
  764. 'S002V01M07GEEQ',
  765. 'S002V01F01ADEQ',
  766. '-',
  767. 'Consulta',
  768. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las áreas de ocupación.",
  769. $idUser,
  770. $nowStr,
  771. );
  772. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  773. return $this->responseController->makeResponse(false, 'EXITO.', $occupationAreasArr);
  774. }
  775. public function registerOccupation(Request $request) {
  776. DB::enableQueryLog();
  777. $validator = Validator::make($request->all(), [
  778. 'id_user' => 'required|string',
  779. 'linea' => 'required|integer',
  780. 'area' => 'required|string',
  781. 'description' => 'required|string|min:15|max:150',
  782. ]);
  783. if($validator->fails()){
  784. return $this->responseController->makeResponse(
  785. true,
  786. "Se encontraron uno o más errores.",
  787. $this->responseController->makeErrors(
  788. $validator->errors()->messages()
  789. ),
  790. 401
  791. );
  792. }
  793. $form = $request->all();
  794. $idUser = $this->encryptionController->decrypt($form['id_user']);
  795. if(!$idUser){
  796. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  797. }
  798. $usr = DB::table('S002V01TUSUA')->where([
  799. ['USUA_NULI', '=', $form['linea']],
  800. ['USUA_IDUS', '=', $idUser]
  801. ])->first();
  802. if(is_null($usr)){
  803. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  804. }
  805. $ubic = $this->templatesUbic;
  806. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  807. $occupationAreasEnc = file_get_contents($ubic . "occupation-areas.sam");
  808. $occupationAreasDec = $this->encryptionController->decrypt($occupationAreasEnc);
  809. $occupationAreasArr = json_decode($occupationAreasDec, true);
  810. $occupationAreasArrDec = [];
  811. foreach($occupationAreasArr as $area){
  812. $occupationAreasArrDec[] = [
  813. 'CODE' => $this->encryptionController->decrypt($area['CODE']),
  814. 'AREA' => $this->encryptionController->decrypt($area['AREA'])
  815. ];
  816. }
  817. $areaCode = $this->encryptionController->decrypt($form['area']);
  818. if(!$areaCode){
  819. return $this->responseController->makeResponse(true, 'El área de ocupación no fue encriptada correctamente.', [], 400);
  820. }
  821. $areaCodeExists = array_filter($occupationAreasArrDec, function($v, $k) use ($areaCode) {
  822. return $v['CODE'] == $areaCode;
  823. }, ARRAY_FILTER_USE_BOTH);
  824. if(count($areaCodeExists) < 1){
  825. return $this->responseController->makeResponse(true, 'El área de ocupación seleccionada no existe.', [], 400);
  826. }
  827. $areaName = end($areaCodeExists)['AREA'] . " ($areaCode)";
  828. $lastOccupationByArea = DB::table('S002V01TOCUP')->where([
  829. ['OCUP_NULI', '=', $form['linea']],
  830. ['OCUP_AREA', '=', $areaCode]
  831. ])->orderBy('OCUP_IDOC', 'desc')->first();
  832. $id = 0;
  833. if(is_null($lastOccupationByArea)){
  834. $id = 1;
  835. }else{
  836. $id = $lastOccupationByArea->OCUP_IDOC + 1;
  837. }
  838. if($id > 999){
  839. return $this->responseController->makeResponse(true, "El área $areaName llegó al límite de 999 elementos.", [], 401);
  840. }
  841. $now = $this->functionsController->now();
  842. $nowStr = $now->toDateTimeString();
  843. DB::table('S002V01TOCUP')->insert([
  844. 'OCUP_NULI' => $form['linea'],
  845. 'OCUP_AREA' => $areaCode,
  846. 'OCUP_IDOC' => $id,
  847. 'OCUP_DESC' => $form['description'],
  848. 'OCUP_USRE' => $idUser,
  849. 'OCUP_FERE' => $nowStr,
  850. ]);
  851. $actions = DB::getQueryLog();
  852. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  853. $idac = $this->functionsController->registerActivity(
  854. $form['linea'],
  855. 'S002V01M07GEEQ',
  856. 'S002V01F01ADEQ',
  857. '-',
  858. 'Registro',
  859. "El usuario $name (" . $usr->USUA_IDUS . ") registró una nueva ocupación para el área $areaName.",
  860. $idUser,
  861. $nowStr,
  862. );
  863. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  864. return $this->responseController->makeResponse(false, 'EXITO.');
  865. }
  866. public function getOccupations($idUser, $line) {
  867. DB::enableQueryLog();
  868. $idUser = $this->encryptionController->decrypt($idUser);
  869. if(!$idUser){
  870. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  871. }
  872. $usr = DB::table('S002V01TUSUA')->where([
  873. ['USUA_NULI', '=', $line],
  874. ['USUA_IDUS', '=', $idUser],
  875. ])->first();
  876. if(is_null($usr)){
  877. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  878. }
  879. $ubic = $this->templatesUbic;
  880. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  881. $occupationAreasEnc = file_get_contents($ubic . "occupation-areas.sam");
  882. $occupationAreasDec = $this->encryptionController->decrypt($occupationAreasEnc);
  883. $occupationAreasArr = json_decode($occupationAreasDec, true);
  884. $occupationAreasArrDec = [];
  885. foreach($occupationAreasArr as $area){
  886. $occupationAreasArrDec[] = [
  887. 'CODE' => $this->encryptionController->decrypt($area['CODE']),
  888. 'AREA' => $this->encryptionController->decrypt($area['AREA'])
  889. ];
  890. }
  891. $occupations = DB::table('S002V01TOCUP')->where('OCUP_NULI', '=', $line)->get()->all();
  892. $occupationsFn = [];
  893. foreach($occupations as $occupation){
  894. $areaInd = $occupation->OCUP_AREA;
  895. $areaStr = $areaInd < 10 ? "0$areaInd" : "$areaInd";
  896. $area = array_filter($occupationAreasArrDec, function($v, $k) use ($areaStr) {
  897. return $v['CODE'] == $areaStr;
  898. }, ARRAY_FILTER_USE_BOTH);
  899. $areaName = end($area)['AREA'] . " (" . end($area)['CODE'] . ")";
  900. $occupationInd = "" . $occupation->OCUP_IDOC . "";
  901. $occupationStr = "";
  902. for($i = strlen($occupationInd); $i < 3; $i++){
  903. $occupationStr .= '0';
  904. }
  905. $usrReg = DB::table('S002V01TUSUA')->where([
  906. ['USUA_NULI', '=', $line],
  907. ['USUA_IDUS', '=', $occupation->OCUP_USRE],
  908. ])->first();
  909. $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $occupation->OCUP_USRE . ")";
  910. $usrModName = null;
  911. if($occupation->OCUP_USMO != null){
  912. $usrMod = DB::table('S002V01TUSUA')->where([
  913. ['USUA_NULI', '=', $line],
  914. ['USUA_IDUS', '=', $occupation->OCUP_USMO],
  915. ])->first();
  916. $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA) . " (" . $occupation->OCUP_USMO . ")";
  917. }
  918. $occupationStr = $areaStr . $occupationStr . $occupationInd;
  919. $occupationsFn[] = [
  920. "NOMBREAREA" => $areaName,
  921. "OCUPACION" => $occupationStr,
  922. "DESCRIPCION" => $occupation->OCUP_DESC,
  923. "ESTADO" => $occupation->OCUP_ESTA,
  924. "USRREG" => $usrRegName,
  925. "FECREG" => $occupation->OCUP_FERE,
  926. "USRMOD" => $usrModName,
  927. "FECMOD" => $occupation->OCUP_FEMO,
  928. ];
  929. }
  930. $now = $this->functionsController->now();
  931. $nowStr = $now->toDateTimeString();
  932. $actions = DB::getQueryLog();
  933. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  934. $idac = $this->functionsController->registerActivity(
  935. $line,
  936. 'S002V01M07GEEQ',
  937. 'S002V01F01ADEQ',
  938. '-',
  939. 'Consulta',
  940. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las ocupaciones registradas.",
  941. $idUser,
  942. $nowStr,
  943. );
  944. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  945. return $this->responseController->makeResponse(false, 'EXITO.', $occupationsFn);
  946. }
  947. public function updateOccupation(Request $request) {
  948. DB::enableQueryLog();
  949. $validator = Validator::make($request->all(), [
  950. 'id_user' => 'required|string',
  951. 'linea' => 'required|integer',
  952. 'area' => 'required|string',
  953. 'occupation' => 'required|string',
  954. 'description' => 'required|string|min:15|max:150',
  955. ]);
  956. if($validator->fails()){
  957. return $this->responseController->makeResponse(
  958. true,
  959. "Se encontraron uno o más errores.",
  960. $this->responseController->makeErrors(
  961. $validator->errors()->messages()
  962. ),
  963. 401
  964. );
  965. }
  966. $form = $request->all();
  967. $idUser = $this->encryptionController->decrypt($form['id_user']);
  968. if(!$idUser){
  969. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  970. }
  971. $usr = DB::table('S002V01TUSUA')->where([
  972. ['USUA_NULI', '=', $form['linea']],
  973. ['USUA_IDUS', '=', $idUser]
  974. ])->first();
  975. if(is_null($usr)){
  976. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  977. }
  978. $ubic = $this->templatesUbic;
  979. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  980. $occupationAreasEnc = file_get_contents($ubic . "occupation-areas.sam");
  981. $occupationAreasDec = $this->encryptionController->decrypt($occupationAreasEnc);
  982. $occupationAreasArr = json_decode($occupationAreasDec, true);
  983. $occupationAreasArrDec = [];
  984. foreach($occupationAreasArr as $area){
  985. $occupationAreasArrDec[] = [
  986. 'CODE' => $this->encryptionController->decrypt($area['CODE']),
  987. 'AREA' => $this->encryptionController->decrypt($area['AREA'])
  988. ];
  989. }
  990. $areaCode = $this->encryptionController->decrypt($form['area']);
  991. if(!$areaCode){
  992. return $this->responseController->makeResponse(true, 'El área de ocupación no fue encriptada correctamente.', [], 400);
  993. }
  994. $areaCodeExists = array_filter($occupationAreasArrDec, function($v, $k) use ($areaCode) {
  995. return $v['CODE'] == $areaCode;
  996. }, ARRAY_FILTER_USE_BOTH);
  997. if(count($areaCodeExists) < 1){
  998. return $this->responseController->makeResponse(true, 'El área de ocupación relacionada no existe.', [], 400);
  999. }
  1000. $occupation = $this->encryptionController->decrypt($form['occupation']);
  1001. if(!$occupation){
  1002. return $this->responseController->makeResponse(true, 'La ocupación no fue encriptada correctamente.', [], 400);
  1003. }
  1004. $occupationID = substr($occupation, 2);
  1005. $occupationObj = DB::table('S002V01TOCUP')->where([
  1006. ['OCUP_NULI', '=', $form['linea']],
  1007. ['OCUP_AREA', '=', $areaCode],
  1008. ['OCUP_IDOC', '=', $occupationID],
  1009. ])->first();
  1010. if(is_null($occupationObj)){
  1011. return $this->responseController->makeResponse(true, 'La ocupación que desea actualizar no existe.', [], 404);
  1012. }
  1013. $now = $this->functionsController->now();
  1014. $nowStr = $now->toDateTimeString();
  1015. DB::table('S002V01TOCUP')->where([
  1016. ['OCUP_NULI', '=', $form['linea']],
  1017. ['OCUP_AREA', '=', $areaCode],
  1018. ['OCUP_IDOC', '=', $occupationID],
  1019. ])->update([
  1020. 'OCUP_DESC' => $form['description'],
  1021. 'OCUP_USMO' => $idUser,
  1022. 'OCUP_FEMO' => $nowStr,
  1023. ]);
  1024. $actions = DB::getQueryLog();
  1025. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1026. $idac = $this->functionsController->registerActivity(
  1027. $form['linea'],
  1028. 'S002V01M07GEEQ',
  1029. 'S002V01F01ADEQ',
  1030. '-',
  1031. 'Actualización',
  1032. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la ocupación $occupation.",
  1033. $idUser,
  1034. $nowStr,
  1035. );
  1036. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1037. return $this->responseController->makeResponse(false, 'EXITO.');
  1038. }
  1039. public function deleteOccupation(Request $request) {
  1040. DB::enableQueryLog();
  1041. $validator = Validator::make($request->all(), [
  1042. 'id_user' => 'required|string',
  1043. 'linea' => 'required|integer',
  1044. 'area' => 'required|string',
  1045. 'occupation' => 'required|string',
  1046. ]);
  1047. if($validator->fails()){
  1048. return $this->responseController->makeResponse(
  1049. true,
  1050. "Se encontraron uno o más errores.",
  1051. $this->responseController->makeErrors(
  1052. $validator->errors()->messages()
  1053. ),
  1054. 401
  1055. );
  1056. }
  1057. $form = $request->all();
  1058. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1059. if(!$idUser){
  1060. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1061. }
  1062. $usr = DB::table('S002V01TUSUA')->where([
  1063. ['USUA_NULI', '=', $form['linea']],
  1064. ['USUA_IDUS', '=', $idUser]
  1065. ])->first();
  1066. if(is_null($usr)){
  1067. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1068. }
  1069. $ubic = $this->templatesUbic;
  1070. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  1071. $occupationAreasEnc = file_get_contents($ubic . "occupation-areas.sam");
  1072. $occupationAreasDec = $this->encryptionController->decrypt($occupationAreasEnc);
  1073. $occupationAreasArr = json_decode($occupationAreasDec, true);
  1074. $occupationAreasArrDec = [];
  1075. foreach($occupationAreasArr as $area){
  1076. $occupationAreasArrDec[] = [
  1077. 'CODE' => $this->encryptionController->decrypt($area['CODE']),
  1078. 'AREA' => $this->encryptionController->decrypt($area['AREA'])
  1079. ];
  1080. }
  1081. $areaCode = $this->encryptionController->decrypt($form['area']);
  1082. if(!$areaCode){
  1083. return $this->responseController->makeResponse(true, 'El área de ocupación no fue encriptada correctamente.', [], 400);
  1084. }
  1085. $areaCodeExists = array_filter($occupationAreasArrDec, function($v, $k) use ($areaCode) {
  1086. return $v['CODE'] == $areaCode;
  1087. }, ARRAY_FILTER_USE_BOTH);
  1088. if(count($areaCodeExists) < 1){
  1089. return $this->responseController->makeResponse(true, 'El área de ocupación relacionada no existe.', [], 400);
  1090. }
  1091. $occupation = $this->encryptionController->decrypt($form['occupation']);
  1092. if(!$occupation){
  1093. return $this->responseController->makeResponse(true, 'La ocupación no fue encriptada correctamente.', [], 400);
  1094. }
  1095. $occupationID = substr($occupation, 2);
  1096. $occupationObj = DB::table('S002V01TOCUP')->where([
  1097. ['OCUP_NULI', '=', $form['linea']],
  1098. ['OCUP_AREA', '=', $areaCode],
  1099. ['OCUP_IDOC', '=', $occupationID],
  1100. ])->first();
  1101. if(is_null($occupationObj)){
  1102. return $this->responseController->makeResponse(true, 'La ocupación que desea eliminar no existe.', [], 404);
  1103. }
  1104. $now = $this->functionsController->now();
  1105. $nowStr = $now->toDateTimeString();
  1106. DB::table('S002V01TOCUP')->where([
  1107. ['OCUP_NULI', '=', $form['linea']],
  1108. ['OCUP_AREA', '=', $areaCode],
  1109. ['OCUP_IDOC', '=', $occupationID],
  1110. ])->update([
  1111. 'OCUP_ESTA' => 'Eliminado',
  1112. 'OCUP_USMO' => $idUser,
  1113. 'OCUP_FEMO' => $nowStr,
  1114. ]);
  1115. $actions = DB::getQueryLog();
  1116. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1117. $idac = $this->functionsController->registerActivity(
  1118. $form['linea'],
  1119. 'S002V01M07GEEQ',
  1120. 'S002V01F01ADEQ',
  1121. '-',
  1122. 'Eliminación',
  1123. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la ocupación $occupation.",
  1124. $idUser,
  1125. $nowStr,
  1126. );
  1127. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1128. return $this->responseController->makeResponse(false, 'EXITO.');
  1129. }
  1130. public function saveEquipmentPreCodified(Request $request) {
  1131. DB::enableQueryLog();
  1132. $validator = Validator::make($request->all(), [
  1133. 'id_user' => 'required|string',
  1134. 'linea' => 'required|integer',
  1135. 'hierarchy' => 'required|string|in:Padre,Hijo',
  1136. 'parent_equipment' => 'required_if:hierarchy,=,Hijo|string',
  1137. 'code_type' => 'required|integer|between:1,6',
  1138. 'origin_location' => 'required|string',
  1139. 'origin_level' => 'required|string',
  1140. 'origin_occupation' => 'required|string',
  1141. 'origin_element' => 'required_unless:code_type,4|string',
  1142. 'origin_element_enc' => 'required_if:code_type,=,4|string',
  1143. 'family' => 'required|string',
  1144. 'subfamily' => 'required|string',
  1145. 'status' => 'required|string',
  1146. 'equipment_type' => 'required|string|max:150',
  1147. 'equipment_model' => 'required|string|max:75',
  1148. 'images' => 'required|json',
  1149. 'documents' => 'required|json',
  1150. 'acquisition_date' => 'required|date',
  1151. 'warranty_start_date' => 'required|date',
  1152. 'warranty_end_date' => 'required|date',
  1153. 'equipment_provider' => 'required|string',
  1154. 'serial_number' => 'required|string|max:150',
  1155. 'has_software' => 'required|string|in:Si,No',
  1156. 'software_name' => 'required_if:has_software,=,Si|string|max:150',
  1157. 'software_version' => 'required_if:has_software,=,Si|string|max:75',
  1158. 'pre_generated_code' => 'required|string',
  1159. 'pcc_intersection' => 'required_if:code_type,=,2|string|max:5',
  1160. 'pcc_position' => 'required_if:code_type,=,2|string|max:2',
  1161. 'origin_kilometer' => 'required_if:code_type,=,3|numeric',
  1162. 'origin_code_type' => 'required_if:code_type,=,6|numeric|between:1,5',
  1163. 'origin_kilometer' => 'required_if:origin_code_type,=,3|numeric',
  1164. 'train_area' => 'required_if:code_type,=,5|string',
  1165. 'destiny_location' => 'required_if:code_type,=,3|string',
  1166. 'destiny_level' => 'required_if:code_type,=,3|string',
  1167. 'destiny_occupation' => 'required_if:code_type,=,3|string',
  1168. 'destiny_element' => 'required_if:code_type,=,3|string|max:150',
  1169. 'destiny_element' => 'required_if:code_type,=,6|string',
  1170. 'destiny_element_enc' => 'required_if:code_type,=,4|string',
  1171. 'destiny_kilometer' => 'required_if:code_type,=,3|string',
  1172. 'destiny_location' => 'required_if:code_type,=,4|string',
  1173. 'destiny_level' => 'required_if:code_type,=,4|string',
  1174. 'destiny_occupation' => 'required_if:code_type,=,4|string',
  1175. 'destiny_code_type' => 'required_if:code_type,=,6|numeric|between:1,5',
  1176. 'destiny_kilometer' => 'required_if:destiny_code_type,=,3|numeric',
  1177. ]);
  1178. if($validator->fails()){
  1179. return $this->responseController->makeResponse(
  1180. true,
  1181. "Se encontraron uno o más errores.",
  1182. $this->responseController->makeErrors(
  1183. $validator->errors()->messages()
  1184. ),
  1185. 401
  1186. );
  1187. }
  1188. $form = $request->all();
  1189. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1190. if(!$idUser){
  1191. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1192. }
  1193. $usr = DB::table('S002V01TUSUA')->where([
  1194. ['USUA_NULI', '=', $form['linea']],
  1195. ['USUA_IDUS', '=', $idUser]
  1196. ])->first();
  1197. if(is_null($usr)){
  1198. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1199. }
  1200. $eqpa = null;
  1201. if($form['hierarchy'] == 'Hijo'){
  1202. $eqpa = $this->encryptionController->decrypt($form['parent_equipment']);
  1203. if(!$eqpa){
  1204. return $this->responseController->makeResponse(true, 'El ID del equipamiento padre no fue encriptado correctamente.', [], 400);
  1205. }
  1206. $parentEquipment = DB::table('S002V01TEQUI')->where([
  1207. ['EQUI_NULI', '=', $form['linea']],
  1208. ['EQUI_COEQ', '=', $eqpa],
  1209. ])->first();
  1210. if(is_null($parentEquipment)){
  1211. return $this->responseController->makeResponse(true, 'El equipamiento padre no existe.', [], 404);
  1212. }
  1213. }
  1214. $ubic = $this->templatesUbic;
  1215. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  1216. $locationsEnc = file_get_contents($ubic . "locations.sam");
  1217. $locationsDec = $this->encryptionController->decrypt($locationsEnc);
  1218. $locationsArr = json_decode($locationsDec, true);
  1219. $locationsArrDec = [];
  1220. foreach($locationsArr as $location){
  1221. $locationStr = $this->encryptionController->decrypt($location['LOCATION']);
  1222. $code = $this->encryptionController->decrypt($location['CODE']);
  1223. $locationsArrDec[] = [
  1224. 'LOCATION' => $locationStr,
  1225. 'CODE' => $code
  1226. ];
  1227. }
  1228. $originLocation = $this->encryptionController->decrypt($form['origin_location']);
  1229. if(!$originLocation){
  1230. return $this->responseController->makeResponse(true, 'La ubicación de origen no fue encriptada correctamente.', [], 400);
  1231. }
  1232. $originLocationFilt = array_filter($locationsArrDec, function($v, $k) use ($originLocation) {
  1233. return $v['CODE'] == $originLocation;
  1234. }, ARRAY_FILTER_USE_BOTH);
  1235. if(count($originLocationFilt) < 1){
  1236. return $this->responseController->makeResponse(true, 'La ubicación de origen no se encuentra registrada en el sistema.', [], 404);
  1237. }
  1238. $destinyLocation = null;
  1239. if(isset($form['destiny_location'])){
  1240. $destinyLocation = $this->encryptionController->decrypt($form['destiny_location']);
  1241. if(!$destinyLocation){
  1242. return $this->responseController->makeResponse(true, 'La ubicación de destino no fue encriptada correctamente.', [], 400);
  1243. }
  1244. $destinyLocationFilt = array_filter($locationsArrDec, function($v, $k) use ($destinyLocation) {
  1245. return $v['CODE'] == $destinyLocation;
  1246. }, ARRAY_FILTER_USE_BOTH);
  1247. if(count($destinyLocationFilt) < 1){
  1248. return $this->responseController->makeResponse(true, 'La ubicación de destino no se encuentra registrada en el sistema.', [], 404);
  1249. }
  1250. }
  1251. $originLevel = $this->encryptionController->decrypt($form['origin_level']);
  1252. if(!$originLevel){
  1253. return $this->responseController->makeResponse(true, 'El nivel de origen no fue encriptado correctamente.', [], 400);
  1254. }
  1255. $supportedLevels = [];
  1256. for($i = 5; $i > 0; $i--){
  1257. $supportedLevels[] = "S0$i";
  1258. }
  1259. for($i = 0; $i <= 15; $i++){
  1260. $tag = $i < 10 ? "P0$i" : "P$i";
  1261. $supportedLevels[] = $tag;
  1262. }
  1263. if(!in_array($originLevel, $supportedLevels)){
  1264. return $this->responseController->makeResponse(true, 'El nivel de origen seleccionado es inválido.', [], 400);
  1265. }
  1266. $destinyLevel = null;
  1267. if(isset($form['destiny_level'])){
  1268. $destinyLevel = $this->encryptionController->decrypt($form['destiny_level']);
  1269. if(!in_array($destinyLevel, $supportedLevels)){
  1270. return $this->responseController->makeResponse(true, 'El nivel de destino seleccionado es inválido.', [], 400);
  1271. }
  1272. }
  1273. $originOccupationStr = $this->encryptionController->decrypt($form['origin_occupation']);
  1274. if(!$originOccupationStr){
  1275. return $this->responseController->makeResponse(true, 'La ocupación de origen no fue encriptada correctamente.', [], 400);
  1276. }
  1277. if($form['code_type'] == '5'){
  1278. $trainOccupationsEnc = file_get_contents($ubic . "train-occupations.sam");
  1279. $trainOccupationsDec = $this->encryptionController->decrypt($trainOccupationsEnc);
  1280. $trainOccupationsArr = json_decode($trainOccupationsDec, true);
  1281. foreach($trainOccupationsArr as $k0=>$v0){
  1282. $trainOccupation = [];
  1283. foreach($v0 as $k1=>$v1){
  1284. $valDec = $this->encryptionController->decrypt($v1);
  1285. $trainOccupation[$k1] = $valDec;
  1286. }
  1287. $trainOccupationsArr[$k0] = $trainOccupation;
  1288. }
  1289. $occupationFilt = array_filter($trainOccupationsArr, function($v, $k) use ($originOccupationStr) {
  1290. return $v['CODE'] == $originOccupationStr;
  1291. }, ARRAY_FILTER_USE_BOTH);
  1292. if(count($occupationFilt) < 1){
  1293. return $this->responseController->makeResponse(true, 'La ocupación de origen seleccionada no existe.', [], 404);
  1294. }
  1295. }else{
  1296. $originOccupationArea = substr($originOccupationStr, 0, 2);
  1297. $originOccupationID = substr($originOccupationStr, 2);
  1298. $originOccupation = DB::table('S002V01TOCUP')->where([
  1299. ['OCUP_NULI', '=', $form['linea']],
  1300. ['OCUP_AREA', '=', $originOccupationArea],
  1301. ['OCUP_IDOC', '=', $originOccupationID]
  1302. ])->first();
  1303. if(is_null($originOccupation)){
  1304. return $this->responseController->makeResponse(true, 'La ocupación de origen seleccionada no existe.', [], 404);
  1305. }
  1306. }
  1307. $destinyOccupationStr = null;
  1308. if(isset($form['destiny_occupation'])){
  1309. $destinyOccupationStr = $this->encryptionController->decrypt($form['destiny_occupation']);
  1310. if(!$destinyOccupationStr){
  1311. return $this->responseController->makeResponse(true, 'La ocupación de destino no fue encriptada correctamente.', [], 400);
  1312. }
  1313. $destinyOccupationArea = substr($destinyOccupationStr, 0, 2);
  1314. $destinyOccupationID = substr($destinyOccupationStr, 2);
  1315. $destinyOccupation = DB::table('S002V01TOCUP')->where([
  1316. ['OCUP_NULI', '=', $form['linea']],
  1317. ['OCUP_AREA', '=', $destinyOccupationArea],
  1318. ['OCUP_IDOC', '=', $destinyOccupationID]
  1319. ])->first();
  1320. if(is_null($destinyOccupation)){
  1321. return $this->responseController->makeResponse(true, 'La ocupación de destino seleccionada no existe.', [], 404);
  1322. }
  1323. }
  1324. $familyCode = $this->encryptionController->decrypt($form['family']);
  1325. if(!$familyCode){
  1326. return $this->responseController->makeResponse(true, 'La familia del equipamiento no fue encriptada correctamente.', [], 400);
  1327. }
  1328. $family = DB::table('S002V01TFAMI')->where([
  1329. ['FAMI_NULI', '=', $form['linea']],
  1330. ['FAMI_COFA', '=', $familyCode]
  1331. ])->first();
  1332. if(is_null($family)){
  1333. return $this->responseController->makeResponse(true, 'La familia seleccionada no existe.', [], 404);
  1334. }
  1335. $subfamilyCode = $this->encryptionController->decrypt($form['subfamily']);
  1336. if(!$subfamilyCode){
  1337. return $this->responseController->makeResponse(true, 'La subfamilia del equipamiento no fue encriptada correctamente.', [], 400);
  1338. }
  1339. $subfamily = DB::table('S002V01TSUBF')->where([
  1340. ['SUBF_NULI', '=', $form['linea']],
  1341. ['SUBF_COFA', '=', $familyCode],
  1342. ['SUBF_COSU', '=', $subfamilyCode]
  1343. ])->first();
  1344. if(is_null($subfamily)){
  1345. return $this->responseController->makeResponse(true, 'La subfamilia seleccionada no existe.', [], 404);
  1346. }
  1347. $validStatus = ["A", "S", "T", "I", "R", "D"];
  1348. $status = $this->encryptionController->decrypt($form['status']);
  1349. if(!$status){
  1350. return $this->responseController->makeResponse(true, 'La estado del equipamiento no fue encriptado correctamente.', [], 400);
  1351. }else if(!in_array($status, $validStatus)){
  1352. return $this->responseController->makeResponse(true, 'El estado seleccionado para el equipamiento es inválido.', [], 400);
  1353. }
  1354. $imagesArr = json_decode($form['images'], true);
  1355. if(count($imagesArr) < 1){
  1356. return $this->responseController->makeResponse(true, 'El arreglo de la galería de imágenes está vacío.', [], 400);
  1357. }
  1358. $imagesGallery = [];
  1359. foreach($imagesArr as $imageFile){
  1360. if(!array_key_exists('type', $imageFile)){
  1361. return $this->responseController->makeResponse(true, 'El arreglo de la galería de imágenes tiene un formato inválido.', [], 400);
  1362. }else if($imageFile['type'] == 'Nuevo'){
  1363. $tempFileID = $this->encryptionController->decrypt($imageFile['id']);
  1364. $tempFile = DB::table('S002V01TARTE')->where([
  1365. ['ARTE_IDAR', '=', $tempFileID],
  1366. ['ARTE_NULI', '=', $form['linea']]
  1367. ])->first();
  1368. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GEEQ', 'FO', $tempFile, $idUser);
  1369. if(!$finalFile[0]){
  1370. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  1371. }
  1372. $imagesGallery[] = $finalFile[1];
  1373. }else{
  1374. $fileID = $this->encryptionController->decrypt($imageFile['id']);
  1375. $imagesGallery[] = $fileID;
  1376. }
  1377. }
  1378. $imagesGalleryStr = json_encode($imagesGallery);
  1379. $documentsArr = json_decode($form['documents'], true);
  1380. if(count($documentsArr) < 1){
  1381. return $this->responseController->makeResponse(true, 'El arreglo de documentos relacionados está vacío.', [], 400);
  1382. }
  1383. $documents = [];
  1384. foreach($documentsArr as $documentFile){
  1385. if(!array_key_exists('type', $documentFile)){
  1386. return $this->responseController->makeResponse(true, 'El arreglo de documentos asociados tiene un formato inválido.', [], 400);
  1387. }else if($documentFile['type'] == 'Nuevo'){
  1388. $tempFileID = $this->encryptionController->decrypt($documentFile['id']);
  1389. $tempFile = DB::table('S002V01TARTE')->where([
  1390. ['ARTE_IDAR', '=', $tempFileID],
  1391. ['ARTE_NULI', '=', $form['linea']]
  1392. ])->first();
  1393. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GEEQ', 'IN', $tempFile, $idUser);
  1394. if(!$finalFile[0]){
  1395. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  1396. }
  1397. $documents[] = $finalFile[1];
  1398. }else{
  1399. $fileID = $this->encryptionController->decrypt($documentFile['id']);
  1400. $documents[] = $fileID;
  1401. }
  1402. }
  1403. $documentsStr = json_encode($documents);
  1404. $acquisitionDate = new Carbon($form['acquisition_date']);
  1405. $warrantyStartDate = new Carbon($form['warranty_start_date']);
  1406. $warrantyEndDate = new Carbon($form['warranty_end_date']);
  1407. if($warrantyStartDate->lt($acquisitionDate)){
  1408. return $this->responseController->makeResponse(true, 'La fecha de inicio de la grantía no puede ser menor a la fecha de adquisición.', [], 400);
  1409. }else if($warrantyEndDate->lte($acquisitionDate)){
  1410. return $this->responseController->makeResponse(true, 'La fecha de término de la grantía no puede ser menor o igual a la fecha de inicio de la garantía.', [], 400);
  1411. }
  1412. $providerID = $this->encryptionController->decrypt($form['equipment_provider']);
  1413. if(!$providerID){
  1414. return $this->responseController->makeResponse(true, 'El proveedor del equipamiento no fue encriptado correctamente.', [], 400);
  1415. }
  1416. $provider = DB::table('S002V01TPROV')->where([
  1417. ['PROV_NUPR', '=', $providerID],
  1418. ['PROV_NULI', '=', $form['linea']]
  1419. ])->first();
  1420. if(is_null($provider)){
  1421. return $this->responseController->makeResponse(true, 'La proveedor seleccionada no existe.', [], 404);
  1422. }
  1423. $serialNumer = $this->encryptionController->decrypt($form['serial_number']);
  1424. if(!$serialNumer){
  1425. return $this->responseController->makeResponse(true, 'El número de serie del equipamiento no fue encriptado correctamente.', [], 400);
  1426. }
  1427. $serialNmberDB = DB::table('S002V01TEQUI')->where([
  1428. ['EQUI_NULI', '=', $form['linea']],
  1429. ['EQUI_NUSE', '=', $serialNumer]
  1430. ])->first();
  1431. if(!is_null($serialNmberDB)){
  1432. $serialNumberStr = $serialNmberDB->EQUI_COEQ;
  1433. return $this->responseController->makeResponse(true, "El número de serie enviado ya se encuentra relacionado al equipamiento $serialNumberStr.", [], 401);
  1434. }
  1435. $preCode = $this->encryptionController->decrypt($form['pre_generated_code']);
  1436. if(!$preCode){
  1437. return $this->responseController->makeResponse(true, 'El código pre generado no fue encriptado correctamente.', [], 400);
  1438. }
  1439. $elde = null;
  1440. $destinyElementSecuence = null;
  1441. $originElement = '';
  1442. $originElementSecuence = null;
  1443. $trainArea = null;
  1444. if($form['code_type'] == '4'){
  1445. $originElementDec = $this->encryptionController->decrypt($form['origin_element_enc']);
  1446. if(!$originElementDec){
  1447. return $this->responseController->makeResponse(true, 'El elemento de origen no fue encriptado correctamente.', [], 400);
  1448. }
  1449. $originElementObj = DB::table('S002V01TEQUI')->where([
  1450. ['EQUI_NULI', '=', $form['linea']],
  1451. ['EQUI_COEQ', '=', $originElementDec]
  1452. ])->first();
  1453. if(is_null($originElementObj)){
  1454. return $this->responseController->makeResponse(true, "El elemento de origen no existe.", [], 404);
  1455. }
  1456. $originElement = $originElementObj->EQUI_ELOR;
  1457. $originElementSecuence = $originElementObj->EQUI_IDEQ;
  1458. $destinyElementDec = $this->encryptionController->decrypt($form['destiny_element_enc']);
  1459. if(!$destinyElementDec){
  1460. return $this->responseController->makeResponse(true, 'El elemento de destino no fue encriptado correctamente.', [], 400);
  1461. }
  1462. $destinyElementObj = DB::table('S002V01TEQUI')->where([
  1463. ['EQUI_NULI', '=', $form['linea']],
  1464. ['EQUI_COEQ', '=', $destinyElementDec]
  1465. ])->first();
  1466. if(is_null($destinyElementObj)){
  1467. return $this->responseController->makeResponse(true, "El elemento de destino no existe.", [], 404);
  1468. }
  1469. $elde = $destinyElementObj->EQUI_ELOR;
  1470. $destinyElementSecuence = $destinyElementObj->EQUI_IDEQ;
  1471. }else if($form['code_type'] == '5'){
  1472. $originElement = $this->encryptionController->decrypt($form['origin_element']);
  1473. if(!$originElement){
  1474. return $this->responseController->makeResponse(true, 'El elemento de origen no fue encriptado correctamente.', [], 400);
  1475. }
  1476. $trainElementsEnc = file_get_contents($ubic . "train-elements.sam");
  1477. $trainElementsDec = $this->encryptionController->decrypt($trainElementsEnc);
  1478. $trainElementsArr = json_decode($trainElementsDec, true);
  1479. foreach($trainElementsArr as $k0=>$v0){
  1480. $trainElement = [];
  1481. foreach($v0 as $k1=>$v1){
  1482. $valDec = $this->encryptionController->decrypt($v1);
  1483. $trainElement[$k1] = $valDec;
  1484. }
  1485. $trainElementsArr[$k0] = $trainElement;
  1486. }
  1487. $trainElementFilt = array_filter($trainElementsArr, function($v, $k) use ($originElement) {
  1488. return $v['CODE'] == $originElement;
  1489. }, ARRAY_FILTER_USE_BOTH);
  1490. if(count($trainElementFilt) < 1){
  1491. return $this->responseController->makeResponse(true, "El elemento de origen no existe.", [], 404);
  1492. }
  1493. $trainArea = $this->encryptionController->decrypt($form['train_area']);
  1494. if(!$trainArea){
  1495. return $this->responseController->makeResponse(true, 'El área del tren no fue encriptado correctamente.', [], 400);
  1496. }
  1497. $carAreasEnc = file_get_contents($ubic . "car-areas.sam");
  1498. $carAreasDec = $this->encryptionController->decrypt($carAreasEnc);
  1499. $carAreasArr = json_decode($carAreasDec, true);
  1500. $carAreasArrDec = [];
  1501. foreach($carAreasArr as $key=>$val){
  1502. $keyDec = $this->encryptionController->decrypt($key);
  1503. $carAreasArrDec[$keyDec] = $val;
  1504. }
  1505. $occupationAreasFilt = array_filter($carAreasArrDec, function($v, $k) use($originOccupationStr) {
  1506. return $k == $originOccupationStr;
  1507. }, ARRAY_FILTER_USE_BOTH);
  1508. if(count($occupationAreasFilt) < 1){
  1509. return $this->responseController->makeResponse(true, "No se encontraron áreas relacionadas a la ocupación $originOccupationStr.", [], 404);
  1510. }
  1511. $occupationAreasArr = end($occupationAreasFilt);
  1512. foreach($occupationAreasArr as $k0=>$v0){
  1513. $occupationArea = [];
  1514. foreach($v0 as $k1=>$v1){
  1515. $valDec = $this->encryptionController->decrypt($v1);
  1516. $occupationArea[$k1] = $valDec;
  1517. }
  1518. $occupationAreasArr[$k0] = $occupationArea;
  1519. }
  1520. $occupationAreaFilt = array_filter($occupationAreasArr, function($v, $k) use($trainArea) {
  1521. return $v['CODE'] == $trainArea;
  1522. }, ARRAY_FILTER_USE_BOTH);
  1523. if(count($occupationAreaFilt) < 1){
  1524. return $this->responseController->makeResponse(true, "el área del tren seleccionada no existe.", [], 404);
  1525. }
  1526. }else{
  1527. $originElement = $form['origin_element'];
  1528. $elde = isset($form['destiny_element']) ? $form['destiny_element'] : null;
  1529. }
  1530. $ipcc = isset($form['pcc_intersection']) ? $form['pcc_intersection'] : null;
  1531. $ppcc = isset($form['pcc_position']) ? $form['pcc_position'] : null;
  1532. $kior = isset($form['origin_kilometer']) ? $form['origin_kilometer'] : null;
  1533. $kide = isset($form['destiny_kilometer']) ? $form['destiny_kilometer'] : null;
  1534. $tcor = null;
  1535. $ceor = null;
  1536. $tcde = null;
  1537. $cede = null;
  1538. if($form['code_type'] == '6'){
  1539. if($form['origin_code_type'] == $form['destiny_code_type']){
  1540. return $this->responseController->makeResponse(true, 'El tipo de código de origen no puede ser igual al tipo de código de destino.', [], 400);
  1541. }
  1542. $ceor = $this->encryptionController->decrypt($form['origin_element']);
  1543. if(!$ceor){
  1544. return $this->responseController->makeResponse(true, 'El código del elemento de origen no fue encriptado correctamente.', [], 400);
  1545. }
  1546. $tcor = $form['origin_code_type'];
  1547. $originElementCodeArr0 = explode('_', $ceor);
  1548. if($form['origin_code_type'] == '1'){
  1549. $originPBSArr = explode('.', $originElementCodeArr0[0]);
  1550. $originLocation = $originPBSArr[1];
  1551. $originLevel = $originPBSArr[2];
  1552. $originOccupationStr = $originPBSArr[3];
  1553. $originElement = $originPBSArr[4];
  1554. $originLBSArr = explode('.', $originElementCodeArr0[1]);
  1555. $originLBSArr = array_reverse($originLBSArr);
  1556. $originEquipment = explode('-', $originLBSArr[0]);
  1557. $originElementSecuence = $originEquipment[2];
  1558. }else if($form['origin_code_type'] == '2'){
  1559. $originPBSArr = explode('.', $originElementCodeArr0[0]);
  1560. $originLocation = $originPBSArr[1];
  1561. $originLevel = $originPBSArr[2];
  1562. $originOccupationStr = $originPBSArr[3];
  1563. $originElement = $originPBSArr[4];
  1564. $ipcc = $originPBSArr[5];
  1565. $ppcc = $originPBSArr[6];
  1566. $originLBSArr = explode('.', $originElementCodeArr0[1]);
  1567. $originLBSArr = array_reverse($originLBSArr);
  1568. $originEquipment = explode('-', $originLBSArr[0]);
  1569. $originElementSecuence = $originEquipment[2];
  1570. }else if($form['origin_code_type'] == '3'){
  1571. $originElementCodeArr1 = explode(':', $originElementCodeArr0[0]);
  1572. $originPBSArr = explode('.', $originElementCodeArr1[0]);
  1573. $originLocation = $originPBSArr[1];
  1574. $originLevel = $originPBSArr[2];
  1575. $originOccupationStr = $originPBSArr[3];
  1576. $originLBSArr = explode('.', $originElementCodeArr0[1]);
  1577. $originLBSArr = array_reverse($originLBSArr);
  1578. $originEquipment = explode('-', $originLBSArr[0]);
  1579. $originElement = $originEquipment[0];
  1580. $originKilometerArr = explode('.', $form['origin_kilometer']);
  1581. $kior = implode(',', $originKilometerArr);
  1582. }else if($form['origin_code_type'] == '4'){
  1583. $originElementCodeArr1 = explode(':', $originElementCodeArr0[0]);
  1584. $originPBSArr = explode('.', $originElementCodeArr1[0]);
  1585. $originLocation = $originPBSArr[1];
  1586. $originLevel = $originPBSArr[2];
  1587. $originOccupationStr = $originPBSArr[3];
  1588. $originLBSArr = explode('.', $originElementCodeArr0[1]);
  1589. $originLBSArr = array_reverse($originLBSArr);
  1590. $originEquipment = explode('-', $originLBSArr[0]);
  1591. $originElement = $originEquipment[0];
  1592. $originElementSecuence = $originEquipment[2];
  1593. }else if($form['origin_code_type'] == '5'){
  1594. $originPBSArr = explode('.', $originElementCodeArr0[0]);
  1595. $originLocation = $originPBSArr[1];
  1596. $originLevel = $originPBSArr[2];
  1597. $originOccupationStr = $originPBSArr[3];
  1598. $originElement = $originPBSArr[5];
  1599. $trainArea = $originPBSArr[4];
  1600. $originLBSArr = explode('.', $originElementCodeArr0[1]);
  1601. $originLBSArr = array_reverse($originLBSArr);
  1602. $originEquipment = explode('-', $originLBSArr[0]);
  1603. $originElementSecuence = $originEquipment[2];
  1604. }
  1605. $cede = $this->encryptionController->decrypt($form['destiny_element']);
  1606. if(!$cede){
  1607. return $this->responseController->makeResponse(true, 'El código del elemento de destino no fue encriptado correctamente.', [], 400);
  1608. }
  1609. $tcde = $form['destiny_code_type'];
  1610. $destinyElementCodeArr0 = explode('_', $cede);
  1611. if($form['destiny_code_type'] == '1'){
  1612. $destinyPBSArr = explode('.', $destinyElementCodeArr0[0]);
  1613. $destinyLocation = $destinyPBSArr[1];
  1614. $destinyLevel = $destinyPBSArr[2];
  1615. $destinyOccupationStr = $destinyPBSArr[3];
  1616. $elde = $destinyPBSArr[4];
  1617. $destinyLBSArr = explode('.', $destinyElementCodeArr0[1]);
  1618. $destinyLBSArr = array_reverse($destinyLBSArr);
  1619. $destinyEquipment = explode('-', $destinyLBSArr[0]);
  1620. $destinyElementSecuence = $destinyEquipment[2];
  1621. }else if($form['destiny_code_type'] == '2'){
  1622. $destinyPBSArr = explode('.', $destinyElementCodeArr0[0]);
  1623. $destinyLocation = $destinyPBSArr[1];
  1624. $destinyLevel = $destinyPBSArr[2];
  1625. $destinyOccupationStr = $destinyPBSArr[3];
  1626. $elde = $destinyPBSArr[4];
  1627. $ipcc = $destinyPBSArr[5];
  1628. $ppcc = $destinyPBSArr[6];
  1629. $destinyLBSArr = explode('.', $destinyElementCodeArr0[1]);
  1630. $destinyLBSArr = array_reverse($destinyLBSArr);
  1631. $destinyEquipment = explode('-', $destinyLBSArr[0]);
  1632. $destinyElementSecuence = $destinyEquipment[2];
  1633. }else if($form['destiny_code_type'] == '3'){
  1634. $destinyElementCodeArr1 = explode(':', $destinyElementCodeArr0[0]);
  1635. $destinyPBSArr = explode('.', $destinyElementCodeArr1[1]);
  1636. $destinyLocation = $destinyPBSArr[0];
  1637. $destinyLevel = $destinyPBSArr[1];
  1638. $destinyOccupationStr = $destinyPBSArr[2];
  1639. $destinyBSArr = explode('.', $destinyElementCodeArr0[1]);
  1640. $destinyBSArr = array_reverse($destinyBSArr);
  1641. $destinyEquipment = explode('-', $destinyBSArr[0]);
  1642. $elde = $destinyEquipment[0];
  1643. $destinyKilometerArr = explode('.', $form['destiny_kilometer']);
  1644. $kide = implode(',', $destinyKilometerArr);
  1645. }else if($form['destiny_code_type'] == '4'){
  1646. $destinyElementCodeArr1 = explode(':', $destinyElementCodeArr0[0]);
  1647. $destinyPBSArr = explode('.', $destinyElementCodeArr1[1]);
  1648. $destinyLocation = $destinyPBSArr[0];
  1649. $destinyLevel = $destinyPBSArr[1];
  1650. $destinyOccupationStr = $destinyPBSArr[2];
  1651. $destinyBSArr = explode('.', $destinyElementCodeArr0[1]);
  1652. $destinyBSArr = array_reverse($destinyBSArr);
  1653. $destinyEquipment = explode('-', $destinyBSArr[0]);
  1654. $elde = $destinyEquipment[0];
  1655. $destinyElementSecuence = $destinyEquipment[2];
  1656. }else if($form['destiny_code_type'] == '5'){
  1657. $destinyPBSArr = explode('.', $destinyElementCodeArr0[0]);
  1658. $destinyLocation = $destinyPBSArr[1];
  1659. $destinyLevel = $destinyPBSArr[2];
  1660. $destinyOccupationStr = $destinyPBSArr[3];
  1661. $elde = $destinyPBSArr[5];
  1662. $trainArea = $destinyPBSArr[4];
  1663. $destinyBSArr = explode('.', $destinyElementCodeArr0[1]);
  1664. $destinyBSArr = array_reverse($destinyBSArr);
  1665. $destinyEquipment = explode('-', $destinyBSArr[0]);
  1666. $destinyElementSecuence = $destinyEquipment[2];
  1667. }
  1668. }
  1669. $codeVerified = $this->verifyPreCode([
  1670. "line" => $form['linea'],
  1671. "originLocation" => $originLocation,
  1672. "originLevel" => $originLevel,
  1673. "originOccupation" => $originOccupationStr,
  1674. "originElement" => $originElement,
  1675. "family" => $familyCode,
  1676. "subfamily" => $subfamilyCode,
  1677. "status" => $status,
  1678. "equipmentType" => $form['equipment_type'],
  1679. "equipmentModel" => $form['equipment_model'],
  1680. "equipmentID" => "XXXXX",
  1681. "pccIntersection" => $ipcc,
  1682. "pccPosition" => $ppcc,
  1683. "originKilometers" => $kior,
  1684. "destinyLocation" => $destinyLocation,
  1685. "destinyLevel" => $destinyLevel,
  1686. "destinyOccupation" => $destinyOccupationStr,
  1687. "destinyElement" => $elde,
  1688. "destinyKilometers" => $kide,
  1689. "originElementSecuence" => $originElementSecuence,
  1690. "destinyElementSecuence" => $destinyElementSecuence,
  1691. "trainArea" => $trainArea,
  1692. "originCodeType" => isset($form['origin_code_type']) ? $form['origin_code_type'] : null,
  1693. "destinyCodeType" => isset($form['destiny_code_type']) ? $form['destiny_code_type'] : null,
  1694. ], $form['code_type'], $form['hierarchy'], $eqpa);
  1695. if($codeVerified != $preCode){
  1696. return $this->responseController->makeResponse(true, 'El código generado no coincide con el código verificado a partir de la información del formulario.', [], 400);
  1697. }
  1698. $deso = isset($form['software_name']) ? $form['software_name'] : null;
  1699. $veso = isset($form['software_version']) ? $form['software_version'] : null;
  1700. $now = $this->functionsController->now();
  1701. $nowStr = $now->toDateTimeString();
  1702. DB::table('S002V01TPCEQ')->insert([
  1703. 'PCEQ_NULI' => $form['linea'],
  1704. 'PCEQ_CPGE' => $preCode,
  1705. 'PCEQ_JERA' => $form['hierarchy'],
  1706. 'PCEQ_EQPA' => $eqpa,
  1707. 'PCEQ_TICO' => $form['code_type'],
  1708. 'PCEQ_UBOR' => $originLocation,
  1709. 'PCEQ_NIOR' => $originLevel,
  1710. 'PCEQ_OCOR' => $originOccupationStr,
  1711. 'PCEQ_ELOR' => $originElement,
  1712. 'PCEQ_FAMI' => $familyCode,
  1713. 'PCEQ_SUBF' => $subfamilyCode,
  1714. 'PCEQ_ESEQ' => $status,
  1715. 'PCEQ_TIEQ' => $form['equipment_type'],
  1716. 'PCEQ_MOEQ' => $form['equipment_model'],
  1717. 'PCEQ_IPCC' => $ipcc,
  1718. 'PCEQ_PPCC' => $ppcc,
  1719. 'PCEQ_KIOR' => $kior,
  1720. 'PCEQ_SEOR' => $originElementSecuence,
  1721. 'PCEQ_ARTR' => $trainArea,
  1722. 'PCEQ_TCOR' => $tcor,
  1723. 'PCEQ_CEOR' => $ceor,
  1724. 'PCEQ_UBDE' => $destinyLocation,
  1725. 'PCEQ_NIDE' => $destinyLevel,
  1726. 'PCEQ_OCDE' => $destinyOccupationStr,
  1727. 'PCEQ_ELDE' => $elde,
  1728. 'PCEQ_KIDE' => $kide,
  1729. 'PCEQ_SEDE' => $destinyElementSecuence,
  1730. 'PCEQ_TCDE' => $tcde,
  1731. 'PCEQ_CEDE' => $cede,
  1732. 'PCEQ_FEAD' => $form['acquisition_date'],
  1733. 'PCEQ_FIGA' => $form['warranty_start_date'],
  1734. 'PCEQ_FTGA' => $form['warranty_end_date'],
  1735. 'PCEQ_PREQ' => $providerID,
  1736. 'PCEQ_NUSE' => $serialNumer,
  1737. 'PCEQ_DESO' => $deso,
  1738. 'PCEQ_VESO' => $veso,
  1739. 'PCEQ_GAIM' => $imagesGalleryStr,
  1740. 'PCEQ_DORE' => $documentsStr,
  1741. 'PCEQ_USRE' => $idUser,
  1742. 'PCEQ_FERE' => $nowStr,
  1743. ]);
  1744. $actions = DB::getQueryLog();
  1745. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1746. $idac = $this->functionsController->registerActivity(
  1747. $form['linea'],
  1748. 'S002V01M07GEEQ',
  1749. 'S002V01F01ADEQ',
  1750. 'S002V01P11REEQ',
  1751. 'Registro',
  1752. "El usuario $name (" . $usr->USUA_IDUS . ") solicitó el registro del equipamiento $preCode.",
  1753. $idUser,
  1754. $nowStr,
  1755. );
  1756. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1757. return $this->responseController->makeResponse(false, 'EXITO.');
  1758. }
  1759. public function saveEquipmentPreCodifiedStock(Request $request) {
  1760. DB::enableQueryLog();
  1761. $validator = Validator::make($request->all(), [
  1762. 'id_user' => 'required|string',
  1763. 'linea' => 'required|integer',
  1764. 'hierarchy' => 'required|string|in:Padre,Hijo',
  1765. 'parent_equipment' => 'required_if:hierarchy,=,Hijo|string',
  1766. 'code_type' => 'required|integer|between:1,7',
  1767. 'origin_location' => 'required_unless:code_type,7|string|nullable',
  1768. 'origin_level' => 'required_unless:code_type,7|string|nullable',
  1769. 'origin_occupation' => 'required_unless:code_type,7|string|nullable',
  1770. 'origin_element' => 'required_unless:code_type,7|string|max:150|nullable',
  1771. 'family' => 'required|string',
  1772. 'subfamily' => 'required|string',
  1773. 'status' => 'required|string',
  1774. 'equipment_type' => 'required|string|max:150',
  1775. 'equipment_model' => 'required|string|max:75',
  1776. 'images' => 'required|json',
  1777. 'documents' => 'required|json',
  1778. 'acquisition_date' => 'required|date',
  1779. 'warranty_start_date' => 'required|date',
  1780. 'warranty_end_date' => 'required|date',
  1781. 'equipment_provider' => 'required|string',
  1782. 'serial_number' => 'nullable|string',
  1783. 'has_software' => 'required|string|in:Si,No',
  1784. 'software_name' => 'required_if:has_software,=,Si|string|max:150',
  1785. 'software_version' => 'required_if:has_software,=,Si|string|max:75',
  1786. 'pre_generated_code' => 'required|string',
  1787. 'pcc_intersection' => 'required_if:code_type,=,2|string|max:5',
  1788. 'pcc_position' => 'required_if:code_type,=,2|string|max:2',
  1789. 'origin_kilometer' => 'required_if:code_type,=,3|numeric',
  1790. 'destiny_location' => 'required_if:code_type,=,3|string',
  1791. 'destiny_level' => 'required_if:code_type,=,3|string',
  1792. 'destiny_occupation' => 'required_if:code_type,=,3|string',
  1793. 'destiny_element' => 'required_if:code_type,=,3|string|max:150',
  1794. 'destiny_kilometer' => 'required_if:code_type,=,3|string',
  1795. 'warehouse' => 'required_if:code_type,=,7|string',
  1796. 'area' => 'required_if:code_type,=,7|string',
  1797. 'level' => 'required_if:code_type,=,7|string',
  1798. 'zone' => 'required_if:code_type,=,7|string',
  1799. 'number_items' => 'required|integer',
  1800. ]);
  1801. if($validator->fails()){
  1802. return $this->responseController->makeResponse(
  1803. true,
  1804. "Se encontraron uno o más errores.",
  1805. $this->responseController->makeErrors(
  1806. $validator->errors()->messages()
  1807. ),
  1808. 401
  1809. );
  1810. }
  1811. $form = $request->all();
  1812. // Desencriptación del usuario
  1813. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1814. if(!$idUser){
  1815. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1816. }
  1817. // Obtención del usuario
  1818. $usr = DB::table('S002V01TUSUA')->where([
  1819. ['USUA_NULI', '=', $form['linea']],
  1820. ['USUA_IDUS', '=', $idUser]
  1821. ])->first();
  1822. // Verificación de la existencia del usuario
  1823. if(is_null($usr)){
  1824. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1825. }
  1826. // El código del equipo padre se inicializa
  1827. $eqpa = null;
  1828. // Si la jerarquía es de tipo "Hijo", Entonces
  1829. if($form['hierarchy'] == 'Hijo'){
  1830. // Se desencripta el código del equipamiento padre
  1831. $eqpa = $this->encryptionController->decrypt($form['parent_equipment']);
  1832. if(!$eqpa){
  1833. return $this->responseController->makeResponse(true, 'El ID del equipamiento padre no fue encriptado correctamente.', [], 400);
  1834. }
  1835. // Se obtiene la información del equipo padre
  1836. $parentEquipment = DB::table('S002V01TEQUI')->where([
  1837. ['EQUI_NULI', '=', $form['linea']],
  1838. ['EQUI_COEQ', '=', $eqpa],
  1839. ])->first();
  1840. // Se verifica que el equipo padre exista
  1841. if(is_null($parentEquipment)){
  1842. return $this->responseController->makeResponse(true, 'El equipamiento padre no existe.', [], 404);
  1843. }
  1844. }
  1845. // Se obtiene la ubicación de las plantillas
  1846. $ubic = $this->templatesUbic;
  1847. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  1848. $locationsEnc = file_get_contents($ubic . "locations.sam");
  1849. $locationsDec = $this->encryptionController->decrypt($locationsEnc);
  1850. $locationsArr = json_decode($locationsDec, true);
  1851. $locationsArrDec = [];
  1852. foreach($locationsArr as $location){
  1853. $locationStr = $this->encryptionController->decrypt($location['LOCATION']);
  1854. $code = $this->encryptionController->decrypt($location['CODE']);
  1855. $locationsArrDec[] = [
  1856. 'LOCATION' => $locationStr,
  1857. 'CODE' => $code
  1858. ];
  1859. }
  1860. $originLocation = null;
  1861. $originLevel = null;
  1862. $originOccupationStr = null;
  1863. $idWarehouse = null;
  1864. $idArea = null;
  1865. $idLevel = null;
  1866. $idZone = null;
  1867. if ($form['code_type'] !== '7') {
  1868. // Se desencripta la ubicación de origen
  1869. $originLocation = $this->encryptionController->decrypt($form['origin_location']);
  1870. if(!$originLocation){
  1871. return $this->responseController->makeResponse(true, 'La ubicación de origen no fue encriptada correctamente.', [], 400);
  1872. }
  1873. // Se verifica con la información del sistema
  1874. $originLocationFilt = array_filter($locationsArrDec, function($v, $k) use ($originLocation) {
  1875. return $v['CODE'] == $originLocation;
  1876. }, ARRAY_FILTER_USE_BOTH);
  1877. // Se verifica que la ubicacion exista en la información del sistema
  1878. if(count($originLocationFilt) < 1){
  1879. return $this->responseController->makeResponse(true, 'La ubicación de origen no se encuentra registrada en el sistema.', [], 404);
  1880. }
  1881. // Se desencripta el nivel del origen
  1882. $originLevel = $this->encryptionController->decrypt($form['origin_level']);
  1883. if(!$originLevel){
  1884. return $this->responseController->makeResponse(true, 'El nivel de origen no fue encriptado correctamente.', [], 400);
  1885. }
  1886. // Se obtienen los niveles disponibles
  1887. $supportedLevels = [];
  1888. for($i = 5; $i > 0; $i--){
  1889. $supportedLevels[] = "S0$i";
  1890. }
  1891. for($i = 0; $i <= 15; $i++){
  1892. $tag = $i < 10 ? "P0$i" : "P$i";
  1893. $supportedLevels[] = $tag;
  1894. }
  1895. // Se verifica que el origen sea válido
  1896. if(!in_array($originLevel, $supportedLevels)){
  1897. return $this->responseController->makeResponse(true, 'El nivel de origen seleccionado es inválido.', [], 400);
  1898. }
  1899. // Se desencripta la ocupación de orden
  1900. $originOccupationStr = $this->encryptionController->decrypt($form['origin_occupation']);
  1901. if(!$originOccupationStr){
  1902. return $this->responseController->makeResponse(true, 'La ocupación de origen no fue encriptada correctamente.', [], 400);
  1903. }
  1904. // Se obtiene la información de la ocupación
  1905. $originOccupationArea = substr($originOccupationStr, 0, 2);
  1906. $originOccupationID = substr($originOccupationStr, 2);
  1907. $originOccupation = DB::table('S002V01TOCUP')->where([
  1908. ['OCUP_NULI', '=', $form['linea']],
  1909. ['OCUP_AREA', '=', $originOccupationArea],
  1910. ['OCUP_IDOC', '=', $originOccupationID]
  1911. ])->first();
  1912. // Se verifica que exista la ocupació
  1913. if(is_null($originOccupation)){
  1914. return $this->responseController->makeResponse(true, 'La ocupación de origen seleccionada no existe.', [], 404);
  1915. }
  1916. } else {
  1917. $form['origin_element'] = null;
  1918. $idWarehouse = $this->encryptionController->decrypt($form['warehouse']);
  1919. if ($idWarehouse === false) {
  1920. return $this->responseController->makeResponse(true, 'El almacen no está encriptado correctamente.', [], 404);
  1921. }
  1922. $idArea = $this->encryptionController->decrypt($form['area']);
  1923. if ($idArea === false) {
  1924. return $this->responseController->makeResponse(true, 'El área no está encriptado correctamente.', [], 404);
  1925. }
  1926. $idLevel = $this->encryptionController->decrypt($form['level']);
  1927. if ($idLevel === false) {
  1928. return $this->responseController->makeResponse(true, 'El nivel no está encriptado correctamente.', [], 404);
  1929. }
  1930. $idZone = $this->encryptionController->decrypt($form['zone']);
  1931. if ($idZone === false) {
  1932. return $this->responseController->makeResponse(true, 'La zona no está encriptado correctamente.', [], 404);
  1933. }
  1934. try {
  1935. $validateWarehouse = DB::table('S002V01TALMA')
  1936. ->where('ALMA_COAL', '=', $idWarehouse)
  1937. ->where('ALMA_NULI', '=', $form['linea'])
  1938. ->exists();
  1939. } catch (\Throwable $th) {
  1940. return $this->responseController->makeResponse(true, 'Ocurrió un error al validar el almacen.', [], 500);
  1941. }
  1942. if (!$validateWarehouse) {
  1943. return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
  1944. }
  1945. try {
  1946. $validateArea = DB::table('S002V01TAREA')
  1947. ->where('AREA_COAL', '=', $idWarehouse)
  1948. ->where('AREA_COAR', '=', $idArea)
  1949. ->where('AREA_NULI', '=', $form['linea'])
  1950. ->exists();
  1951. } catch (\Throwable $th) {
  1952. return $this->responseController->makeResponse(true, 'Ocurrió un error al validar el almacen.', [], 500);
  1953. }
  1954. if (!$validateArea) {
  1955. return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
  1956. }
  1957. try {
  1958. $validateLevel = DB::table('S002V01TNIVE')
  1959. ->where('NIVE_COAL', '=', $idWarehouse)
  1960. ->where('NIVE_COAR', '=', $idArea)
  1961. ->where('NIVE_CONI', '=', $idLevel)
  1962. ->where('NIVE_NULI', '=', $form['linea'])
  1963. ->exists();
  1964. } catch (\Throwable $th) {
  1965. return $this->responseController->makeResponse(true, 'Ocurrió un error al validar el almacen.', [], 500);
  1966. }
  1967. if (!$validateLevel) {
  1968. return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
  1969. }
  1970. try {
  1971. $validateZone = DB::table('S002V01TZONA')
  1972. ->where('ZONA_COAL', '=', $idWarehouse)
  1973. ->where('ZONA_COAR', '=', $idArea)
  1974. ->where('ZONA_CONI', '=', $idLevel)
  1975. ->where('ZONA_COZO', '=', $idZone)
  1976. ->where('ZONA_NULI', '=', $form['linea'])
  1977. ->exists();
  1978. } catch (\Throwable $th) {
  1979. return $this->responseController->makeResponse(true, 'Ocurrió un error al validar el almacen.', [], 500);
  1980. }
  1981. if (!$validateZone) {
  1982. return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
  1983. }
  1984. }
  1985. // Se desencripta la familia
  1986. $familyCode = $this->encryptionController->decrypt($form['family']);
  1987. if(!$familyCode){
  1988. return $this->responseController->makeResponse(true, 'La familia del equipamiento no fue encriptada correctamente.', [], 400);
  1989. }
  1990. // Se obtienen los datos de la familia
  1991. $family = DB::table('S002V01TFAMI')->where([
  1992. ['FAMI_NULI', '=', $form['linea']],
  1993. ['FAMI_COFA', '=', $familyCode]
  1994. ])->first();
  1995. // Se verifica que la familia exista
  1996. if(is_null($family)){
  1997. return $this->responseController->makeResponse(true, 'La familia seleccionada no existe.', [], 404);
  1998. }
  1999. // Se desencripta la subfamilia
  2000. $subfamilyCode = $this->encryptionController->decrypt($form['subfamily']);
  2001. if(!$subfamilyCode){
  2002. return $this->responseController->makeResponse(true, 'La subfamilia del equipamiento no fue encriptada correctamente.', [], 400);
  2003. }
  2004. // Se obtienen los datos de la subfamilia
  2005. $subfamily = DB::table('S002V01TSUBF')->where([
  2006. ['SUBF_NULI', '=', $form['linea']],
  2007. ['SUBF_COFA', '=', $familyCode],
  2008. ['SUBF_COSU', '=', $subfamilyCode]
  2009. ])->first();
  2010. // Se verifica que la subfamilia exista
  2011. if(is_null($subfamily)){
  2012. return $this->responseController->makeResponse(true, 'La subfamilia seleccionada no existe.', [], 404);
  2013. }
  2014. // Se inicializa arreglo con los estados disponibles
  2015. $validStatus = ["A", "S", "T", "I", "R", "D"];
  2016. // Se desencripta el estado
  2017. $status = $this->encryptionController->decrypt($form['status']);
  2018. // Se verifica que el estado sea un valor válido
  2019. if(!$status){
  2020. return $this->responseController->makeResponse(true, 'La estado del equipamiento no fue encriptado correctamente.', [], 400);
  2021. }else if(!in_array($status, $validStatus)){
  2022. return $this->responseController->makeResponse(true, 'El estado seleccionado para el equipamiento es inválido.', [], 400);
  2023. }
  2024. // Se obtiene el arreglo de las imagenes
  2025. $imagesArr = json_decode($form['images'], true);
  2026. // Se verifica que el arreglo contenga imagenes
  2027. if(count($imagesArr) < 1){
  2028. return $this->responseController->makeResponse(true, 'El arreglo de la galería de imágenes está vacío.', [], 400);
  2029. }
  2030. $imagesGallery = [];
  2031. // Se iteran las imagenes
  2032. foreach($imagesArr as $imageFile){
  2033. // Se verifica que tenga un formato correcto
  2034. if(!array_key_exists('type', $imageFile)){
  2035. return $this->responseController->makeResponse(true, 'El arreglo de la galería de imágenes tiene un formato inválido.', [], 400);
  2036. // Si la imagen es nueva, entonces...
  2037. }else if($imageFile['type'] == 'Nuevo'){
  2038. // Se obtiene el ID de la imagen
  2039. $tempFileID = $this->encryptionController->decrypt($imageFile['id']);
  2040. // Se obtiene la información registrada en la tabla de archivos temporales
  2041. $tempFile = DB::table('S002V01TARTE')->where([
  2042. ['ARTE_IDAR', '=', $tempFileID],
  2043. ['ARTE_NULI', '=', $form['linea']]
  2044. ])->first();
  2045. // La imagen es colocada en su posición final
  2046. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GEEQ', 'FO', $tempFile, $idUser);
  2047. // Si ocurrió un error, entonces se manda el error
  2048. if(!$finalFile[0]){
  2049. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  2050. }
  2051. // La información es guardada en un arreglo
  2052. $imagesGallery[] = $finalFile[1];
  2053. }else{
  2054. // Se desencripta el id de la imagen
  2055. $fileID = $this->encryptionController->decrypt($imageFile['id']);
  2056. // Es guardada en un arreglo
  2057. $imagesGallery[] = $fileID;
  2058. }
  2059. }
  2060. // El arreglo de las imagenes es pasada en formato string
  2061. $imagesGalleryStr = json_encode($imagesGallery);
  2062. // Se obtiene el arreglo de los documentos
  2063. $documentsArr = json_decode($form['documents'], true);
  2064. if(count($documentsArr) < 1){
  2065. return $this->responseController->makeResponse(true, 'El arreglo de documentos relacionados está vacío.', [], 400);
  2066. }
  2067. $documents = [];
  2068. // Se iteran los documentos
  2069. foreach($documentsArr as $documentFile){
  2070. // Se verifica que tenga un formato correcto
  2071. if(!array_key_exists('type', $documentFile)){
  2072. return $this->responseController->makeResponse(true, 'El arreglo de documentos asociados tiene un formato inválido.', [], 400);
  2073. // Si el documento es nuevo, entonces...
  2074. }else if($documentFile['type'] == 'Nuevo'){
  2075. // Se obtiene el ID del documento
  2076. $tempFileID = $this->encryptionController->decrypt($documentFile['id']);
  2077. // Se obtiene la información registrada en la tabla de archivos temporales
  2078. $tempFile = DB::table('S002V01TARTE')->where([
  2079. ['ARTE_IDAR', '=', $tempFileID],
  2080. ['ARTE_NULI', '=', $form['linea']]
  2081. ])->first();
  2082. // El documento es colocada en su posición final
  2083. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GEEQ', 'IN', $tempFile, $idUser);
  2084. // Si ocurrió un error, entonces se manda el error
  2085. if(!$finalFile[0]){
  2086. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  2087. }
  2088. // La información es guardada en un arreglo
  2089. $documents[] = $finalFile[1];
  2090. }else{
  2091. // Se desencripta el id del documento
  2092. $fileID = $this->encryptionController->decrypt($documentFile['id']);
  2093. // Es guardada en un arreglo
  2094. $documents[] = $fileID;
  2095. }
  2096. }
  2097. // El arreglo de los documentos es pasada en formato string
  2098. $documentsStr = json_encode($documents);
  2099. // Se obtiene el formato de la fecha en formato manejable
  2100. $acquisitionDate = new Carbon($form['acquisition_date']);
  2101. $warrantyStartDate = new Carbon($form['warranty_start_date']);
  2102. $warrantyEndDate = new Carbon($form['warranty_end_date']);
  2103. // Se verifica que la fecha de inicio de la garantia sea menor a la fecha final de la garantia
  2104. if($warrantyStartDate->lt($acquisitionDate)){
  2105. return $this->responseController->makeResponse(true, 'La fecha de inicio de la grantía no puede ser menor a la fecha de adquisición.', [], 400);
  2106. }else if($warrantyEndDate->lte($acquisitionDate)){
  2107. return $this->responseController->makeResponse(true, 'La fecha de término de la grantía no puede ser menor o igual a la fecha de inicio de la garantía.', [], 400);
  2108. }
  2109. // Se desencripta el numero del proveedor
  2110. $providerID = $this->encryptionController->decrypt($form['equipment_provider']);
  2111. if(!$providerID){
  2112. return $this->responseController->makeResponse(true, 'El proveedor del equipamiento no fue encriptado correctamente.', [], 400);
  2113. }
  2114. // Se obtiene la información del proveedor
  2115. $provider = DB::table('S002V01TPROV')->where([
  2116. ['PROV_NUPR', '=', $providerID],
  2117. ['PROV_NULI', '=', $form['linea']]
  2118. ])->first();
  2119. // Se verifica que el proveedor exista
  2120. if(is_null($provider)){
  2121. return $this->responseController->makeResponse(true, 'La proveedor seleccionada no existe.', [], 404);
  2122. }
  2123. $arrSerialNumber = array();
  2124. if ($form['serial_number'] !== '' && !is_null($form['serial_number'])) {
  2125. // Se desencripta el número de serie
  2126. $serialNumer = $this->encryptionController->decrypt($form['serial_number']);
  2127. if(!$serialNumer){
  2128. return $this->responseController->makeResponse(true, 'El número de serie del equipamiento no fue encriptado correctamente.', [], 400);
  2129. }
  2130. $arrSerialNumber = explode(',', $serialNumer);
  2131. if (intval($form['number_items']) !== count($arrSerialNumber)) {
  2132. return $this->responseController->makeResponse(true, 'La cantidad de número de series no corresponde con la cantidad de artículos a registrar.', [], 400);
  2133. }
  2134. foreach ($arrSerialNumber as $key => $serialNumber) {
  2135. // Se obtiene la información del equipamiento por medio del número de serie
  2136. $serialNmberDB = DB::table('S002V01TPCEQ')->where([
  2137. ['PCEQ_NULI', '=', $form['linea']],
  2138. ['PCEQ_NUSE', '=', $serialNumber]
  2139. ])->first();
  2140. // Se verifica que exista el código de serie
  2141. if(!is_null($serialNmberDB)){
  2142. $serialNumberStr = $serialNmberDB->PCEQ_CPGE;
  2143. return $this->responseController->makeResponse(true, "El número de serie $serialNumber enviado ya se encuentra relacionado al equipamiento $serialNumberStr.", [], 401);
  2144. }
  2145. }
  2146. $temp_array = array_unique($arrSerialNumber);
  2147. $duplicates = sizeof($temp_array) != sizeof($arrSerialNumber);
  2148. if ($duplicates) {
  2149. return $this->responseController->makeResponse(true, 'Los número de serie no se pueden repetir.', [], 400);
  2150. }
  2151. } else {
  2152. try {
  2153. $getEquipment = DB::table('S002V01TPCEQ')
  2154. ->where('PCEQ_NULI', '=', $form['linea'])
  2155. ->where('PCEQ_NUSE', 'LIKE', '0-%')
  2156. ->get(['PCEQ_NUSE AS NUMERO_SERIE']);
  2157. } catch (\Throwable $th) {
  2158. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los artículos.', $th->getMessage(), 400);
  2159. }
  2160. $lastSerie = 0;
  2161. if (count($getEquipment) > 0) {
  2162. foreach ($getEquipment as $key => $equipment) {
  2163. $serie = str_replace('0-', '', $equipment->NUMERO_SERIE);
  2164. $serie = intval($serie);
  2165. if (is_null($lastSerie)) {
  2166. $lastSerie = $serie;
  2167. } else if ($serie > $lastSerie) {
  2168. $lastSerie = $serie;
  2169. }
  2170. }
  2171. }
  2172. for ($i=0; $i < $form['number_items']; $i++) {
  2173. $lastSerie = $lastSerie + 1;
  2174. $arrSerialNumber[] = '0-'.$lastSerie;
  2175. }
  2176. }
  2177. if ( empty($arrSerialNumber) ) {
  2178. return $this->responseController->makeResponse(true, 'No hay números de serie disponibles.', [], 400);
  2179. }
  2180. // Se desencripta el código pregenerado en Angular
  2181. $preCode = $this->encryptionController->decrypt($form['pre_generated_code']);
  2182. if(!$preCode){
  2183. return $this->responseController->makeResponse(true, 'El código pre generado no fue encriptado correctamente.', [], 400);
  2184. }
  2185. // Se obtiene el código pregenerado en Laravel
  2186. $codeVerified = $this->verifyPreCode([
  2187. "line" => $form['linea'],
  2188. "originLocation" => $originLocation,
  2189. "originLevel" => $originLevel,
  2190. "originOccupation" => $originOccupationStr,
  2191. "originElement" => $form['origin_element'],
  2192. "warehouse" => $idWarehouse,
  2193. "area" => $idArea,
  2194. "level" => $idLevel,
  2195. "zone" => $idZone,
  2196. "family" => $familyCode,
  2197. "subfamily" => $subfamilyCode,
  2198. "status" => $status,
  2199. "equipmentType" => $form['equipment_type'],
  2200. "equipmentModel" => $form['equipment_model'],
  2201. "equipmentID" => "XXXXX",
  2202. "pccIntersection" => null,
  2203. "pccPosition" => null,
  2204. "originKilometers" => null,
  2205. "destinyLocation" => null,
  2206. "destinyLevel" => null,
  2207. "destinyOccupation" => null,
  2208. "destinyElement" => null,
  2209. "destinyKilometers" => null
  2210. ], $form['code_type'], $form['hierarchy'], $eqpa);
  2211. // Se verifica que el código pregenerado en Angular y el pregenerado en Laravel
  2212. if($codeVerified != $preCode){
  2213. return $this->responseController->makeResponse(true, 'El código generado no coincide con el código verificado a partir de la información del formulario.', [], 400);
  2214. }
  2215. // Se verifica que la información del sfotware
  2216. $deso = isset($form['software_name']) ? $form['software_name'] : null;
  2217. $veso = isset($form['software_version']) ? $form['software_version'] : null;
  2218. // Se obtiene la fecha actual
  2219. $now = $this->functionsController->now();
  2220. $nowStr = $now->toDateTimeString();
  2221. $arrPreCodification = array();
  2222. $numberItems = intval($form['number_items']);
  2223. for ($i=0; $i < $numberItems; $i++) {
  2224. // Se ingresa la información a la tabla de los precódigos de los equipamientos
  2225. $idPreCodification = DB::table('S002V01TPCEQ')->insertGetId([
  2226. 'PCEQ_NULI' => $form['linea'],
  2227. 'PCEQ_CPGE' => $preCode,
  2228. 'PCEQ_JERA' => $form['hierarchy'],
  2229. 'PCEQ_EQPA' => $eqpa,
  2230. 'PCEQ_TICO' => $form['code_type'],
  2231. 'PCEQ_UBOR' => $originLocation,
  2232. 'PCEQ_NIOR' => $originLevel,
  2233. 'PCEQ_OCOR' => $originOccupationStr,
  2234. 'PCEQ_ELOR' => $form['origin_element'],
  2235. 'PCEQ_ALMA' => $idWarehouse,
  2236. 'PCEQ_AREA' => $idArea,
  2237. 'PCEQ_NIVE' => $idLevel,
  2238. 'PCEQ_ZONA' => $idZone,
  2239. 'PCEQ_FAMI' => $familyCode,
  2240. 'PCEQ_SUBF' => $subfamilyCode,
  2241. 'PCEQ_ESEQ' => $status,
  2242. 'PCEQ_TIEQ' => $form['equipment_type'],
  2243. 'PCEQ_MOEQ' => $form['equipment_model'],
  2244. 'PCEQ_IPCC' => null,
  2245. 'PCEQ_PPCC' => null,
  2246. 'PCEQ_KIOR' => 0.0,
  2247. 'PCEQ_UBDE' => '',
  2248. 'PCEQ_NIDE' => '',
  2249. 'PCEQ_OCDE' => '',
  2250. 'PCEQ_ELDE' => '',
  2251. 'PCEQ_KIDE' => 0.0,
  2252. 'PCEQ_FEAD' => $form['acquisition_date'],
  2253. 'PCEQ_FIGA' => $form['warranty_start_date'],
  2254. 'PCEQ_FTGA' => $form['warranty_end_date'],
  2255. 'PCEQ_PREQ' => $providerID,
  2256. 'PCEQ_NUSE' => count($arrSerialNumber) === 1 ? $arrSerialNumber[0] : $arrSerialNumber[$i],
  2257. 'PCEQ_DESO' => $deso,
  2258. 'PCEQ_VESO' => $veso,
  2259. 'PCEQ_GAIM' => $imagesGalleryStr,
  2260. 'PCEQ_DORE' => $documentsStr,
  2261. 'PCEQ_USRE' => $idUser,
  2262. 'PCEQ_FERE' => $nowStr,
  2263. ]);
  2264. $idPreCodification = $this->encryptionController->encrypt($idPreCodification);
  2265. $arrPreCodification[] = $idPreCodification;
  2266. }
  2267. $actions = DB::getQueryLog();
  2268. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2269. $idac = $this->functionsController->registerActivity(
  2270. $form['linea'],
  2271. 'S002V01M07GEEQ',
  2272. 'S002V01F01ADEQ',
  2273. 'S002V01P11REEQ',
  2274. 'Registro',
  2275. "El usuario $name (" . $usr->USUA_IDUS . ") solicitó el registro del equipamiento $preCode.",
  2276. $idUser,
  2277. $nowStr,
  2278. );
  2279. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2280. return $this->responseController->makeResponse(false, 'EXITO.', $arrPreCodification);
  2281. }
  2282. public function verifyPreCode(array $parameters, string $type, string $mode, string | null $parentCode = '') : string {
  2283. $code = "";
  2284. if($mode == 'Hijo'){
  2285. $code .= $parentCode;
  2286. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2287. $equipmentStr = "";
  2288. foreach($equipment as $ctrl){
  2289. $val = $parameters[$ctrl];
  2290. if($ctrl == 'equipmentModel'){
  2291. $val = $this->processElement($val, 'model');
  2292. }else if($ctrl == 'equipmentType'){
  2293. $val = $this->processElement($val, 'element');
  2294. }
  2295. $equipmentStr .= $val . '-';
  2296. }
  2297. $equipmentStr = substr($equipmentStr, 0, -1);
  2298. $code .= "." . $equipmentStr;
  2299. }else{
  2300. switch($type){
  2301. case "1":
  2302. //CASO 1: Codificación general
  2303. $lbs = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement'];
  2304. $lbsStr = "";
  2305. foreach($lbs as $ctrl){
  2306. $val = $parameters[$ctrl];
  2307. if($ctrl == 'line'){
  2308. $val = intval($val) < 10 ? "0$val" : "$val";
  2309. }else if($ctrl == 'originElement'){
  2310. $val = $this->processElement($val, 'element');
  2311. }
  2312. $lbsStr .= $val . ".";
  2313. }
  2314. $lbsStr = substr($lbsStr, 0, -1);
  2315. $pbs = ['family', 'subfamily', 'status'];
  2316. $pbsStr = "";
  2317. foreach($pbs as $ctrl){
  2318. $val = $parameters[$ctrl];
  2319. $pbsStr .= $val . ".";
  2320. }
  2321. $pbsStr = substr($pbsStr, 0, -1);
  2322. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2323. $equipmentStr = "";
  2324. foreach($equipment as $ctrl){
  2325. $val = $parameters[$ctrl];
  2326. if($ctrl == 'equipmentModel'){
  2327. $val = $this->processElement($val, 'model');
  2328. }else if($ctrl == 'equipmentType'){
  2329. $val = $this->processElement($val, 'element');
  2330. }
  2331. $equipmentStr .= $val . '-';
  2332. }
  2333. $equipmentStr = substr($equipmentStr, 0, -1);
  2334. $code = $lbsStr . "_" . $pbsStr . "." . $equipmentStr;
  2335. break;
  2336. case "2":
  2337. // CASO 2: Elemento en PCC
  2338. $lbs = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'pccIntersection', 'pccPosition'];
  2339. $lbsStr = "";
  2340. foreach($lbs as $ctrl){
  2341. $val = $parameters[$ctrl];
  2342. if($ctrl == 'line'){
  2343. $val = intval($val) < 10 ? "0$val" : "$val";
  2344. }else if($ctrl == 'originElement'){
  2345. $elementArr = explode(' - ', $val);
  2346. if(count($elementArr) > 1){
  2347. $elementCode = $elementArr[1];
  2348. $pccElementFilt = array_filter($this->pccValidElements, function($v, $k) use ($elementCode) {
  2349. return $elementCode == $v['code'];
  2350. }, ARRAY_FILTER_USE_BOTH);
  2351. if(count($pccElementFilt) > 0){
  2352. $pccElement = end($pccElementFilt);
  2353. $val = $pccElement['code'];
  2354. }
  2355. }
  2356. }
  2357. $lbsStr .= $val . ".";
  2358. }
  2359. $lbsStr = substr($lbsStr, 0, -1);
  2360. $pbs = ['family', 'subfamily', 'status'];
  2361. $pbsStr = "";
  2362. foreach($pbs as $ctrl){
  2363. $val = $parameters[$ctrl];
  2364. $pbsStr .= $val . ".";
  2365. }
  2366. $pbsStr = substr($pbsStr, 0, -1);
  2367. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2368. $equipmentStr = "";
  2369. foreach($equipment as $ctrl){
  2370. $val = $parameters[$ctrl];
  2371. if($ctrl == 'equipmentModel'){
  2372. $val = $this->processElement($val, 'model');
  2373. }else if($ctrl == 'equipmentType'){
  2374. $val = $this->processElement($val, 'element');
  2375. }
  2376. $equipmentStr .= $val . '-';
  2377. }
  2378. $equipmentStr = substr($equipmentStr, 0, -1);
  2379. $code = $lbsStr . "_" . $pbsStr . "." . $equipmentStr;
  2380. break;
  2381. case "3":
  2382. // CASO 3: Origen - destino para líneas y enlaces
  2383. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'originKilometers'];
  2384. $lbsOriginTag = "";
  2385. foreach($lbsOrigin as $ctrl){
  2386. $val = $parameters[$ctrl];
  2387. if($ctrl == 'line'){
  2388. $val = intval($val) < 10 ? "0$val" : "$val";
  2389. }else if($ctrl == 'originElement'){
  2390. $val = $this->processElement($val, 'element');
  2391. }else if($ctrl == 'originKilometers'){
  2392. $valArr = explode('.', $val);
  2393. $val = implode(',', $valArr);
  2394. }
  2395. $lbsOriginTag .= $val . ".";
  2396. }
  2397. $lbsOriginTag = substr($lbsOriginTag, 0, -1);
  2398. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'destinyElement', 'destinyKilometers'];
  2399. $lbsDestinyTag = "";
  2400. foreach($lbsDestiny as $ctrl){
  2401. $val = $parameters[$ctrl];
  2402. if($ctrl == 'line'){
  2403. $val = intval($val) < 10 ? "0$val" : "$val";
  2404. }else if($ctrl == 'destinyElement'){
  2405. $val = $this->processElement($val, 'element');
  2406. }else if($ctrl == 'destinyKilometers'){
  2407. $valArr = explode('.', $val);
  2408. $val = implode(',', $valArr);
  2409. }
  2410. $lbsDestinyTag .= $val . ".";
  2411. }
  2412. $lbsDestinyTag = substr($lbsDestinyTag, 0, -1);
  2413. $pbs = ['family', 'subfamily', 'status'];
  2414. $pbsStr = "";
  2415. foreach($pbs as $ctrl){
  2416. $val = $parameters[$ctrl];
  2417. $pbsStr .= $val . ".";
  2418. }
  2419. $pbsStr = substr($pbsStr, 0, -1);
  2420. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2421. $equipmentStr = "";
  2422. foreach($equipment as $ctrl){
  2423. $val = $parameters[$ctrl];
  2424. if($ctrl == 'equipmentModel'){
  2425. $val = $this->processElement($val, 'model');
  2426. }else if($ctrl == 'equipmentType'){
  2427. $val = $this->processElement($val, 'element');
  2428. }
  2429. $equipmentStr .= $val . '-';
  2430. }
  2431. $equipmentStr = substr($equipmentStr, 0, -1);
  2432. $code = "$lbsOriginTag:$lbsDestinyTag" . "_" . "$pbsStr.$equipmentStr";
  2433. break;
  2434. case "4":
  2435. // CASO 4: Origen - destino para estaciones y edificios
  2436. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'originElementSecuence'];
  2437. $lbsOriginTag = "";
  2438. foreach($lbsOrigin as $ctrl){
  2439. $val = $parameters[$ctrl];
  2440. if($ctrl == 'line'){
  2441. $val = intval($val) < 10 ? "0$val" : "$val";
  2442. }else if($ctrl == 'originElement'){
  2443. $val = $this->processElement($val, 'element');
  2444. }else if($ctrl == 'originElementSecuence'){
  2445. $valStr = "$val";
  2446. $valLength = strlen($valStr);
  2447. $valStrAux = "";
  2448. for($i = $valLength; $i < 6; $i++){
  2449. $valStrAux .= "0";
  2450. }
  2451. $val = "$valStrAux$valStr";
  2452. }
  2453. $lbsOriginTag .= $val . ".";
  2454. }
  2455. $lbsOriginTag = substr($lbsOriginTag, 0, -1);
  2456. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'destinyElement', 'destinyElementSecuence'];
  2457. $lbsDestinyTag = "";
  2458. foreach($lbsDestiny as $ctrl){
  2459. $val = $parameters[$ctrl];
  2460. if($ctrl == 'line'){
  2461. $val = intval($val) < 10 ? "0$val" : "$val";
  2462. }else if($ctrl == 'destinyElement'){
  2463. $val = $this->processElement($val, 'element');
  2464. }else if($ctrl == 'destinyElementSecuence'){
  2465. $valStr = "$val";
  2466. $valLength = strlen($valStr);
  2467. $valStrAux = "";
  2468. for($i = $valLength; $i < 6; $i++){
  2469. $valStrAux .= "0";
  2470. }
  2471. $val = "$valStrAux$valStr";
  2472. }
  2473. $lbsDestinyTag .= $val . ".";
  2474. }
  2475. $lbsDestinyTag = substr($lbsDestinyTag, 0, -1);
  2476. $pbs = ['family', 'subfamily', 'status'];
  2477. $pbsStr = "";
  2478. foreach($pbs as $ctrl){
  2479. $val = $parameters[$ctrl];
  2480. $pbsStr .= $val . ".";
  2481. }
  2482. $pbsStr = substr($pbsStr, 0, -1);
  2483. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2484. $equipmentStr = "";
  2485. foreach($equipment as $ctrl){
  2486. $val = $parameters[$ctrl];
  2487. if($ctrl == 'equipmentModel'){
  2488. $val = $this->processElement($val, 'model');
  2489. }else if($ctrl == 'equipmentType'){
  2490. $val = $this->processElement($val, 'element');
  2491. }
  2492. $equipmentStr .= $val . '-';
  2493. }
  2494. $equipmentStr = substr($equipmentStr, 0, -1);
  2495. $code = "$lbsOriginTag:$lbsDestinyTag" . "_" . "$pbsStr.$equipmentStr";
  2496. break;
  2497. case "5":
  2498. // CASO 4: Tren
  2499. $lbs = ['line', 'originLocation', 'originLevel', 'originOccupation', 'trainArea', 'originElement'];
  2500. $lbsStr = "";
  2501. foreach($lbs as $ctrl){
  2502. $val = $parameters[$ctrl];
  2503. if($ctrl == 'line'){
  2504. $val = intval($val) < 10 ? "0$val" : "$val";
  2505. }
  2506. $lbsStr .= $val . ".";
  2507. }
  2508. $lbsStr = substr($lbsStr, 0, -1);
  2509. $pbs = ['family', 'subfamily', 'status'];
  2510. $pbsStr = "";
  2511. foreach($pbs as $ctrl){
  2512. $val = $parameters[$ctrl];
  2513. $pbsStr .= $val . ".";
  2514. }
  2515. $pbsStr = substr($pbsStr, 0, -1);
  2516. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2517. $equipmentStr = "";
  2518. foreach($equipment as $ctrl){
  2519. $val = $parameters[$ctrl];
  2520. if($ctrl == 'equipmentModel'){
  2521. $val = $this->processElement($val, 'model');
  2522. }else if($ctrl == 'equipmentType'){
  2523. $val = $this->processElement($val, 'element');
  2524. }
  2525. $equipmentStr .= $val . '-';
  2526. }
  2527. $equipmentStr = substr($equipmentStr, 0, -1);
  2528. $code = $lbsStr . "_" . $pbsStr . "." . $equipmentStr;
  2529. break;
  2530. case "6":
  2531. $lbsOrigin = [];
  2532. if($parameters['originCodeType'] == '1'){
  2533. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'originElementSecuence'];
  2534. }else if($parameters['originCodeType'] == '2'){
  2535. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'pccIntersection',
  2536. 'pccPosition', 'originElementSecuence'];
  2537. }else if($parameters['originCodeType'] == '3'){
  2538. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'originKilometers'];
  2539. }else if($parameters['originCodeType'] == '4'){
  2540. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'originElement', 'originElementSecuence'];
  2541. }else if($parameters['originCodeType'] == '5'){
  2542. $lbsOrigin = ['line', 'originLocation', 'originLevel', 'originOccupation', 'trainArea', 'originElement', 'originElementSecuence'];
  2543. }
  2544. $lbsOriginTag = "";
  2545. foreach($lbsOrigin as $ctrl){
  2546. $val = $parameters[$ctrl];
  2547. if($ctrl == 'line'){
  2548. $val = intval($val) < 10 ? "0$val" : "$val";
  2549. }else if($ctrl == 'originElement' && $parameters['originCodeType'] != '5'){
  2550. $val = $this->processElement($val, 'element');
  2551. }else if($ctrl == 'originElementSecuence'){
  2552. $valStr = "$val";
  2553. $valLength = strlen($valStr);
  2554. $valStrAux = "";
  2555. for($i = $valLength; $i < 6; $i++){
  2556. $valStrAux .= "0";
  2557. }
  2558. $val = "$valStrAux$valStr";
  2559. }
  2560. $lbsOriginTag .= $val . ".";
  2561. }
  2562. $lbsOriginTag = substr($lbsOriginTag, 0, -1);
  2563. $lbsDestiny = [];
  2564. if($parameters['destinyCodeType'] == '1'){
  2565. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'destinyElement', 'destinyElementSecuence'];
  2566. }else if($parameters['destinyCodeType'] == '2'){
  2567. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'destinyElement', 'pccIntersection',
  2568. 'pccPosition', 'destinyElementSecuence'];
  2569. }else if($parameters['destinyCodeType'] == '3'){
  2570. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'destinyElement', 'destinyKilometers'];
  2571. }else if($parameters['destinyCodeType'] == '4'){
  2572. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'destinyElement', 'destinyElementSecuence'];
  2573. }else if($parameters['destinyCodeType'] == '5'){
  2574. $lbsDestiny = ['destinyLocation', 'destinyLevel', 'destinyOccupation', 'trainArea', 'destinyElement', 'destinyElementSecuence'];
  2575. }
  2576. $lbsDestinyTag = "";
  2577. foreach($lbsDestiny as $ctrl){
  2578. $val = $parameters[$ctrl];
  2579. if($ctrl == 'line'){
  2580. $val = intval($val) < 10 ? "0$val" : "$val";
  2581. }else if($ctrl == 'destinyElement' && $parameters['destinyCodeType'] != '5'){
  2582. $val = $this->processElement($val, 'element');
  2583. }else if($ctrl == 'destinyElementSecuence'){
  2584. $valStr = "$val";
  2585. $valLength = strlen($valStr);
  2586. $valStrAux = "";
  2587. for($i = $valLength; $i < 6; $i++){
  2588. $valStrAux .= "0";
  2589. }
  2590. $val = "$valStrAux$valStr";
  2591. }
  2592. $lbsDestinyTag .= $val . ".";
  2593. }
  2594. $lbsDestinyTag = substr($lbsDestinyTag, 0, -1);
  2595. $pbs = ['family', 'subfamily', 'status'];
  2596. $pbsStr = "";
  2597. foreach($pbs as $ctrl){
  2598. $val = $parameters[$ctrl];
  2599. $pbsStr .= $val . ".";
  2600. }
  2601. $pbsStr = substr($pbsStr, 0, -1);
  2602. $equipment = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2603. $equipmentStr = "";
  2604. foreach($equipment as $ctrl){
  2605. $val = $parameters[$ctrl];
  2606. if($ctrl == 'equipmentModel'){
  2607. $val = $this->processElement($val, 'model');
  2608. }else if($ctrl == 'equipmentType'){
  2609. $val = $this->processElement($val, 'element');
  2610. }
  2611. $equipmentStr .= $val . '-';
  2612. }
  2613. $equipmentStr = substr($equipmentStr, 0, -1);
  2614. $code = "$lbsOriginTag:$lbsDestinyTag" . "_" . "$pbsStr.$equipmentStr";
  2615. break;
  2616. case "7":
  2617. $siteTag = '';
  2618. $site = ['line', 'area', 'level'];
  2619. foreach($site as $ctrl){
  2620. $val = $parameters[$ctrl];
  2621. if($ctrl == 'line'){
  2622. $val = intval($val) < 10 ? "0$val" : "$val";
  2623. }
  2624. $siteTag .= $val.'.';
  2625. }
  2626. $siteTag = substr($siteTag, 0, -1);
  2627. $areaTag = '';
  2628. $area = ['warehouse', 'zone'];
  2629. foreach($area as $ctrl){
  2630. $val = $parameters[$ctrl];
  2631. $areaTag .= $val.'.';
  2632. }
  2633. $areaTag = substr($areaTag, 0, -1);
  2634. $technicalSpecificationTag = '';
  2635. $technicalSpecification = ['family', 'subfamily', 'status'];
  2636. foreach($technicalSpecification as $ctrl){
  2637. $val = $parameters[$ctrl];
  2638. $technicalSpecificationTag .= $val.'.';
  2639. }
  2640. $technicalSpecificationTag = substr($technicalSpecificationTag, 0, -1);
  2641. $equipmentIdentifierTag = '';
  2642. $equipmentIdentifier = ['equipmentType', 'equipmentModel', 'equipmentID'];
  2643. foreach($equipmentIdentifier as $ctrl){
  2644. $val = $parameters[$ctrl];
  2645. if($ctrl == 'equipmentModel'){
  2646. $val = $this->processElement($val, 'model');
  2647. }else if($ctrl == 'equipmentType'){
  2648. $val = $this->processElement($val, 'element');
  2649. }
  2650. $equipmentIdentifierTag .= $val.'-';
  2651. }
  2652. $equipmentIdentifierTag = substr($equipmentIdentifierTag, 0, -1);
  2653. $code = $siteTag.'-'.$areaTag.'_'.$technicalSpecificationTag.'.'.$equipmentIdentifierTag;
  2654. break;
  2655. }
  2656. }
  2657. return $code;
  2658. }
  2659. private function processElement(string $value, string $type) : string {
  2660. $value = strtoupper($value);
  2661. $validVal0 = $this->functionsController->unaccent($value);
  2662. $validVal0 = strtoupper($validVal0);
  2663. $validVal0 = str_replace('-', '', $validVal0);
  2664. $CONNECTORS = ['DE', 'PARA', 'Y', 'O', 'DEL', 'EL', 'LA', 'LOS', 'POR', 'EN'];
  2665. $valueArr1 = explode(' ', $validVal0);
  2666. $validVal1 = [];
  2667. foreach($valueArr1 as $word){
  2668. if(!in_array($word, $CONNECTORS)){
  2669. $validVal1[] = $word;
  2670. }
  2671. }
  2672. $validLength = count($validVal1);
  2673. $validVal2 = "";
  2674. if($validLength < 1){
  2675. return "ERROR";
  2676. }else if($validLength == 1){
  2677. if(strlen($validVal1[0]) < 5){
  2678. $validVal2 = $validVal1[0];
  2679. for($i = strlen($validVal1[0]); $i < 5; $i++){
  2680. if($type == 'model'){
  2681. $validVal2 = "X$validVal2";
  2682. }else{
  2683. $validVal2 = $validVal2 . "X";
  2684. }
  2685. }
  2686. }else{
  2687. $validVal2 = substr($validVal1[0], 0, 5);
  2688. }
  2689. }else if($validLength == 2){
  2690. $word1 = "";
  2691. if(strlen($validVal1[0]) < 2){
  2692. if($type == 'model'){
  2693. $word1 = "X$validVal1[0]";
  2694. }else{
  2695. $word1 = $validVal1[0] . "X";
  2696. }
  2697. }else{
  2698. $word1 = substr($validVal1[0], 0, 2);
  2699. }
  2700. $word2 = "";
  2701. if(strlen($validVal1[1]) < 3){
  2702. $word2 = $validVal1[1];
  2703. for($i = strlen($validVal1[1]); $i < 3; $i++){
  2704. if($type == 'model'){
  2705. $word2 = "X$word2";
  2706. }else{
  2707. $word2 = $word2 . "X";
  2708. }
  2709. }
  2710. }else{
  2711. $word2 = substr($validVal1[1], 0, 3);
  2712. }
  2713. $validVal2 = $word1 . $word2;
  2714. }else if($validLength == 3){
  2715. $word1 = "";
  2716. if(strlen($validVal1[0]) < 2){
  2717. if($type == 'model'){
  2718. $word1 = "X$validVal1[0]";
  2719. }else{
  2720. $word1 = $validVal1[0] . "X";
  2721. }
  2722. }else{
  2723. $word1 = substr($validVal1[0], 0, 2);
  2724. }
  2725. $word2 = substr($validVal1[1], 0, 1);
  2726. $word3 = "";
  2727. if(strlen($validVal1[2]) < 2){
  2728. if($type == 'model'){
  2729. $word3 = "X$validVal1[2]";
  2730. }else{
  2731. $word3 = $validVal1[2] . "X";
  2732. }
  2733. }else{
  2734. $word3 = substr($validVal1[2], 0, 2);
  2735. }
  2736. $validVal2 = $word1 . $word2 . $word3;
  2737. }else if($validLength == 4){
  2738. $word1 = "";
  2739. if(strlen($validVal1[0]) < 2){
  2740. if($type == 'model'){
  2741. $word1 = "X$validVal1[0]";
  2742. }else{
  2743. $word1 = $validVal1[0] . "X";
  2744. }
  2745. }else{
  2746. $word1 = substr($validVal1[0], 0, 2);
  2747. }
  2748. $word2 = substr($validVal1[1], 0, 1);
  2749. $word3 = substr($validVal1[2], 0, 1);
  2750. $word4 = substr($validVal1[3], 0, 1);
  2751. $validVal2 = $word1 . $word2 . $word3 . $word4;
  2752. }else if($validLength >= 5){
  2753. $word1 = substr($validVal1[0], 0, 1);
  2754. $word2 = substr($validVal1[1], 0, 1);
  2755. $word3 = substr($validVal1[2], 0, 1);
  2756. $word4 = substr($validVal1[3], 0, 1);
  2757. $word5 = substr($validVal1[4], 0, 1);
  2758. $validVal2 = $word1 . $word2 . $word3 . $word4 . $word5;
  2759. }else{
  2760. return "ERROR";
  2761. }
  2762. return $validVal2;
  2763. }
  2764. public function getPendigEquipments($idUser, $line) {
  2765. DB::enableQueryLog();
  2766. $idUser = $this->encryptionController->decrypt($idUser);
  2767. if(!$idUser){
  2768. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  2769. }
  2770. $usr = DB::table('S002V01TUSUA')->where([
  2771. ['USUA_NULI', '=', $line],
  2772. ['USUA_IDUS', '=', $idUser],
  2773. ])->first();
  2774. if(is_null($usr)){
  2775. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  2776. }
  2777. $pendingEquipments = DB::table('S002V01TPCEQ')->select([
  2778. 'PCEQ_IDPR AS IDREG',
  2779. 'PCEQ_CPGE AS CODIGO',
  2780. 'PCEQ_TICO AS TIPO_CODIGO',
  2781. 'PCEQ_TIEQ AS TIPO_EQUIPAMIENTO',
  2782. 'PCEQ_MOEQ AS MODELO_EQUIPAMIENTO',
  2783. 'PCEQ_GAIM AS GALERIA_IMAGENES',
  2784. 'PCEQ_ESRE AS ESTADO_REGISTRO',
  2785. ])->where([
  2786. ['PCEQ_NULI', '=', $line],
  2787. ['PCEQ_ESRE', '=', 'Revisión'],
  2788. ])->get()->all();
  2789. $idUserEnc = $this->encryptionController->encrypt($idUser);
  2790. foreach($pendingEquipments as $key=>$equipment){
  2791. $equipment->IDREG = $this->encryptionController->encrypt($equipment->IDREG);
  2792. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  2793. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES);
  2794. $imagesGalleryFn = [];
  2795. foreach($imagesGalleryArr as $imageCode){
  2796. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  2797. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  2798. $imageCodeEnc,
  2799. $idUserEnc,
  2800. $line
  2801. );
  2802. $response = json_decode($publicUri->original, true);
  2803. if($response['error']){
  2804. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  2805. }else{
  2806. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  2807. $imagesGalleryFn[] = $uriEnc;
  2808. }
  2809. }
  2810. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  2811. $equipment->TIPO_EQUIPAMIENTO = $this->encryptionController->encrypt($equipment->TIPO_EQUIPAMIENTO);
  2812. $equipment->MODELO_EQUIPAMIENTO = $this->encryptionController->encrypt($equipment->MODELO_EQUIPAMIENTO);
  2813. $pendingEquipments[$key] = $equipment;
  2814. }
  2815. $now = $this->functionsController->now();
  2816. $nowStr = $now->toDateTimeString();
  2817. $actions = DB::getQueryLog();
  2818. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2819. $idac = $this->functionsController->registerActivity(
  2820. $line,
  2821. 'S002V01M07GEEQ',
  2822. 'S002V01F01ADEQ',
  2823. '-',
  2824. 'Consulta',
  2825. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos en revisión.",
  2826. $idUser,
  2827. $nowStr,
  2828. );
  2829. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2830. return $this->responseController->makeResponse(false, 'EXITO.', $pendingEquipments);
  2831. }
  2832. public function getPendigEquipment($idReg, $idUser, $line) {
  2833. DB::enableQueryLog();
  2834. $idUser = $this->encryptionController->decrypt($idUser);
  2835. if(!$idUser){
  2836. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  2837. }
  2838. $usr = DB::table('S002V01TUSUA')->where([
  2839. ['USUA_NULI', '=', $line],
  2840. ['USUA_IDUS', '=', $idUser],
  2841. ])->first();
  2842. if(is_null($usr)){
  2843. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  2844. }
  2845. $idReg = $this->encryptionController->decrypt($idReg);
  2846. if(!$idReg){
  2847. return $this->responseController->makeResponse(true, 'El ID del pre-registro no está encriptado correctamente', [], 400);
  2848. }
  2849. $pendingEquipment = DB::table('S002V01TPCEQ')->select([
  2850. 'PCEQ_IDPR AS IDREG',
  2851. 'PCEQ_CPGE AS CODIGO',
  2852. 'PCEQ_JERA AS JERARQUIA',
  2853. 'PCEQ_EQPA AS PADRE',
  2854. 'PCEQ_TICO AS TIPO_CODIGO',
  2855. 'PCEQ_UBOR AS UBICACION_ORIGEN',
  2856. 'PCEQ_NIOR AS NIVEL_ORIGEN',
  2857. 'PCEQ_OCOR AS OCUPACION_ORIGEN',
  2858. 'PCEQ_ELOR AS ELEMENTO_ORIGEN',
  2859. 'PCEQ_FAMI AS FAMILIA',
  2860. 'PCEQ_SUBF AS SUBFAMILIA',
  2861. 'PCEQ_ESEQ AS ESTADO_EQUIPAMIENTO',
  2862. 'PCEQ_TIEQ AS TIPO_EQUIPAMIENTO',
  2863. 'PCEQ_MOEQ AS MODELO_EQUIPAMIENTO',
  2864. 'PCEQ_IPCC AS INTERSECCION_PCC',
  2865. 'PCEQ_PPCC AS POSICION_PCC',
  2866. 'PCEQ_KIOR AS KILOMETRO_ORIGEN',
  2867. 'PCEQ_UBDE AS UBICACION_DESTINO',
  2868. 'PCEQ_NIDE AS NIVEL_DESTINO',
  2869. 'PCEQ_OCDE AS OCUPACION_DESTINO',
  2870. 'PCEQ_ELDE AS ELEMENTO_DESTINO',
  2871. 'PCEQ_KIDE AS KILOMETRO_DESTINO',
  2872. 'PCEQ_FEAD AS FECHA_ADQUISICION',
  2873. 'PCEQ_FIGA AS FECHA_INICIO_GARANTIA',
  2874. 'PCEQ_FTGA AS FECHA_FIN_GARANTIA',
  2875. 'PCEQ_PREQ AS PROVEEDOR',
  2876. 'PCEQ_NUSE AS NUMERO_SERIAL',
  2877. 'PCEQ_DESO AS DENOMINACION_SOFTWARE',
  2878. 'PCEQ_VESO AS VERSION_SOFTWARE',
  2879. 'PCEQ_GAIM AS GALERIA_IMAGENES',
  2880. 'PCEQ_DORE AS DOCUMENTOS',
  2881. 'PCEQ_ESRE AS ESTADO_REGISTRO',
  2882. 'PCEQ_CORE AS COMENTARIOS_RECHAZO',
  2883. 'PCEQ_COAC AS COMENTARIOS_ACEPTACION',
  2884. 'PCEQ_USRE AS USUARIO_REGISTRO',
  2885. 'PCEQ_FERE AS FECHA_REGISTRO',
  2886. 'PCEQ_USMO AS USUARIO_MODIFICO',
  2887. 'PCEQ_FEMO AS FECHA_MODIFICACION'
  2888. ])->where([
  2889. ['PCEQ_NULI', '=', $line],
  2890. ['PCEQ_IDPR', '=', $idReg],
  2891. ['PCEQ_ESRE', '=', 'Revisión'],
  2892. ])->first();
  2893. if(is_null($pendingEquipment)){
  2894. return $this->responseController->makeResponse(true, 'El pre-registro solicitado no existe', [], 404);
  2895. }
  2896. $pendingEquipment->IDREG = $this->encryptionController->encrypt($pendingEquipment->IDREG);
  2897. $pendingEquipment->CODIGO = $this->encryptionController->encrypt($pendingEquipment->CODIGO);
  2898. $ubic = $this->templatesUbic;
  2899. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  2900. $locationsEnc = file_get_contents($ubic . "locations.sam");
  2901. $locationsDec = $this->encryptionController->decrypt($locationsEnc);
  2902. $locationsArr = json_decode($locationsDec, true);
  2903. $locationsArrDec = [];
  2904. foreach($locationsArr as $location){
  2905. $locationStr = $this->encryptionController->decrypt($location['LOCATION']);
  2906. $code = $this->encryptionController->decrypt($location['CODE']);
  2907. $locationsArrDec[] = [
  2908. 'LOCATION' => $locationStr,
  2909. 'CODE' => $code
  2910. ];
  2911. }
  2912. $originLocation = $pendingEquipment->UBICACION_ORIGEN;
  2913. $originLocationFilt = array_filter($locationsArrDec, function ($v, $k) use ($originLocation) {
  2914. return $v['CODE'] == $originLocation;
  2915. }, ARRAY_FILTER_USE_BOTH);
  2916. $pendingEquipment->UBICACION_ORIGEN = end($originLocationFilt)['LOCATION'] . " (" . $pendingEquipment->UBICACION_ORIGEN . ")";
  2917. $levelsArr = [];
  2918. for($i = 5; $i > 0; $i--){
  2919. $levelsArr[] = [
  2920. 'LEVEL' => "Subterráneo S0$i",
  2921. 'CODE' => "S0$i",
  2922. ];
  2923. }
  2924. for($i = 0; $i <= 15; $i++){
  2925. $code = $i < 10 ? "P0$i" : "P$i";
  2926. $level = $i == 0 ? "Planta baja P00" : "Piso $code";
  2927. $levelsArr[] = [
  2928. 'LEVEL' => $level,
  2929. 'CODE' => $code,
  2930. ];
  2931. }
  2932. $originLevel = $pendingEquipment->NIVEL_ORIGEN;
  2933. $originLevelFilt = array_filter($levelsArr, function ($v, $k) use ($originLevel) {
  2934. return $v['CODE'] == $originLevel;
  2935. }, ARRAY_FILTER_USE_BOTH);
  2936. $pendingEquipment->NIVEL_ORIGEN = end($originLevelFilt)['LEVEL'] . " (" . $pendingEquipment->NIVEL_ORIGEN . ")";
  2937. $originOccupationStr = $pendingEquipment->OCUPACION_ORIGEN;
  2938. $originOccupationArea = substr($originOccupationStr, 0, 2);
  2939. $originOccupationID = substr($originOccupationStr, 2);
  2940. $originOccupation = DB::table('S002V01TOCUP')->where([
  2941. ['OCUP_NULI', '=', $line],
  2942. ['OCUP_AREA', '=', $originOccupationArea],
  2943. ['OCUP_IDOC', '=', $originOccupationID]
  2944. ])->first();
  2945. $pendingEquipment->OCUPACION_ORIGEN = $originOccupation->OCUP_DESC . " (" . $originOccupationStr . ")";
  2946. $family = DB::table('S002V01TFAMI')->where([
  2947. ['FAMI_NULI', '=', $line],
  2948. ['FAMI_COFA', '=', $pendingEquipment->FAMILIA],
  2949. ])->first();
  2950. $subfamily = DB::table('S002V01TSUBF')->where([
  2951. ['SUBF_NULI', '=', $line],
  2952. ['SUBF_COFA', '=', $pendingEquipment->FAMILIA],
  2953. ['SUBF_COSU', '=', $pendingEquipment->SUBFAMILIA],
  2954. ])->first();
  2955. $pendingEquipment->FAMILIA = $family->FAMI_NOFA . " (" . $pendingEquipment->FAMILIA . ")";
  2956. $pendingEquipment->SUBFAMILIA = $subfamily->SUBF_NOSU . " (" . $pendingEquipment->SUBFAMILIA . ")";
  2957. $validStatus = ["A" => "Adquisición", "S" => "Stock", "T" => "Traslado", "I" => "Instalación", "R" => "Reparación", "D" => "Disposición"];
  2958. $pendingEquipment->ESTADO_EQUIPAMIENTO = $validStatus[$pendingEquipment->ESTADO_EQUIPAMIENTO] . " (" . $pendingEquipment->ESTADO_EQUIPAMIENTO . ")";
  2959. $idUserEnc = $this->encryptionController->encrypt($idUser);
  2960. $imagesGalleryArr = json_decode($pendingEquipment->GALERIA_IMAGENES);
  2961. $imagesGalleryFn = [];
  2962. foreach($imagesGalleryArr as $imageCode){
  2963. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  2964. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  2965. $imageCodeEnc,
  2966. $idUserEnc,
  2967. $line
  2968. );
  2969. $response = json_decode($publicUri->original, true);
  2970. if($response['error']){
  2971. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  2972. }else{
  2973. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  2974. $imagesGalleryFn[] = $uriEnc;
  2975. }
  2976. }
  2977. $documentsArr = json_decode($pendingEquipment->DOCUMENTOS);
  2978. $documentsFn = [];
  2979. foreach($documentsArr as $document){
  2980. $codeArr = explode('=',$document);
  2981. $codeArr0 = explode('-', $codeArr[0]);
  2982. $file = DB::table('S002V01TAFAL')->where([
  2983. ['AFAL_NULI', '=', $line],
  2984. ['AFAL_COMO', '=', $codeArr0[1]],
  2985. ['AFAL_CLDO', '=', $codeArr0[2]],
  2986. ['AFAL_FECR', '=', $codeArr0[3]],
  2987. ['AFAL_NUSE', '=', $codeArr0[4]],
  2988. ['AFAL_NUVE', '=', $codeArr[1]],
  2989. ])->first();
  2990. if(is_null($file)){
  2991. return $this->responseController->makeResponse(true, "El archivo $document no está registrado.", [], 404);
  2992. }
  2993. $documentsFn[] = [
  2994. 'id' => $this->encryptionController->encrypt($document),
  2995. 'name' => $document,
  2996. 'size' => $file->AFAL_TAMA
  2997. ];
  2998. }
  2999. $pendingEquipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  3000. $pendingEquipment->DOCUMENTOS = json_encode($documentsFn);
  3001. $pendingEquipment->PROVEEDOR = $this->encryptionController->encrypt($pendingEquipment->PROVEEDOR);
  3002. $pendingEquipment->NUMERO_SERIAL = $this->encryptionController->encrypt($pendingEquipment->NUMERO_SERIAL);
  3003. $usrReg = DB::table('S002V01TUSUA')->where([
  3004. ['USUA_NULI', '=', $line],
  3005. ['USUA_IDUS', '=', $pendingEquipment->USUARIO_REGISTRO]
  3006. ])->first();
  3007. $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  3008. $pendingEquipment->USUARIO_REGISTRO = $usrRegName . " (" . $pendingEquipment->USUARIO_REGISTRO . ")";
  3009. if(!is_null($pendingEquipment->USUARIO_MODIFICO)){
  3010. $usrMod = DB::table('S002V01TUSUA')->where([
  3011. ['USUA_NULI', '=', $line],
  3012. ['USUA_IDUS', '=', $pendingEquipment->USUARIO_MODIFICO]
  3013. ])->first();
  3014. $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  3015. $pendingEquipment->USUARIO_MODIFICO = $usrModName . " (" . $pendingEquipment->USUARIO_MODIFICO . ")";
  3016. }
  3017. $pendingEquipment->TIPO_EQUIPAMIENTO = $this->encryptionController->encrypt($pendingEquipment->TIPO_EQUIPAMIENTO);
  3018. $pendingEquipment->MODELO_EQUIPAMIENTO = $this->encryptionController->encrypt($pendingEquipment->MODELO_EQUIPAMIENTO);
  3019. $now = $this->functionsController->now();
  3020. $nowStr = $now->toDateTimeString();
  3021. $actions = DB::getQueryLog();
  3022. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3023. $idac = $this->functionsController->registerActivity(
  3024. $line,
  3025. 'S002V01M07GEEQ',
  3026. 'S002V01F01ADEQ',
  3027. '-',
  3028. 'Consulta',
  3029. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el equipamiento pre codificado $idReg.",
  3030. $idUser,
  3031. $nowStr,
  3032. );
  3033. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3034. return $this->responseController->makeResponse(false, 'EXITO.', $pendingEquipment);
  3035. }
  3036. public function changePreCodedEquipmentStatus(Request $request) {
  3037. DB::enableQueryLog();
  3038. $validator = Validator::make($request->all(), [
  3039. 'id_user' => 'required|string',
  3040. 'linea' => 'required|integer',
  3041. 'id_reg' => 'required|string',
  3042. 'status' => 'required|string|in:Aprobado,Rechazado',
  3043. 'comments' => 'required|string|min:15',
  3044. ]);
  3045. if($validator->fails()){
  3046. return $this->responseController->makeResponse(
  3047. true,
  3048. "Se encontraron uno o más errores.",
  3049. $this->responseController->makeErrors(
  3050. $validator->errors()->messages()
  3051. ),
  3052. 401
  3053. );
  3054. }
  3055. $form = $request->all();
  3056. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3057. if(!$idUser){
  3058. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  3059. }
  3060. $usr = DB::table('S002V01TUSUA')->where([
  3061. ['USUA_NULI', '=', $form['linea']],
  3062. ['USUA_IDUS', '=', $idUser]
  3063. ])->first();
  3064. if(is_null($usr)){
  3065. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  3066. }
  3067. $idReg = $this->encryptionController->decrypt($form['id_reg']);
  3068. if(!$idReg){
  3069. return $this->responseController->makeResponse(true, 'El ID del pre-registro no está encriptado correctamente', [], 400);
  3070. }
  3071. $pendingEquipment = DB::table('S002V01TPCEQ')->where([
  3072. ['PCEQ_NULI', '=', $form['linea']],
  3073. ['PCEQ_IDPR', '=', $idReg],
  3074. ])->first();
  3075. if(is_null($pendingEquipment)){
  3076. return $this->responseController->makeResponse(true, 'El pre-registro solicitado no existe.', [], 404);
  3077. }else if($pendingEquipment->PCEQ_ESRE == 'Rechazado'){
  3078. return $this->responseController->makeResponse(true, 'El pre-registro se encuentra rechazado.', [], 400);
  3079. }else if($pendingEquipment->PCEQ_ESRE == 'Aprobado'){
  3080. return $this->responseController->makeResponse(true, 'El pre-registro se encuentra aprobado.', [], 400);
  3081. }
  3082. $now = $this->functionsController->now();
  3083. $nowStr = $now->toDateTimeString();
  3084. if($form['status'] == 'Rechazado'){
  3085. DB::table('S002V01TPCEQ')->where([
  3086. ['PCEQ_IDPR', '=', $idReg],
  3087. ['PCEQ_NULI', '=', $form['linea']],
  3088. ])->update([
  3089. 'PCEQ_ESRE' => $form['status'],
  3090. 'PCEQ_CORE' => $form['comments'],
  3091. 'PCEQ_USMO' => $idUser,
  3092. 'PCEQ_FEMO' => $nowStr,
  3093. ]);
  3094. }else{
  3095. //PASO 1: SE BUSCA EL ÚLTIMO ID DEL EQUIPAMIENTO
  3096. $lastID = DB::table('S002V01TEQUI')->select([
  3097. 'EQUI_IDEQ AS LAST_ID'
  3098. ])->where([
  3099. ['EQUI_NULI', '=', $form['linea']],
  3100. ['EQUI_FAMI', '=', $pendingEquipment->PCEQ_FAMI],
  3101. ['EQUI_SUBF', '=', $pendingEquipment->PCEQ_SUBF],
  3102. ['EQUI_TIPO', '=', $pendingEquipment->PCEQ_TIEQ],
  3103. ['EQUI_MODE', '=', $pendingEquipment->PCEQ_MOEQ],
  3104. ])->orderBy('EQUI_IDEQ', 'asc')->first();
  3105. //PASO 2: SE DEFINE EL ID DEL NUEVO EQUIPAMIENTO
  3106. $IDNum = is_null($lastID) ? 1 : $lastID->LAST_ID + 1;
  3107. //PASO 3: SE DEFINE UN ESPACIO PARA RETORNAR EL PROCESO
  3108. doAgain:
  3109. //PASO 4: SE RELLENA EL ID CON CEROS A LA IZQUIERDA PARA DARLE EL FORMATO DE LA CODIFICACIÓN
  3110. $IDStr = "$IDNum";
  3111. for($i = strlen($IDStr); $i < 6; $i++){
  3112. $IDStr = "0$IDStr";
  3113. }
  3114. //PASO 5: SE INTEGRA EL ID AL CÓDIGO PRE-GENERADO
  3115. $preCodeArr = explode('_', $pendingEquipment->PCEQ_CPGE);
  3116. $previewPBS = $preCodeArr[1];
  3117. $previewPBSArr = explode('-', $previewPBS);
  3118. $previewPBSArr = array_reverse($previewPBSArr);
  3119. $previewPBSArr[0] = $IDStr;
  3120. $previewPBSArr = array_reverse($previewPBSArr);
  3121. $previewPBS = implode('-', $previewPBSArr);
  3122. //PASO 6: SE BUSCA SI EL CÓDIGO ESTÁ REGISTRADO EN ALGÚN EQUIPAMIENTO O EN EL HISTORIAL DE CÓDIGOS DE ALGÚN EQUIPAMIENTO
  3123. $previewCode = $preCodeArr[0] . "_" . $previewPBS;
  3124. $registeredCode = DB::table('S002V01TEQUI')->where([
  3125. ['EQUI_NULI', '=', $form['linea']],
  3126. ['EQUI_COEQ', '=', $previewCode]
  3127. ])->first();
  3128. $codeInHistory = DB::table('S002V01TEQUI')
  3129. ->where('EQUI_NULI', '=', $form['linea'])
  3130. ->whereJsonContains('EQUI_HICO', $previewCode)->first();
  3131. //PASO 7: VERIFICAR QUE EL CÓDIGO NO EXISTA, SI EXISTE SE REALIZA NUEVAMENTE EL PROCESO AUMENTANDO EN 1 EL ID
  3132. if(!is_null($registeredCode) || !is_null($codeInHistory)){
  3133. $IDNum++;
  3134. goto doAgain;
  3135. }
  3136. //PASO 8: REALIZAR EL REGISTRO DEL EQUIPAMIENTO
  3137. $hico = json_encode([$previewCode]);
  3138. DB::table('S002V01TEQUI')->insert([
  3139. 'EQUI_NULI' => $form['linea'],
  3140. 'EQUI_FAMI' => $pendingEquipment->PCEQ_FAMI,
  3141. 'EQUI_SUBF' => $pendingEquipment->PCEQ_SUBF,
  3142. 'EQUI_TIPO' => $pendingEquipment->PCEQ_TIEQ,
  3143. 'EQUI_MODE' => $pendingEquipment->PCEQ_MOEQ,
  3144. 'EQUI_IDEQ' => $IDNum,
  3145. 'EQUI_ESEQ' => $pendingEquipment->PCEQ_ESEQ,
  3146. 'EQUI_COEQ' => $previewCode,
  3147. 'EQUI_JERA' => $pendingEquipment->PCEQ_JERA,
  3148. 'EQUI_EQPA' => $pendingEquipment->PCEQ_EQPA,
  3149. 'EQUI_TICO' => $pendingEquipment->PCEQ_TICO,
  3150. 'EQUI_UBOR' => $pendingEquipment->PCEQ_UBOR,
  3151. 'EQUI_NIOR' => $pendingEquipment->PCEQ_NIOR,
  3152. 'EQUI_OCOR' => $pendingEquipment->PCEQ_OCOR,
  3153. 'EQUI_ELOR' => $pendingEquipment->PCEQ_ELOR,
  3154. 'EQUI_ALMA' => $pendingEquipment->PCEQ_ALMA,
  3155. 'EQUI_AREA' => $pendingEquipment->PCEQ_AREA,
  3156. 'EQUI_NIVE' => $pendingEquipment->PCEQ_NIVE,
  3157. 'EQUI_ZONA' => $pendingEquipment->PCEQ_ZONA,
  3158. 'EQUI_IPCC' => $pendingEquipment->PCEQ_IPCC,
  3159. 'EQUI_PPCC' => $pendingEquipment->PCEQ_PPCC,
  3160. 'EQUI_KIOR' => $pendingEquipment->PCEQ_KIOR,
  3161. 'EQUI_SEOR' => $pendingEquipment->PCEQ_SEOR,
  3162. 'EQUI_ARTR' => $pendingEquipment->PCEQ_ARTR,
  3163. 'EQUI_TCOR' => $pendingEquipment->PCEQ_TCOR,
  3164. 'EQUI_CEOR' => $pendingEquipment->PCEQ_CEOR,
  3165. 'EQUI_UBDE' => $pendingEquipment->PCEQ_UBDE,
  3166. 'EQUI_NIDE' => $pendingEquipment->PCEQ_NIDE,
  3167. 'EQUI_OCDE' => $pendingEquipment->PCEQ_OCDE,
  3168. 'EQUI_ELDE' => $pendingEquipment->PCEQ_ELDE,
  3169. 'EQUI_KIDE' => $pendingEquipment->PCEQ_KIDE,
  3170. 'EQUI_SEDE' => $pendingEquipment->PCEQ_SEDE,
  3171. 'EQUI_TCDE' => $pendingEquipment->PCEQ_TCDE,
  3172. 'EQUI_CEDE' => $pendingEquipment->PCEQ_CEDE,
  3173. 'EQUI_FEAD' => $pendingEquipment->PCEQ_FEAD,
  3174. 'EQUI_FIGA' => $pendingEquipment->PCEQ_FIGA,
  3175. 'EQUI_FTGA' => $pendingEquipment->PCEQ_FTGA,
  3176. 'EQUI_PREQ' => $pendingEquipment->PCEQ_PREQ,
  3177. 'EQUI_NUSE' => $pendingEquipment->PCEQ_NUSE,
  3178. 'EQUI_DESO' => $pendingEquipment->PCEQ_DESO,
  3179. 'EQUI_VESO' => $pendingEquipment->PCEQ_VESO,
  3180. 'EQUI_HICO' => $hico,
  3181. 'EQUI_GAIM' => $pendingEquipment->PCEQ_GAIM,
  3182. 'EQUI_DORE' => $pendingEquipment->PCEQ_DORE,
  3183. 'EQUI_USRE' => $idUser,
  3184. 'EQUI_FERE' => $nowStr,
  3185. ]);
  3186. DB::table('S002V01TPCEQ')->where([
  3187. ['PCEQ_IDPR', '=', $idReg],
  3188. ['PCEQ_NULI', '=', $form['linea']],
  3189. ])->update([
  3190. 'PCEQ_ESRE' => $form['status'],
  3191. 'PCEQ_CORE' => $form['comments'],
  3192. 'PCEQ_USMO' => $idUser,
  3193. 'PCEQ_FEMO' => $nowStr,
  3194. ]);
  3195. }
  3196. if ($pendingEquipment->PCEQ_TICO === '7') {
  3197. try {
  3198. $star = (array) DB::table('S002V01TSTAR')
  3199. ->where('STAR_IDPC', '=', $pendingEquipment->PCEQ_IDPR)
  3200. ->where('STAR_ESTA', '=', 'Pendiente')
  3201. ->where('STAR_NULI', '=', $form['linea'])
  3202. ->first();
  3203. } catch (\Throwable $th) {
  3204. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los artículos en Stock.', [], 500);
  3205. }
  3206. if ( !empty($star) && !is_null($star) ) {
  3207. try {
  3208. $validateUpdate = DB::table('S002V01TSTAR')
  3209. ->where('STAR_IDPC', '=', $pendingEquipment->PCEQ_IDPR)
  3210. ->where('STAR_ESTA', '=', 'Pendiente')
  3211. ->where('STAR_NULI', '=', $form['linea'])
  3212. ->update([
  3213. 'STAR_ESTA' => 'Activo',
  3214. 'STAR_USMO' => $idUser,
  3215. 'STAR_FEMO' => $nowStr,
  3216. 'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  3217. ]);
  3218. } catch (\Throwable $th) {
  3219. return $this->responseController->makeResponse(true, 'Ocurrió un al actualizar el stock.', [], 500);
  3220. }
  3221. if (!$validateUpdate) {
  3222. return $this->responseController->makeResponse(true, 'No se pudo actualizar la información en stock.', [], 500);
  3223. }
  3224. try {
  3225. $validateUpdate = DB::table('S002V01TUBAR')
  3226. ->where('UBAR_IDST', '=', $star['STAR_IDST'])
  3227. ->where('UBAR_ESTA', '=', 'Pendiente')
  3228. ->where('UBAR_NULI', '=', $form['linea'])
  3229. ->update([
  3230. 'UBAR_COUB' => $previewCode,
  3231. 'UBAR_ESTA' => 'Activo',
  3232. 'UBAR_USMO' => $idUser,
  3233. 'UBAR_FEMO' => $nowStr,
  3234. 'UBAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  3235. ]);
  3236. } catch (\Throwable $th) {
  3237. return $this->responseController->makeResponse(true, 'Ocurrió un al actualizar el stock.', [], 500);
  3238. }
  3239. if (!$validateUpdate) {
  3240. return $this->responseController->makeResponse(true, 'No se pudo actualizar la información en stock.', [], 500);
  3241. }
  3242. }
  3243. }
  3244. $actions = DB::getQueryLog();
  3245. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3246. $idac = $this->functionsController->registerActivity(
  3247. $form['linea'],
  3248. 'S002V01M07GEEQ',
  3249. 'S002V01F01ADEQ',
  3250. 'S002V01P11REEQ',
  3251. 'Registro',
  3252. "El usuario $name (" . $usr->USUA_IDUS . ") cambió el estado del pre-registro $idReg a $form[status].",
  3253. $idUser,
  3254. $nowStr,
  3255. );
  3256. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3257. return $this->responseController->makeResponse(false, 'EXITO.');
  3258. }
  3259. public function getEquipments($idUser, $line) {
  3260. DB::enableQueryLog();
  3261. $idUser = $this->encryptionController->decrypt($idUser);
  3262. if(!$idUser){
  3263. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3264. }
  3265. $usr = DB::table('S002V01TUSUA')->where([
  3266. ['USUA_NULI', '=', $line],
  3267. ['USUA_IDUS', '=', $idUser],
  3268. ])->first();
  3269. if(is_null($usr)){
  3270. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3271. }
  3272. $equipments = DB::table('S002V01TEQUI')->select([
  3273. 'EQUI_COEQ AS CODIGO',
  3274. 'EQUI_TIPO AS TIPO',
  3275. 'EQUI_MODE AS MODELO',
  3276. 'EQUI_IDEQ AS ID_EQUIPO',
  3277. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  3278. 'EQUI_GAIM AS GALERIA_IMAGENES',
  3279. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  3280. 'EQUI_TICO AS TIPO_CODIGO',
  3281. 'EQUI_EQPA AS EQUIPO_PADRE',
  3282. ])->where('EQUI_NULI', '=', $line)->get()->all();
  3283. $idUserEnc = $this->encryptionController->encrypt($idUser);
  3284. foreach($equipments as $key=>$equipment){
  3285. $children = DB::table('S002V01TEQUI')->where([
  3286. ['EQUI_NULI', '=', $line],
  3287. ['EQUI_EQPA', '=', $equipment->CODIGO],
  3288. ])->get()->all();
  3289. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  3290. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  3291. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  3292. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES, true);
  3293. $imagesGalleryFn = [];
  3294. foreach($imagesGalleryArr as $imageCode){
  3295. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  3296. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  3297. $imageCodeEnc,
  3298. $idUserEnc,
  3299. $line
  3300. );
  3301. $response = json_decode($publicUri->original, true);
  3302. if($response['error']){
  3303. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  3304. }else{
  3305. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  3306. $imagesGalleryFn[] = $uriEnc;
  3307. }
  3308. }
  3309. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  3310. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  3311. $equipments[$key] = $equipment;
  3312. }
  3313. $now = $this->functionsController->now();
  3314. $nowStr = $now->toDateTimeString();
  3315. $actions = DB::getQueryLog();
  3316. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3317. $idac = $this->functionsController->registerActivity(
  3318. $line,
  3319. 'S002V01M07GEEQ',
  3320. 'S002V01F01ADEQ',
  3321. 'S002V01P01MEEQ',
  3322. 'Consulta',
  3323. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos registrados.",
  3324. $idUser,
  3325. $nowStr,
  3326. );
  3327. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3328. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  3329. }
  3330. public function getEquipmentsBySubfamily($familyCode, $subfamilyCode, $idUser, $line) {
  3331. DB::enableQueryLog();
  3332. $idUser = $this->encryptionController->decrypt($idUser);
  3333. if(!$idUser){
  3334. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3335. }
  3336. $usr = DB::table('S002V01TUSUA')->where([
  3337. ['USUA_NULI', '=', $line],
  3338. ['USUA_IDUS', '=', $idUser],
  3339. ])->first();
  3340. if(is_null($usr)){
  3341. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3342. }
  3343. $familyCode = $this->encryptionController->decrypt($familyCode);
  3344. if(!$familyCode){
  3345. return $this->responseController->makeResponse(true, 'El código de la familia no está encriptado correctamente', [], 400);
  3346. }
  3347. $family = DB::table('S002V01TFAMI')->where([
  3348. ['FAMI_NULI', '=', $line],
  3349. ['FAMI_COFA', '=', $familyCode],
  3350. ])->first();
  3351. if(is_null($family)){
  3352. return $this->responseController->makeResponse(true, 'La familia relacionada no está registrada.', [], 404);
  3353. }
  3354. $subfamilyCode = $this->encryptionController->decrypt($subfamilyCode);
  3355. if(!$subfamilyCode){
  3356. return $this->responseController->makeResponse(true, 'El código de la subfamilia no está encriptado correctamente', [], 400);
  3357. }
  3358. $subfamily = DB::table('S002V01TSUBF')->where([
  3359. ['SUBF_NULI', '=', $line],
  3360. ['SUBF_COFA', '=', $familyCode],
  3361. ['SUBF_COSU', '=', $subfamilyCode],
  3362. ])->first();
  3363. if(is_null($subfamily)){
  3364. return $this->responseController->makeResponse(true, 'La subfamilia relacionada no está registrada.', [], 404);
  3365. }
  3366. $equipments = DB::table('S002V01TEQUI')->select([
  3367. 'EQUI_COEQ AS CODIGO',
  3368. 'EQUI_TIPO AS TIPO',
  3369. 'EQUI_MODE AS MODELO',
  3370. 'EQUI_IDEQ AS ID_EQUIPO',
  3371. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  3372. 'EQUI_GAIM AS GALERIA_IMAGENES',
  3373. ])->where([
  3374. ['EQUI_NULI', '=', $line],
  3375. ['EQUI_FAMI', '=', $familyCode],
  3376. ['EQUI_SUBF', '=', $subfamilyCode],
  3377. ['EQUI_JERA', '=', 'Padre']
  3378. ])->get()->all();
  3379. $idUserEnc = $this->encryptionController->encrypt($idUser);
  3380. foreach($equipments as $key=>$equipment){
  3381. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  3382. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  3383. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES, true);
  3384. $imagesGalleryFn = [];
  3385. foreach($imagesGalleryArr as $imageCode){
  3386. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  3387. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  3388. $imageCodeEnc,
  3389. $idUserEnc,
  3390. $line
  3391. );
  3392. $response = json_decode($publicUri->original, true);
  3393. if($response['error']){
  3394. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  3395. }else{
  3396. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  3397. $imagesGalleryFn[] = $uriEnc;
  3398. }
  3399. }
  3400. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  3401. $equipments[$key] = $equipment;
  3402. }
  3403. $now = $this->functionsController->now();
  3404. $nowStr = $now->toDateTimeString();
  3405. $actions = DB::getQueryLog();
  3406. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3407. $idac = $this->functionsController->registerActivity(
  3408. $line,
  3409. 'S002V01M07GEEQ',
  3410. 'S002V01F01ADEQ',
  3411. 'S002V01P01MEEQ',
  3412. 'Consulta',
  3413. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos relacionados a la subfamilia $subfamilyCode de la familia $familyCode.",
  3414. $idUser,
  3415. $nowStr,
  3416. );
  3417. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3418. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  3419. }
  3420. public function getEquipmentsByParent($parentCode, $idUser, $line) {
  3421. DB::enableQueryLog();
  3422. $idUser = $this->encryptionController->decrypt($idUser);
  3423. if(!$idUser){
  3424. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3425. }
  3426. $usr = DB::table('S002V01TUSUA')->where([
  3427. ['USUA_NULI', '=', $line],
  3428. ['USUA_IDUS', '=', $idUser],
  3429. ])->first();
  3430. if(is_null($usr)){
  3431. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3432. }
  3433. $parentCode = $this->encryptionController->decrypt($parentCode);
  3434. if(!$parentCode){
  3435. return $this->responseController->makeResponse(true, 'El código del equipamiento padre no está encriptado correctamente', [], 400);
  3436. }
  3437. $equipments = DB::table('S002V01TEQUI')->select([
  3438. 'EQUI_COEQ AS CODIGO',
  3439. 'EQUI_TIPO AS TIPO',
  3440. 'EQUI_MODE AS MODELO',
  3441. 'EQUI_IDEQ AS ID_EQUIPO',
  3442. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  3443. 'EQUI_GAIM AS GALERIA_IMAGENES',
  3444. 'EQUI_EQPA AS EQUIPO_PADRE',
  3445. ])->where([
  3446. ['EQUI_NULI', '=', $line],
  3447. ['EQUI_JERA', '=', 'Hijo'],
  3448. ['EQUI_EQPA', '=', $parentCode],
  3449. ])->get()->all();
  3450. $idUserEnc = $this->encryptionController->encrypt($idUser);
  3451. foreach($equipments as $key=>$equipment){
  3452. $children = DB::table('S002V01TEQUI')->where([
  3453. ['EQUI_NULI', '=', $line],
  3454. ['EQUI_EQPA', '=', $equipment->CODIGO],
  3455. ])->get()->all();
  3456. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  3457. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  3458. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  3459. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES, true);
  3460. $imagesGalleryFn = [];
  3461. foreach($imagesGalleryArr as $imageCode){
  3462. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  3463. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  3464. $imageCodeEnc,
  3465. $idUserEnc,
  3466. $line
  3467. );
  3468. $response = json_decode($publicUri->original, true);
  3469. if($response['error']){
  3470. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  3471. }else{
  3472. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  3473. $imagesGalleryFn[] = $uriEnc;
  3474. }
  3475. }
  3476. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  3477. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  3478. $equipments[$key] = $equipment;
  3479. }
  3480. $now = $this->functionsController->now();
  3481. $nowStr = $now->toDateTimeString();
  3482. $actions = DB::getQueryLog();
  3483. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3484. $idac = $this->functionsController->registerActivity(
  3485. $line,
  3486. 'S002V01M07GEEQ',
  3487. 'S002V01F01ADEQ',
  3488. 'S002V01P02DEEQ',
  3489. 'Consulta',
  3490. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos relacionados al equipamiento $parentCode.",
  3491. $idUser,
  3492. $nowStr,
  3493. );
  3494. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3495. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  3496. }
  3497. public function getEquipmentDetails($equipmentCode, $idUser, $line) {
  3498. DB::enableQueryLog();
  3499. $idUser = $this->encryptionController->decrypt($idUser);
  3500. if(!$idUser){
  3501. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3502. }
  3503. $usr = DB::table('S002V01TUSUA')->where([
  3504. ['USUA_NULI', '=', $line],
  3505. ['USUA_IDUS', '=', $idUser],
  3506. ])->first();
  3507. if(is_null($usr)){
  3508. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3509. }
  3510. $equipmentCode = $this->encryptionController->decrypt($equipmentCode);
  3511. if(!$equipmentCode){
  3512. return $this->responseController->makeResponse(true, 'El código del equipamiento no está encriptado correctamente', [], 400);
  3513. }
  3514. $equipment = DB::table('S002V01TEQUI')->select([
  3515. 'EQUI_FAMI AS FAMILIA',
  3516. 'EQUI_SUBF AS SUBFAMILIA',
  3517. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  3518. 'EQUI_MODE AS MODELO',
  3519. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  3520. 'EQUI_ESEQ AS ESTADO',
  3521. 'EQUI_COEQ AS CODIGO',
  3522. 'EQUI_JERA AS JERARQUIA',
  3523. 'EQUI_EQPA AS EQUIPO_PADRE',
  3524. 'EQUI_TICO AS TIPO_CODIGO',
  3525. 'EQUI_UBOR AS UBICACION_ORIGEN',
  3526. 'EQUI_NIOR AS NIVEL_ORIGEN',
  3527. 'EQUI_OCOR AS OCUPACION_ORIGEN',
  3528. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  3529. 'EQUI_IPCC AS INTERSECCION_PCC',
  3530. 'EQUI_PPCC AS POSICION_PCC',
  3531. 'EQUI_KIOR AS KILOMETRO_ORIGEN',
  3532. 'EQUI_SEOR AS SECUENCIA_ELEMENTO_ORIGEN',//
  3533. 'EQUI_ARTR AS AREA_TREN',//
  3534. 'EQUI_TCOR AS TIPO_CODIFICACION_ORIGEN',//
  3535. 'EQUI_CEOR AS CODIGO_ELEMENTO_ORIGEN',//
  3536. 'EQUI_UBDE AS UBICACION_DESTINO',
  3537. 'EQUI_NIDE AS NIVEL_DESTINO',
  3538. 'EQUI_OCDE AS OCUPACION_DESTINO',
  3539. 'EQUI_ELDE AS ELEMENTO_DESTINO',
  3540. 'EQUI_KIDE AS KILOMETRO_DESTINO',
  3541. 'EQUI_SEDE AS SECUENCIA_ELEMENTO_DESTINO',//
  3542. 'EQUI_TCDE AS TIPO_CODIFICACION_DESTINO',//
  3543. 'EQUI_CEDE AS CODIGO_ELEMENTO_DESTINO',//
  3544. 'EQUI_CRSE AS NIVEL_CRITICIDAD',//
  3545. 'EQUI_FEAD AS FECHA_ADQUISICION',
  3546. 'EQUI_FIGA AS FECHA_INICIO_GARANTIA',
  3547. 'EQUI_FTGA AS FECHA_TERMINO_GARANTIA',
  3548. 'EQUI_PREQ AS PROVEEDOR',
  3549. 'EQUI_NUSE AS NUMERO_SERIAL',
  3550. 'EQUI_DESO AS DENOMINACION_SOFTWARE',
  3551. 'EQUI_VESO AS VERSION_SOFTWARE',
  3552. 'EQUI_HICO AS HISTORIAL_CODIGOS',
  3553. 'EQUI_GAIM AS GALERIA_IMAGENES',
  3554. 'EQUI_DORE AS DOCUMENTOS',
  3555. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  3556. 'EQUI_USRE AS USUARIO_REGISTRO',
  3557. 'EQUI_FERE AS FECHA_REGISTRO',
  3558. 'EQUI_USMO AS USUARIO_MODIFICACION',
  3559. 'EQUI_FEMO AS FECHA_MODIFICACION',
  3560. ])->where([
  3561. ['EQUI_NULI', '=', $line],
  3562. ['EQUI_COEQ', '=', $equipmentCode],
  3563. ])->first();
  3564. $family = DB::table('S002V01TFAMI')->where([
  3565. ['FAMI_NULI', '=', $line],
  3566. ['FAMI_COFA', '=', $equipment->FAMILIA]
  3567. ])->first();
  3568. $subfamily = DB::table('S002V01TSUBF')->where([
  3569. ['SUBF_NULI', '=', $line],
  3570. ['SUBF_COFA', '=', $equipment->FAMILIA],
  3571. ['SUBF_COSU', '=', $equipment->SUBFAMILIA]
  3572. ])->first();
  3573. $ubic = $this->templatesUbic;
  3574. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  3575. $equipment->FAMILIA = $family->FAMI_NOFA . " (" . $equipment->FAMILIA . ")";
  3576. $equipment->SUBFAMILIA = $subfamily->SUBF_NOSU . " (" . $equipment->SUBFAMILIA . ")";
  3577. $equipment->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($equipment->ID_EQUIPAMIENTO);
  3578. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  3579. $ubic = $this->templatesUbic;
  3580. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  3581. $locationsEnc = file_get_contents($ubic . "locations.sam");
  3582. $locationsDec = $this->encryptionController->decrypt($locationsEnc);
  3583. $locationsArr = json_decode($locationsDec, true);
  3584. $locationsArrDec = [];
  3585. foreach($locationsArr as $location){
  3586. $locationStr = $this->encryptionController->decrypt($location['LOCATION']);
  3587. $code = $this->encryptionController->decrypt($location['CODE']);
  3588. $locationsArrDec[] = [
  3589. 'LOCATION' => $locationStr,
  3590. 'CODE' => $code
  3591. ];
  3592. }
  3593. $originLocation = $equipment->UBICACION_ORIGEN;
  3594. $originLocationFilt = array_filter($locationsArrDec, function ($v, $k) use ($originLocation) {
  3595. return $v['CODE'] == $originLocation;
  3596. }, ARRAY_FILTER_USE_BOTH);
  3597. $equipment->UBICACION_ORIGEN = end($originLocationFilt)['LOCATION'] . " (" . $equipment->UBICACION_ORIGEN . ")";
  3598. if(!is_null($equipment->UBICACION_DESTINO) && $equipment->UBICACION_DESTINO != ''){
  3599. $destinyLocation = $equipment->UBICACION_DESTINO;
  3600. $destinyLocationFilt = array_filter($locationsArrDec, function ($v, $k) use ($destinyLocation) {
  3601. return $v['CODE'] == $destinyLocation;
  3602. }, ARRAY_FILTER_USE_BOTH);
  3603. $equipment->UBICACION_DESTINO = end($destinyLocationFilt)['LOCATION'] . " (" . $equipment->UBICACION_DESTINO . ")";
  3604. }
  3605. $levelsArr = [];
  3606. for($i = 5; $i > 0; $i--){
  3607. $levelsArr[] = [
  3608. 'LEVEL' => "Subterráneo S0$i",
  3609. 'CODE' => "S0$i",
  3610. ];
  3611. }
  3612. for($i = 0; $i <= 15; $i++){
  3613. $code = $i < 10 ? "P0$i" : "P$i";
  3614. $level = $i == 0 ? "Planta baja P00" : "Piso $code";
  3615. $levelsArr[] = [
  3616. 'LEVEL' => $level,
  3617. 'CODE' => $code,
  3618. ];
  3619. }
  3620. $originLevel = $equipment->NIVEL_ORIGEN;
  3621. $originLevelFilt = array_filter($levelsArr, function ($v, $k) use ($originLevel) {
  3622. return $v['CODE'] == $originLevel;
  3623. }, ARRAY_FILTER_USE_BOTH);
  3624. $equipment->NIVEL_ORIGEN = end($originLevelFilt)['LEVEL'] . " (" . $equipment->NIVEL_ORIGEN . ")";
  3625. if(!is_null($equipment->NIVEL_DESTINO) && $equipment->NIVEL_DESTINO != ''){
  3626. $destinyLevel = $equipment->NIVEL_DESTINO;
  3627. $destinyLevelFilt = array_filter($levelsArr, function ($v, $k) use ($destinyLevel) {
  3628. return $v['CODE'] == $destinyLevel;
  3629. }, ARRAY_FILTER_USE_BOTH);
  3630. $equipment->NIVEL_DESTINO = end($destinyLevelFilt)['LEVEL'] . " (" . $equipment->NIVEL_DESTINO . ")";
  3631. }
  3632. if($equipment->TIPO_CODIGO == '5'){
  3633. $trainOccupationsEnc = file_get_contents($ubic . "train-occupations.sam");
  3634. $trainOccupationsDec = $this->encryptionController->decrypt($trainOccupationsEnc);
  3635. $trainOccupationsArr = json_decode($trainOccupationsDec, true);
  3636. $trainOccupationsArrDec = [];
  3637. foreach($trainOccupationsArr as $k0=>$v0){
  3638. $trainOccupation = [];
  3639. foreach($v0 as $k1=>$v1){
  3640. $valDec = $this->encryptionController->decrypt($v1);
  3641. $trainOccupation[$k1] = $valDec;
  3642. }
  3643. $trainOccupationsArrDec[$k0] = $trainOccupation;
  3644. }
  3645. $originOccupation = $equipment->OCUPACION_ORIGEN;
  3646. $trainOccupationFilt = array_filter($trainOccupationsArrDec, function($v, $k) use($originOccupation){
  3647. return $v['CODE'] == $originOccupation;
  3648. }, ARRAY_FILTER_USE_BOTH);
  3649. $trainOccupation = end($trainOccupationFilt);
  3650. $equipment->OCUPACION_ORIGEN = $trainOccupation['CAR'] . " (" . $trainOccupation['CODE'] . ")";
  3651. $trainElementsEnc = file_get_contents($ubic . "train-elements.sam");
  3652. $trainElementsDec = $this->encryptionController->decrypt($trainElementsEnc);
  3653. $trainElementsArr = json_decode($trainElementsDec, true);
  3654. $trainElementsArrDec = [];
  3655. foreach($trainElementsArr as $k0=>$v0){
  3656. $trainElement = [];
  3657. foreach($v0 as $k1=>$v1){
  3658. $valDec = $this->encryptionController->decrypt($v1);
  3659. $trainElement[$k1] = $valDec;
  3660. }
  3661. $trainElementsArrDec[$k0] = $trainElement;
  3662. }
  3663. $originElement = $equipment->ELEMENTO_ORIGEN;
  3664. $trainElementFilt = array_filter($trainElementsArrDec, function($v, $k) use($originElement){
  3665. return $v['CODE'] == $originElement;
  3666. }, ARRAY_FILTER_USE_BOTH);
  3667. $trainElement = end($trainElementFilt);
  3668. $equipment->ELEMENTO_ORIGEN = $trainElement['ELEMENT'] . " (" . $trainElement['CODE'] . ")";
  3669. $carAreasEnc = file_get_contents($ubic . "car-areas.sam");
  3670. $carAreasDec = $this->encryptionController->decrypt($carAreasEnc);
  3671. $carAreasArr = json_decode($carAreasDec, true);
  3672. $carAreasArrDec = [];
  3673. foreach($carAreasArr as $k0=>$v0){
  3674. $keyDec = $this->encryptionController->decrypt($k0);
  3675. if($keyDec == $trainOccupation['CODE']){
  3676. foreach($v0 as $k1=>$v1){
  3677. $carArea = [];
  3678. foreach($v1 as $k2=>$v2){
  3679. $valDec = $this->encryptionController->decrypt($v2);
  3680. $carArea[$k2] = $valDec;
  3681. }
  3682. $carAreasArrDec[$k1] = $carArea;
  3683. }
  3684. }
  3685. }
  3686. $trainArea = $equipment->AREA_TREN;
  3687. $carAreaFilt = array_filter($carAreasArrDec, function($v, $k) use($trainArea){
  3688. return $v['CODE'] == $trainArea;
  3689. }, ARRAY_FILTER_USE_BOTH);
  3690. $carArea = end($carAreaFilt);
  3691. $equipment->AREA_TREN = $carArea['AREA'] . " (" . $carArea['CODE'] . ")";
  3692. }else{
  3693. $originOccupationStr = $equipment->OCUPACION_ORIGEN;
  3694. $originOccupationArea = substr($originOccupationStr, 0, 2);
  3695. $originOccupationID = substr($originOccupationStr, 2);
  3696. $originOccupation = DB::table('S002V01TOCUP')->where([
  3697. ['OCUP_NULI', '=', $line],
  3698. ['OCUP_AREA', '=', $originOccupationArea],
  3699. ['OCUP_IDOC', '=', $originOccupationID]
  3700. ])->first();
  3701. $equipment->OCUPACION_ORIGEN = $originOccupation->OCUP_DESC . " (" . $originOccupationStr . ")";
  3702. if(!is_null($equipment->OCUPACION_DESTINO) && $equipment->OCUPACION_DESTINO != ''){
  3703. $destinyOccupationStr = $equipment->OCUPACION_DESTINO;
  3704. $destinyOccupationArea = substr($destinyOccupationStr, 0, 2);
  3705. $destinyOccupationID = substr($destinyOccupationStr, 2);
  3706. $destinyOccupation = DB::table('S002V01TOCUP')->where([
  3707. ['OCUP_NULI', '=', $line],
  3708. ['OCUP_AREA', '=', $destinyOccupationArea],
  3709. ['OCUP_IDOC', '=', $destinyOccupationID]
  3710. ])->first();
  3711. $equipment->OCUPACION_DESTINO = $destinyOccupation->OCUP_DESC . " (" . $destinyOccupationStr . ")";
  3712. }
  3713. }
  3714. if(!is_null($equipment->SECUENCIA_ELEMENTO_ORIGEN)){
  3715. $equipment->SECUENCIA_ELEMENTO_ORIGEN = $this->encryptionController->encrypt($equipment->SECUENCIA_ELEMENTO_ORIGEN);
  3716. }
  3717. if(!is_null($equipment->SECUENCIA_ELEMENTO_DESTINO)){
  3718. $equipment->SECUENCIA_ELEMENTO_DESTINO = $this->encryptionController->encrypt($equipment->SECUENCIA_ELEMENTO_DESTINO);
  3719. }
  3720. if(!is_null($equipment->CODIGO_ELEMENTO_ORIGEN)){
  3721. $equipment->CODIGO_ELEMENTO_ORIGEN = $this->encryptionController->encrypt($equipment->CODIGO_ELEMENTO_ORIGEN);
  3722. }
  3723. if(!is_null($equipment->CODIGO_ELEMENTO_DESTINO)){
  3724. $equipment->CODIGO_ELEMENTO_DESTINO = $this->encryptionController->encrypt($equipment->CODIGO_ELEMENTO_DESTINO);
  3725. }
  3726. $validStatus = ["A" => "Adquisición", "S" => "Stock", "T" => "Traslado", "I" => "Instalación", "R" => "Reparación", "D" => "Disposición"];
  3727. $equipment->ESTADO = $validStatus[$equipment->ESTADO] . " (" . $equipment->ESTADO . ")";
  3728. $idUserEnc = $this->encryptionController->encrypt($idUser);
  3729. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES);
  3730. $imagesGalleryFn = [];
  3731. foreach($imagesGalleryArr as $imageCode){
  3732. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  3733. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  3734. $imageCodeEnc,
  3735. $idUserEnc,
  3736. $line
  3737. );
  3738. $response = json_decode($publicUri->original, true);
  3739. if($response['error']){
  3740. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  3741. }else{
  3742. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  3743. $imagesGalleryFn[] = $uriEnc;
  3744. }
  3745. }
  3746. $documentsArr = json_decode($equipment->DOCUMENTOS);
  3747. $documentsFn = [];
  3748. foreach($documentsArr as $document){
  3749. $codeArr = explode('=',$document);
  3750. $codeArr0 = explode('-', $codeArr[0]);
  3751. $file = DB::table('S002V01TAFAL')->where([
  3752. ['AFAL_NULI', '=', $line],
  3753. ['AFAL_COMO', '=', $codeArr0[1]],
  3754. ['AFAL_CLDO', '=', $codeArr0[2]],
  3755. ['AFAL_FECR', '=', $codeArr0[3]],
  3756. ['AFAL_NUSE', '=', $codeArr0[4]],
  3757. ['AFAL_NUVE', '=', $codeArr[1]],
  3758. ])->first();
  3759. if(is_null($file)){
  3760. return $this->responseController->makeResponse(true, "El archivo $document no está registrado.", [], 404);
  3761. }
  3762. $documentsFn[] = [
  3763. 'id' => $this->encryptionController->encrypt($document),
  3764. 'name' => $document,
  3765. 'size' => $file->AFAL_TAMA
  3766. ];
  3767. }
  3768. if(!is_null($equipment->NIVEL_CRITICIDAD)){
  3769. $equipment->NIVEL_CRITICIDAD = $this->encryptionController->encrypt($equipment->NIVEL_CRITICIDAD);
  3770. }
  3771. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  3772. $equipment->DOCUMENTOS = json_encode($documentsFn);
  3773. $provider = DB::table('S002V01TPROV')->where([
  3774. ['PROV_NULI', '=', $line],
  3775. ['PROV_NUPR', '=', $equipment->PROVEEDOR],
  3776. ])->first();
  3777. $equipment->PROVEEDOR = $provider->PROV_NOCO . " (" . $equipment->PROVEEDOR . ")";
  3778. $equipment->NUMERO_SERIAL = $this->encryptionController->encrypt($equipment->NUMERO_SERIAL);
  3779. $codesHistory = json_decode($equipment->HISTORIAL_CODIGOS, true);
  3780. $codesHistoryFn = [];
  3781. foreach($codesHistory as $code){
  3782. $code['CODIGO'] = $this->encryptionController->encrypt($code['CODIGO']);
  3783. if(isset($code['PADRE'])){
  3784. $code['PADRE'] = $this->encryptionController->encrypt($code['PADRE']);
  3785. }
  3786. $codesHistoryFn[] = $code;
  3787. }
  3788. $equipment->HISTORIAL_CODIGOS = json_encode($codesHistoryFn);
  3789. $usrReg = DB::table('S002V01TUSUA')->where([
  3790. ['USUA_NULI', '=', $line],
  3791. ['USUA_IDUS', '=', $equipment->USUARIO_REGISTRO]
  3792. ])->first();
  3793. $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  3794. $equipment->USUARIO_REGISTRO = $usrRegName . " (" . $equipment->USUARIO_REGISTRO . ")";
  3795. if(!is_null($equipment->USUARIO_MODIFICACION)){
  3796. $usrMod = DB::table('S002V01TUSUA')->where([
  3797. ['USUA_NULI', '=', $line],
  3798. ['USUA_IDUS', '=', $equipment->USUARIO_MODIFICACION]
  3799. ])->first();
  3800. $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  3801. $equipment->USUARIO_MODIFICACION = $usrModName . " (" . $equipment->USUARIO_MODIFICACION . ")";
  3802. }
  3803. $equipment->TIPO_EQUIPAMIENTO = $this->encryptionController->encrypt($equipment->TIPO_EQUIPAMIENTO);
  3804. $equipment->MODELO = $this->encryptionController->encrypt($equipment->MODELO);
  3805. $now = $this->functionsController->now();
  3806. $nowStr = $now->toDateTimeString();
  3807. $actions = DB::getQueryLog();
  3808. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3809. $idac = $this->functionsController->registerActivity(
  3810. $line,
  3811. 'S002V01M07GEEQ',
  3812. 'S002V01F01ADEQ',
  3813. 'S002V01P01MEEQ',
  3814. 'Consulta',
  3815. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el equipamiento $equipmentCode.",
  3816. $idUser,
  3817. $nowStr,
  3818. );
  3819. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3820. return $this->responseController->makeResponse(false, 'EXITO.', $equipment);
  3821. }
  3822. public function getTrainOccupations($idUser, $line) {
  3823. DB::enableQueryLog();
  3824. $idUser = $this->encryptionController->decrypt($idUser);
  3825. if(!$idUser){
  3826. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3827. }
  3828. $usr = DB::table('S002V01TUSUA')->where([
  3829. ['USUA_NULI', '=', $line],
  3830. ['USUA_IDUS', '=', $idUser],
  3831. ])->first();
  3832. if(is_null($usr)){
  3833. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3834. }
  3835. $ubic = $this->templatesUbic;
  3836. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  3837. $trainOccupationsEnc = file_get_contents($ubic . "train-occupations.sam");
  3838. $trainOccupationsDec = $this->encryptionController->decrypt($trainOccupationsEnc);
  3839. $trainOccupationsArr = json_decode($trainOccupationsDec, true);
  3840. $now = $this->functionsController->now();
  3841. $nowStr = $now->toDateTimeString();
  3842. $actions = DB::getQueryLog();
  3843. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3844. $idac = $this->functionsController->registerActivity(
  3845. $line,
  3846. 'S002V01M07GEEQ',
  3847. 'S002V01F01ADEQ',
  3848. '-',
  3849. 'Consulta',
  3850. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las ocupaciones de tren.",
  3851. $idUser,
  3852. $nowStr,
  3853. );
  3854. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3855. return $this->responseController->makeResponse(false, 'EXITO.', $trainOccupationsArr);
  3856. }
  3857. public function getTrainAreas($trainOccupation, $idUser, $line) {
  3858. DB::enableQueryLog();
  3859. $idUser = $this->encryptionController->decrypt($idUser);
  3860. if(!$idUser){
  3861. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3862. }
  3863. $usr = DB::table('S002V01TUSUA')->where([
  3864. ['USUA_NULI', '=', $line],
  3865. ['USUA_IDUS', '=', $idUser],
  3866. ])->first();
  3867. if(is_null($usr)){
  3868. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3869. }
  3870. $trainOccupation = $this->encryptionController->decrypt($trainOccupation);
  3871. if(!$trainOccupation){
  3872. return $this->responseController->makeResponse(true, 'La ocupación no fue encriptada correctamente.', [], 400);
  3873. }
  3874. $ubic = $this->templatesUbic;
  3875. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  3876. $carAreasEnc = file_get_contents($ubic . "car-areas.sam");
  3877. $carAreasDec = $this->encryptionController->decrypt($carAreasEnc);
  3878. $carAreasArr = json_decode($carAreasDec, true);
  3879. $carAreasArrDec = [];
  3880. foreach($carAreasArr as $key=>$val){
  3881. $keyDec = $this->encryptionController->decrypt($key);
  3882. $carAreasArrDec[$keyDec] = $val;
  3883. }
  3884. if(!array_key_exists($trainOccupation, $carAreasArrDec)){
  3885. return $this->responseController->makeResponse(true, "La ocupación $trainOccupation no existe.", [], 404);
  3886. }
  3887. $now = $this->functionsController->now();
  3888. $nowStr = $now->toDateTimeString();
  3889. $actions = DB::getQueryLog();
  3890. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3891. $idac = $this->functionsController->registerActivity(
  3892. $line,
  3893. 'S002V01M07GEEQ',
  3894. 'S002V01F01ADEQ',
  3895. '-',
  3896. 'Consulta',
  3897. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las áreas de la ocupación $trainOccupation de tren.",
  3898. $idUser,
  3899. $nowStr,
  3900. );
  3901. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3902. return $this->responseController->makeResponse(false, 'EXITO.', $carAreasArrDec[$trainOccupation]);
  3903. }
  3904. public function getTrainElements($idUser, $line) {
  3905. DB::enableQueryLog();
  3906. $idUser = $this->encryptionController->decrypt($idUser);
  3907. if(!$idUser){
  3908. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3909. }
  3910. $usr = DB::table('S002V01TUSUA')->where([
  3911. ['USUA_NULI', '=', $line],
  3912. ['USUA_IDUS', '=', $idUser],
  3913. ])->first();
  3914. if(is_null($usr)){
  3915. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3916. }
  3917. $ubic = $this->templatesUbic;
  3918. $ubic = str_replace("pdf_templates\\01_05_GEEQ", "global_resources", $ubic);
  3919. $trainElementsEnc = file_get_contents($ubic . "train-elements.sam");
  3920. $trainElementsDec = $this->encryptionController->decrypt($trainElementsEnc);
  3921. $trainElementsArr = json_decode($trainElementsDec, true);
  3922. $now = $this->functionsController->now();
  3923. $nowStr = $now->toDateTimeString();
  3924. $actions = DB::getQueryLog();
  3925. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3926. $idac = $this->functionsController->registerActivity(
  3927. $line,
  3928. 'S002V01M07GEEQ',
  3929. 'S002V01F01ADEQ',
  3930. '-',
  3931. 'Consulta',
  3932. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los elementos de tren.",
  3933. $idUser,
  3934. $nowStr,
  3935. );
  3936. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3937. return $this->responseController->makeResponse(false, 'EXITO.', $trainElementsArr);
  3938. }
  3939. public function getEquipmentsByCodeType($codeType, $idUser, $line) {
  3940. DB::enableQueryLog();
  3941. $idUser = $this->encryptionController->decrypt($idUser);
  3942. if(!$idUser){
  3943. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  3944. }
  3945. $usr = DB::table('S002V01TUSUA')->where([
  3946. ['USUA_NULI', '=', $line],
  3947. ['USUA_IDUS', '=', $idUser],
  3948. ])->first();
  3949. if(is_null($usr)){
  3950. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  3951. }
  3952. $codeType = $this->encryptionController->decrypt($codeType);
  3953. if(!$codeType){
  3954. return $this->responseController->makeResponse(true, 'El tipo de código seleccionado no está encriptado correctamente', [], 400);
  3955. }
  3956. $equipments = DB::table('S002V01TEQUI')->select([
  3957. 'EQUI_COEQ AS CODIGO',
  3958. 'EQUI_TIPO AS TIPO',
  3959. 'EQUI_MODE AS MODELO',
  3960. 'EQUI_IDEQ AS ID_EQUIPO',
  3961. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  3962. 'EQUI_GAIM AS GALERIA_IMAGENES',
  3963. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  3964. 'EQUI_TICO AS TIPO_CODIGO',
  3965. 'EQUI_EQPA AS EQUIPO_PADRE',
  3966. ])->where([
  3967. ['EQUI_NULI', '=', $line],
  3968. ['EQUI_TICO', '=', $codeType],
  3969. ])->get()->all();
  3970. $idUserEnc = $this->encryptionController->encrypt($idUser);
  3971. foreach($equipments as $key=>$equipment){
  3972. $children = DB::table('S002V01TEQUI')->where([
  3973. ['EQUI_NULI', '=', $line],
  3974. ['EQUI_EQPA', '=', $equipment->CODIGO],
  3975. ])->get()->all();
  3976. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  3977. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  3978. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  3979. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES, true);
  3980. $imagesGalleryFn = [];
  3981. foreach($imagesGalleryArr as $imageCode){
  3982. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  3983. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  3984. $imageCodeEnc,
  3985. $idUserEnc,
  3986. $line
  3987. );
  3988. $response = json_decode($publicUri->original, true);
  3989. if($response['error']){
  3990. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  3991. }else{
  3992. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  3993. $imagesGalleryFn[] = $uriEnc;
  3994. }
  3995. }
  3996. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  3997. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  3998. $equipments[$key] = $equipment;
  3999. }
  4000. $now = $this->functionsController->now();
  4001. $nowStr = $now->toDateTimeString();
  4002. $actions = DB::getQueryLog();
  4003. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4004. $idac = $this->functionsController->registerActivity(
  4005. $line,
  4006. 'S002V01M07GEEQ',
  4007. 'S002V01F01ADEQ',
  4008. 'S002V01P01MEEQ',
  4009. 'Consulta',
  4010. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos con tipo de código #$codeType.",
  4011. $idUser,
  4012. $nowStr,
  4013. );
  4014. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4015. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  4016. }
  4017. public function generateGraphicArborescence(Request $request) {
  4018. DB::enableQueryLog();
  4019. $validator = Validator::make($request->all(), [
  4020. 'id_user' => 'required|string',
  4021. 'linea' => 'required|integer',
  4022. 'equipment_code' => 'required|string',
  4023. 'equipment_arborescence' => 'required|string',
  4024. ]);
  4025. if($validator->fails()){
  4026. return $this->responseController->makeResponse(
  4027. true,
  4028. "Se encontraron uno o más errores.",
  4029. $this->responseController->makeErrors(
  4030. $validator->errors()->messages()
  4031. ),
  4032. 401
  4033. );
  4034. }
  4035. $form = $request->all();
  4036. $idUser = $this->encryptionController->decrypt($form['id_user']);
  4037. if(!$idUser){
  4038. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  4039. }
  4040. $usr = DB::table('S002V01TUSUA')->where([
  4041. ['USUA_NULI', '=', $form['linea']],
  4042. ['USUA_IDUS', '=', $idUser]
  4043. ])->first();
  4044. if(is_null($usr)){
  4045. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4046. }
  4047. $equipmentCodeDec = $this->encryptionController->decrypt($form['equipment_code']);
  4048. if(!$equipmentCodeDec){
  4049. return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400);
  4050. }
  4051. $equipment = DB::table('S002V01TEQUI')->where([
  4052. ['EQUI_NULI', '=', $form['linea']],
  4053. ['EQUI_COEQ', '=', $equipmentCodeDec]
  4054. ])->first();
  4055. if(is_null($equipment)){
  4056. return $this->responseController->makeResponse(true, 'El equipamiento solicitado no existe.', [], 404);
  4057. }
  4058. $arborescenceDec = $this->encryptionController->decrypt($form['equipment_arborescence']);
  4059. if(!$arborescenceDec){
  4060. return $this->responseController->makeResponse(true, 'El arreglo de la arborescencia no fue encriptado correctamente.', [], 400);
  4061. }
  4062. $materialIcons = [];
  4063. $iconsLocation = $this->templatesUbic;
  4064. $iconsLocation = str_replace("pdf_templates\\01_05_GEEQ\\", "global_resources\\mat_icons_png", $iconsLocation);
  4065. if(!file_exists($iconsLocation)){
  4066. return $this->responseController->makeResponse(true, 'No se pudo obtener la lista de iconos.', [], 404);
  4067. }
  4068. $iconsList = scandir($iconsLocation);
  4069. foreach($iconsList as $category){
  4070. if($category != '.' && $category != '..'){
  4071. $categoryIcons = scandir("$iconsLocation\\$category");
  4072. foreach($categoryIcons as $icon){
  4073. if($icon != '.' && $icon != '..'){
  4074. if(file_exists("$iconsLocation\\$category\\$icon\\materialicons\\48dp\\2x")){
  4075. $imgFiles = scandir("$iconsLocation\\$category\\$icon\\materialicons\\48dp\\2x");
  4076. if(count($imgFiles) == 3){
  4077. foreach($imgFiles as $imgStr){
  4078. if($imgStr != '.' && $imgStr != '..'){
  4079. $materialIcons[] = [
  4080. 'category' => $category,
  4081. 'icon' => $icon,
  4082. 'iconRoute' => "$iconsLocation\\$category\\$icon\\materialicons\\48dp\\2x\\$imgStr"
  4083. ];
  4084. }
  4085. }
  4086. }
  4087. }
  4088. }
  4089. }
  4090. }
  4091. }
  4092. $html = file_get_contents($this->templatesUbic . "01-GEEQ-PL-010101-000001=01=PDF_ARBORESCENCIA.html");
  4093. $arborescenceArr = json_decode($arborescenceDec, true);
  4094. $tableBody = "";
  4095. foreach($arborescenceArr as $level=>$item){
  4096. $levelIndex = $level + 1;
  4097. if(!array_key_exists('label', $item) || !array_key_exists('graph', $item)){
  4098. return $this->responseController->makeResponse(true, "El elemento del nivel $levelIndex de la arborescencia tiene un formato inválido.", [], 404);
  4099. }
  4100. if($levelIndex == 1){
  4101. $logo = file_get_contents("C:\inetpub\wwwroot\sam\storage\app\public\global_resources\sam-short-logo.png");
  4102. $logoStr = "data:image/svg+xml;base64," . base64_encode($logo);
  4103. $tableBody .= "
  4104. <tr>
  4105. <td class=\"td-label\">Línea 1</td>
  4106. <td style=\"padding: 8px; text-align:center;\">
  4107. <img src=\"$logoStr\" width=\"256px\">
  4108. </td>
  4109. </tr>
  4110. ";
  4111. }else if($levelIndex > 1 && $levelIndex <= 3){
  4112. $graphArr = json_decode($item['graph'], true);
  4113. if($graphArr['customIcon'] == 'N'){
  4114. $iconName = $graphArr['icon'];
  4115. $iconFilt = array_filter($materialIcons, function($v, $k) use ($iconName) {
  4116. return $v['icon'] == $iconName;
  4117. }, ARRAY_FILTER_USE_BOTH);
  4118. $iconObj = end($iconFilt);
  4119. $imageContent = file_get_contents($iconObj['iconRoute']);
  4120. $imageContentStr = "data:image/svg+xml;base64," . base64_encode($imageContent);
  4121. $tableBody .= "
  4122. <tr>
  4123. <td class=\"td-label\">$item[label]</td>
  4124. <td style=\"padding: 8px; text-align:center;\">
  4125. <img src=\"$imageContentStr\" width=\"128px\" height=\"128px\" style=\"opacity:0.6;\">
  4126. </td>
  4127. </tr>
  4128. ";
  4129. }
  4130. }else{
  4131. $graphLocation = str_replace('http://git.ittec.mx/', '', $item['graph']);
  4132. $graphLocation = str_replace('/', "\\", $graphLocation);
  4133. $publicImagesLocation = str_replace('sam\storage\app\public\pdf_templates\01_05_GEEQ\\', '', $this->templatesUbic);
  4134. $graphLocation = $publicImagesLocation . $graphLocation;
  4135. if(file_exists($graphLocation)){
  4136. $graphSize = getimagesize($graphLocation);
  4137. $graphWidth = $graphSize[0];
  4138. $graphHeight = $graphSize[1];
  4139. $graphSizeStr = '';
  4140. if($graphWidth > $graphHeight){
  4141. $widthZoom = round($this->functionsController->floatDiv($graphWidth, 272));
  4142. $widthZoom = $widthZoom <= 0 ? 1 : $widthZoom;
  4143. $graphWidth = round($this->functionsController->floatDiv($graphWidth, $widthZoom));
  4144. $graphHeight = round($this->functionsController->floatDiv($graphHeight, $widthZoom));
  4145. $graphSizeStr = "width=\"" . $graphWidth . "px\" height=\"" . $graphHeight . "px\"";
  4146. }else if($graphWidth < $graphHeight){
  4147. $heightZoom = round($this->functionsController->floatDiv($graphHeight, 272));
  4148. $heightZoom = $heightZoom <= 0 ? 1 : $heightZoom;
  4149. $graphWidth = round($this->functionsController->floatDiv($graphWidth, $heightZoom));
  4150. $graphHeight = round($this->functionsController->floatDiv($graphHeight, $heightZoom));
  4151. $graphSizeStr = "width=\"" . $graphWidth . "px\" height=\"" . $graphHeight . "px\"";
  4152. }else{
  4153. $widthZoom = round($this->functionsController->floatDiv($graphWidth, 272));
  4154. $widthZoom = $widthZoom <= 0 ? 1 : $widthZoom;
  4155. $heightZoom = round($this->functionsController->floatDiv($graphHeight, 272));
  4156. $heightZoom = $heightZoom <= 0 ? 1 : $heightZoom;
  4157. $graphWidth = round($this->functionsController->floatDiv($graphWidth, $widthZoom));
  4158. $graphHeight = round($this->functionsController->floatDiv($graphHeight, $heightZoom));
  4159. $graphSizeStr = "width=\"" . $graphWidth . "px\" height=\"" . $graphHeight . "px\"";
  4160. }
  4161. $labelArr = explode(' - ', $item['label']);
  4162. $graphContent = file_get_contents($graphLocation);
  4163. $graphContentStr ="data:image/svg+xml;base64," . base64_encode($graphContent);
  4164. $tableBody .= "
  4165. <tr>
  4166. <td class=\"td-label\">
  4167. <b>Código: </b>$labelArr[0]<br><br>
  4168. <b>Descripción: </b>$labelArr[1] - $labelArr[2]
  4169. </td>
  4170. <td style=\"padding: 8px; text-align:center;\">
  4171. <img src=\"$graphContentStr\" $graphSizeStr>
  4172. </td>
  4173. </tr>
  4174. ";
  4175. }
  4176. }
  4177. }
  4178. $html = str_replace('%tableBody%', $tableBody, $html);
  4179. $elementCodeArr0 = explode('_', $equipmentCodeDec);
  4180. $elementCodeStr0 = end($elementCodeArr0);
  4181. $elementCodeArr1 = explode('.', $elementCodeStr0);
  4182. $elementCodeStr = end($elementCodeArr1);
  4183. $como = 'GEEQ';
  4184. $cldo = 'IN';
  4185. $noar = "arborescencia_$elementCodeStr";
  4186. $exte = "pdf";
  4187. $line = intval($form['linea']);
  4188. $line = $line < 10 ? "0$line" : "$line";
  4189. $now = $this->functionsController->now();
  4190. $nowStr = $now->toDateTimeString();
  4191. $nowArr = explode(" ", $nowStr);
  4192. $dateArr = explode("-", $nowArr[0]);
  4193. $year = substr($dateArr[0], 2);
  4194. $fecr = $year . $dateArr[1] .$dateArr[2];
  4195. $sec = DB::table('S002V01TAFAL')->where([
  4196. ['AFAL_NULI', '=', $line],
  4197. ['AFAL_COMO', '=', $como],
  4198. ['AFAL_CLDO', '=', $cldo],
  4199. ])->orderBy('AFAL_NUSE', 'desc')->first();
  4200. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  4201. for($i = strlen($nuse); $i < 6; $i++){
  4202. $nuse = "0$nuse";
  4203. }
  4204. $ver = DB::table('S002V01TAFAL')->where([
  4205. ['AFAL_NULI', '=', $line],
  4206. ['AFAL_COMO', '=', $como],
  4207. ['AFAL_CLDO', '=', $cldo],
  4208. ['AFAL_NOAR', '=', $noar],
  4209. ['AFAL_EXTE', '=', $exte],
  4210. ])->orderBy('AFAL_NUVE', 'desc')->first();
  4211. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  4212. for($i = strlen($nuve); $i < 2; $i++){
  4213. $nuve = "0$nuve";
  4214. }
  4215. $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';
  4216. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  4217. $dompdf = new Dompdf();
  4218. $dompdf->loadHtml($html);
  4219. $dompdf->setPaper('A4', 'portrait');
  4220. $dompdf->render();
  4221. $output = $dompdf->output();
  4222. $tempFile = $filePath . $fileName;
  4223. if(!file_exists($tempFile)){
  4224. fopen($tempFile, 'w');
  4225. }
  4226. file_put_contents($tempFile, $output);
  4227. $ubic = Storage::putFile('files', new File($tempFile));
  4228. $ubic = str_replace("/", "\\", $ubic);
  4229. $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
  4230. $tama = filesize($ubic);
  4231. $usac = json_encode([$idUser]);
  4232. unlink($tempFile);
  4233. DB::table('S002V01TAFAL')->insert([
  4234. 'AFAL_NULI' => $line,
  4235. 'AFAL_COMO' => $como,
  4236. 'AFAL_CLDO' => $cldo,
  4237. 'AFAL_FECR' => $fecr,
  4238. 'AFAL_NUSE' => $nuse,
  4239. 'AFAL_NUVE' => $nuve,
  4240. 'AFAL_NOAR' => $noar,
  4241. 'AFAL_EXTE' => $exte,
  4242. 'AFAL_TAMA' => $tama,
  4243. 'AFAL_UBIC' => $ubic,
  4244. 'AFAL_USAC' => $usac,
  4245. 'AFAL_USRE' => $idUser,
  4246. 'AFAL_FERE' => $nowStr,
  4247. ]);
  4248. $actions = DB::getQueryLog();
  4249. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4250. $idac = $this->functionsController->registerActivity(
  4251. $line,
  4252. 'S002V01M07GEEQ',
  4253. 'S002V01F01ADEQ',
  4254. '-',
  4255. 'Registro',
  4256. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de arborescencia del equipamiento $equipmentCodeDec.",
  4257. $idUser,
  4258. $nowStr,
  4259. );
  4260. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4261. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $this->encryptionController->encrypt($fileName)]);
  4262. }
  4263. public function updateSecurityCriticality(Request $request) {
  4264. DB::enableQueryLog();
  4265. $validator = Validator::make($request->all(), [
  4266. 'id_user' => 'required|string',
  4267. 'linea' => 'required|integer',
  4268. 'equipment_code' => 'required|string',
  4269. 'criticality' => 'required|string',
  4270. ]);
  4271. if($validator->fails()){
  4272. return $this->responseController->makeResponse(
  4273. true,
  4274. "Se encontraron uno o más errores.",
  4275. $this->responseController->makeErrors(
  4276. $validator->errors()->messages()
  4277. ),
  4278. 401
  4279. );
  4280. }
  4281. $form = $request->all();
  4282. $idUser = $this->encryptionController->decrypt($form['id_user']);
  4283. if(!$idUser){
  4284. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  4285. }
  4286. $usr = DB::table('S002V01TUSUA')->where([
  4287. ['USUA_NULI', '=', $form['linea']],
  4288. ['USUA_IDUS', '=', $idUser]
  4289. ])->first();
  4290. if(is_null($usr)){
  4291. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4292. }
  4293. $equipmentCodeDec = $this->encryptionController->decrypt($form['equipment_code']);
  4294. if(!$equipmentCodeDec){
  4295. return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400);
  4296. }
  4297. $equipment = DB::table('S002V01TEQUI')->where([
  4298. ['EQUI_NULI', '=', $form['linea']],
  4299. ['EQUI_COEQ', '=', $equipmentCodeDec]
  4300. ])->first();
  4301. if(is_null($equipment)){
  4302. return $this->responseController->makeResponse(true, 'El equipamiento solicitado no existe.', [], 404);
  4303. }
  4304. $criticality = $this->encryptionController->decrypt($form['criticality']);
  4305. if(!$criticality){
  4306. return $this->responseController->makeResponse(true, 'La criticidad seleccionada no fue encriptada correctamente.', [], 400);
  4307. }
  4308. $now = $this->functionsController->now();
  4309. $nowStr = $now->toDateTimeString();
  4310. DB::table('S002V01TEQUI')->where([
  4311. ['EQUI_NULI', '=', $form['linea']],
  4312. ['EQUI_COEQ', '=', $equipmentCodeDec]
  4313. ])->update([
  4314. 'EQUI_CRSE' => $criticality,
  4315. 'EQUI_USMO' => $idUser,
  4316. 'EQUI_FEMO' => $nowStr,
  4317. ]);
  4318. $actions = DB::getQueryLog();
  4319. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4320. $idac = $this->functionsController->registerActivity(
  4321. $form['linea'],
  4322. 'S002V01M07GEEQ',
  4323. 'S002V01F03GCSE',
  4324. 'S002V01P01GECR',
  4325. 'Actualización',
  4326. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la criticidad de seguridad del equipamiento $equipmentCodeDec.",
  4327. $idUser,
  4328. $nowStr,
  4329. );
  4330. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  4331. return $this->responseController->makeResponse(false, 'EXITO.');
  4332. }
  4333. public function generateEquipmentFile(Request $request) {
  4334. DB::enableQueryLog();
  4335. $validator = Validator::make($request->all(), [
  4336. 'id_user' => 'required|string',
  4337. 'linea' => 'required|integer',
  4338. 'file_type' => 'required|string|in:PDF,XLS',
  4339. 'file_data' => 'required|string',
  4340. ]);
  4341. if($validator->fails()){
  4342. return $this->responseController->makeResponse(
  4343. true,
  4344. "Se encontraron uno o más errores.",
  4345. $this->responseController->makeErrors(
  4346. $validator->errors()->messages()
  4347. ),
  4348. 401
  4349. );
  4350. }
  4351. $form = $request->all();
  4352. $idUser = $this->encryptionController->decrypt($form['id_user']);
  4353. if(!$idUser){
  4354. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  4355. }
  4356. $usr = DB::table('S002V01TUSUA')->where([
  4357. ['USUA_NULI', '=', $form['linea']],
  4358. ['USUA_IDUS', '=', $idUser]
  4359. ])->first();
  4360. if(is_null($usr)){
  4361. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4362. }
  4363. $fileData = $this->encryptionController->decrypt($form['file_data']);
  4364. if(!$fileData){
  4365. return $this->responseController->makeResponse(true, 'La información del equipamiento no fue encriptada correctamente.', [], 400);
  4366. }
  4367. $fileDataArr = json_decode($fileData, true);
  4368. $spreadsheet = $this->generateEquipmentDataSheet($fileDataArr);
  4369. $now = $this->functionsController->now();
  4370. $nowStr = $now->toDateTimeString();
  4371. $dateTimeArr = explode(" ", $nowStr);
  4372. $dateArr = explode("-", $dateTimeArr[0]);
  4373. $year = substr($dateArr[0], 2);
  4374. $como = 'GEEQ';
  4375. $cldo = 'IN';
  4376. $fecr = $year . $dateArr[1] . $dateArr[2];
  4377. $sec = DB::table('S002V01TAFAL')->where([
  4378. ['AFAL_NULI', '=', $form['linea']],
  4379. ['AFAL_COMO', '=', $como],
  4380. ['AFAL_CLDO', '=', $cldo],
  4381. ])->orderBy('AFAL_NUSE', 'desc')->first();
  4382. $nuse = "";
  4383. if(is_null($sec)){
  4384. $nuse = '000001';
  4385. }else{
  4386. $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
  4387. $nuse = "";
  4388. for($i = strlen($secu); $i < 6; $i++){
  4389. $nuse .= "0";
  4390. }
  4391. $nuse = $nuse . $secu;
  4392. }
  4393. $equipmentCode = $fileDataArr['CODIGO'];
  4394. $equipmentCodeArr0 = explode('_', $equipmentCode);
  4395. $equipmentCodeArr1 = explode('.', $equipmentCodeArr0[1]);
  4396. $equipmentCodeArr1 = array_reverse($equipmentCodeArr1);
  4397. $timestamp = $now->timestamp;
  4398. $noar = "ficha_descriptiva_$equipmentCodeArr1[0]_$timestamp";
  4399. $exte = $form['file_type'] == 'XLS' ? "xlsx": 'pdf';
  4400. $ver = DB::table('S002V01TAFAL')->where([
  4401. ['AFAL_NULI', '=', $form['linea']],
  4402. ['AFAL_COMO', '=', $como],
  4403. ['AFAL_CLDO', '=', $cldo],
  4404. ['AFAL_NOAR', '=', $noar],
  4405. ['AFAL_EXTE', '=', $exte],
  4406. ])->orderBy('AFAL_NUVE', 'desc')->first();
  4407. $nuve = "";
  4408. if(is_null($ver)){
  4409. $nuve = "01";
  4410. }else{
  4411. $vers = intval($ver->AFAL_NUVE) + 1;
  4412. $nuve = $vers < 10 ? "0$vers" : "$vers";
  4413. }
  4414. $line = $form['linea'] < 10 ? "0$form[linea]" : "$form[linea]";
  4415. $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';
  4416. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  4417. $tempFile = $filePath . $fileName;
  4418. if(file_exists($tempFile)){
  4419. unlink($tempFile);
  4420. }
  4421. if($form['file_type'] == 'XLS'){
  4422. $writer = IOFactory::createWriter($spreadsheet, 'Xlsx');
  4423. }else{
  4424. $writer = new Mpdf($spreadsheet);
  4425. $writer->setOrientation(PageSetup::ORIENTATION_LANDSCAPE);
  4426. }
  4427. $writer->save($tempFile);
  4428. $ubic = Storage::putFile('files', new File($tempFile));
  4429. $ubic = str_replace("/", "\\", $ubic);
  4430. $ubic = "C:\inetpub\wwwroot\sam\storage\app\\" . $ubic;
  4431. $tama = filesize($ubic);
  4432. $usac = json_encode([$idUser]);
  4433. unlink($tempFile);
  4434. DB::table('S002V01TAFAL')->insert([
  4435. 'AFAL_NULI' => $line,
  4436. 'AFAL_COMO' => $como,
  4437. 'AFAL_CLDO' => $cldo,
  4438. 'AFAL_FECR' => $fecr,
  4439. 'AFAL_NUSE' => $nuse,
  4440. 'AFAL_NUVE' => $nuve,
  4441. 'AFAL_NOAR' => $noar,
  4442. 'AFAL_EXTE' => $exte,
  4443. 'AFAL_TAMA' => $tama,
  4444. 'AFAL_UBIC' => $ubic,
  4445. 'AFAL_USAC' => $usac,
  4446. 'AFAL_USRE' => $idUser,
  4447. 'AFAL_FERE' => $nowStr,
  4448. ]);
  4449. $actions = DB::getQueryLog();
  4450. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4451. $idac = $this->functionsController->registerActivity(
  4452. $line,
  4453. 'S002V01M07GEEQ',
  4454. 'S002V01F01ADEQ',
  4455. '-',
  4456. 'Registro',
  4457. "El usuario $name (" . $usr->USUA_IDUS . ") generó la ficha descriptiva del equipamiento #$equipmentCode.",
  4458. $idUser,
  4459. $nowStr,
  4460. );
  4461. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4462. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $this->encryptionController->encrypt($fileName)]);
  4463. }
  4464. private function generateEquipmentDataSheet($equipmentInfo) : Spreadsheet {
  4465. $spreadsheet = new Spreadsheet;
  4466. $spreadsheet->getProperties()
  4467. ->setCreator('STC')
  4468. ->setTitle('Ficha descriptiva de equipamiento.')
  4469. ->setSubject('Ficha equipamiento')
  4470. ->setKeywords('Ficha Técnica Equipamiento')
  4471. ->setCategory('Fichas técnicas');
  4472. $worksheet = $spreadsheet->getActiveSheet();
  4473. $worksheet->setTitle('FICHA DESCRIPTIVA');
  4474. $worksheet->mergeCells('B2:M2');
  4475. $worksheet->setCellValue('B2', $equipmentInfo['CODIGO'])->getStyle('B2')->getFill()
  4476. ->setFillType(Fill::FILL_SOLID)
  4477. ->getStartColor()->setRGB('B7BCC4');
  4478. $worksheet->getStyle('B2')->getFont()->setBold(true);
  4479. $worksheet->getStyle('B2')->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
  4480. $worksheet->getColumnDimension('B')->setWidth(16);
  4481. $worksheet->getColumnDimension('C')->setWidth(16);
  4482. $worksheet->getColumnDimension('D')->setWidth(16);
  4483. $worksheet->getColumnDimension('E')->setWidth(16);
  4484. $worksheet->getColumnDimension('F')->setWidth(16);
  4485. $worksheet->getColumnDimension('G')->setWidth(16);
  4486. $worksheet->getColumnDimension('H')->setWidth(16);
  4487. $worksheet->getColumnDimension('I')->setWidth(16);
  4488. $worksheet->getColumnDimension('J')->setWidth(16);
  4489. $worksheet->getColumnDimension('K')->setWidth(16);
  4490. $worksheet->getColumnDimension('L')->setWidth(16);
  4491. $worksheet->getColumnDimension('M')->setWidth(16);
  4492. /*INICIO COLUMNA 1*/
  4493. $worksheet->mergeCells('B3:E3');
  4494. $worksheet->setCellValue('B3', "Tipo: $equipmentInfo[TIPO_EQUIPAMIENTO]");
  4495. $worksheet->mergeCells('F3:I3');
  4496. $worksheet->setCellValue('F3', "Modelo: $equipmentInfo[MODELO]");
  4497. $worksheet->mergeCells('J3:M3');
  4498. $worksheet->setCellValue('J3', "ID: $equipmentInfo[ID_EQUIPAMIENTO]");
  4499. /*FIN COLUMNA 1*/
  4500. /*INICIO COLUMNA 2*/
  4501. $worksheet->mergeCells('B4:E4');
  4502. $worksheet->setCellValue('B4', "Familia: $equipmentInfo[FAMILIA]");
  4503. $worksheet->mergeCells('F4:I4');
  4504. $worksheet->setCellValue('F4', "Subfamilia: $equipmentInfo[SUBFAMILIA]");
  4505. $worksheet->mergeCells('J4:M4');
  4506. $worksheet->setCellValue('J4', "Estado: $equipmentInfo[ESTADO]");
  4507. /*FIN COLUMNA 2*/
  4508. /*INICIO COLUMNA 3*/
  4509. $worksheet->mergeCells('B5:E5');
  4510. $worksheet->setCellValue('B5', "Jerarquía: $equipmentInfo[JERARQUIA]");
  4511. $parentCode = is_null($equipmentInfo['EQUIPO_PADRE']) ? '-' : $equipmentInfo['EQUIPO_PADRE'];
  4512. $worksheet->mergeCells('F5:M5');
  4513. $worksheet->setCellValue('F5', "Equipo padre: $parentCode");
  4514. /*FIN COLUMNA 3*/
  4515. /*INICIO COLUMNA 4*/
  4516. $worksheet->mergeCells('B6:D6');
  4517. $worksheet->setCellValue('B6', "Tipo de codificación: $equipmentInfo[TIPO_CODIGO]");
  4518. $worksheet->mergeCells('E6:G6');
  4519. $worksheet->setCellValue('E6', "Ubicación de origen: $equipmentInfo[UBICACION_ORIGEN]");
  4520. $worksheet->mergeCells('H6:J6');
  4521. $worksheet->setCellValue('H6', "Nivel de origen: $equipmentInfo[NIVEL_ORIGEN]");
  4522. $worksheet->mergeCells('K6:M6');
  4523. $worksheet->setCellValue('K6', "Ocupación de origen: $equipmentInfo[OCUPACION_ORIGEN]");
  4524. /*FIN COLUMNA 4*/
  4525. /*INICIO COLUMNA 5*/
  4526. $worksheet->mergeCells('B7:D7');
  4527. $worksheet->setCellValue('B7', "Elemento de origen: $equipmentInfo[ELEMENTO_ORIGEN]");
  4528. $pccIntersection = is_null($equipmentInfo['INTERSECCION_PCC']) ? 'No aplica' : $equipmentInfo['INTERSECCION_PCC'];
  4529. $worksheet->mergeCells('E7:G7');
  4530. $worksheet->setCellValue('E7', "Intersección en PCC: $pccIntersection");
  4531. $pccPosition = is_null($equipmentInfo['POSICION_PCC']) ? 'No aplica' : $equipmentInfo['POSICION_PCC'];
  4532. $worksheet->mergeCells('H7:J7');
  4533. $worksheet->setCellValue('H7', "Posición en PCC: $pccPosition");
  4534. $pccPosition = is_null($equipmentInfo['KILOMETRO_ORIGEN']) ? 'No aplica' : $equipmentInfo['KILOMETRO_ORIGEN'];
  4535. $worksheet->mergeCells('K7:M7');
  4536. $worksheet->setCellValue('K7', "Kilómetro de origen: $pccPosition");
  4537. /*FIN COLUMNA 5*/
  4538. /*INICIO COLUMNA 6*/
  4539. $trainArea = is_null($equipmentInfo['AREA_TREN']) ? 'No aplica' : $equipmentInfo['AREA_TREN'];
  4540. $worksheet->mergeCells('B8:D8');
  4541. $worksheet->setCellValue('B8', "Área del tren: $trainArea");
  4542. $originElementSecuence = is_null($equipmentInfo['SECUENCIA_ELEMENTO_ORIGEN']) ? 'No aplica' : $equipmentInfo['SECUENCIA_ELEMENTO_ORIGEN'];
  4543. $worksheet->mergeCells('E8:G8');
  4544. $worksheet->setCellValue('E8', "Secuencia del elemento de origen: $originElementSecuence");
  4545. $originCodificationType = is_null($equipmentInfo['TIPO_CODIFICACION_ORIGEN']) ? 'No aplica' : $equipmentInfo['TIPO_CODIFICACION_ORIGEN'];
  4546. $worksheet->mergeCells('H8:J8');
  4547. $worksheet->setCellValue('H8', "Tipo de codificación de origen: $originCodificationType");
  4548. $originElementCode = is_null($equipmentInfo['CODIGO_ELEMENTO_ORIGEN']) ? 'No aplica' : $equipmentInfo['CODIGO_ELEMENTO_ORIGEN'];
  4549. $worksheet->mergeCells('K8:M8');
  4550. $worksheet->setCellValue('K8', "Código del elemento de origen: $originElementCode");
  4551. /*FIN COLUMNA 6*/
  4552. /*INICIO COLUMNA 7*/
  4553. $destinyLocation = is_null($equipmentInfo['UBICACION_DESTINO']) ? 'No aplica' : $equipmentInfo['UBICACION_DESTINO'];
  4554. $worksheet->mergeCells('B9:D9');
  4555. $worksheet->setCellValue('B9', "Ubicación de destino: $destinyLocation");
  4556. $destinyLevel = is_null($equipmentInfo['NIVEL_DESTINO']) ? 'No aplica' : $equipmentInfo['NIVEL_DESTINO'];
  4557. $worksheet->mergeCells('E9:G9');
  4558. $worksheet->setCellValue('E9', "Nivel de destino: $destinyLevel");
  4559. $destinyOccupation = is_null($equipmentInfo['OCUPACION_DESTINO']) ? 'No aplica' : $equipmentInfo['OCUPACION_DESTINO'];
  4560. $worksheet->mergeCells('H9:J9');
  4561. $worksheet->setCellValue('H9', "Ocupación de destino: $destinyOccupation");
  4562. $destinyElement = is_null($equipmentInfo['ELEMENTO_DESTINO']) ? 'No aplica' : $equipmentInfo['ELEMENTO_DESTINO'];
  4563. $worksheet->mergeCells('K9:M9');
  4564. $worksheet->setCellValue('K9', "Elemento de destino: $destinyElement");
  4565. /*FIN COLUMNA 7*/
  4566. /*INICIO COLUMNA 8*/
  4567. $destinyKilometer = is_null($equipmentInfo['KILOMETRO_DESTINO']) ? 'No aplica' : $equipmentInfo['KILOMETRO_DESTINO'];
  4568. $worksheet->mergeCells('B10:D10');
  4569. $worksheet->setCellValue('B10', "Kilómetro de destino: $destinyKilometer");
  4570. $destinyElementSecuence = is_null($equipmentInfo['SECUENCIA_ELEMENTO_DESTINO']) ? 'No aplica' : $equipmentInfo['SECUENCIA_ELEMENTO_DESTINO'];
  4571. $worksheet->mergeCells('E10:G10');
  4572. $worksheet->setCellValue('E10', "Secuencia del elemento de destino: $destinyElementSecuence");
  4573. $destinyCodificationType = is_null($equipmentInfo['TIPO_CODIFICACION_DESTINO']) ? 'No aplica' : $equipmentInfo['TIPO_CODIFICACION_DESTINO'];
  4574. $worksheet->mergeCells('H10:J10');
  4575. $worksheet->setCellValue('H10', "Tipo de codificación de destino: $destinyCodificationType");
  4576. $destinyElementCode = is_null($equipmentInfo['CODIGO_ELEMENTO_DESTINO']) ? 'No aplica' : $equipmentInfo['CODIGO_ELEMENTO_DESTINO'];
  4577. $worksheet->mergeCells('K10:M10');
  4578. $worksheet->setCellValue('K10', "Código del elemento de destino: $destinyElementCode");
  4579. /*FIN COLUMNA 8*/
  4580. /*INICIO COLUMNA 9*/
  4581. $criticalityLevel = !isset($equipmentInfo['NIVEL_CRITICIDAD_OBJ']) ? 'No configurado' : $equipmentInfo['NIVEL_CRITICIDAD_OBJ']['label'];
  4582. $worksheet->mergeCells('B11:D11');
  4583. $worksheet->setCellValue('B11', "Nivel de criticidad de seguridad: $criticalityLevel");
  4584. $worksheet->mergeCells('E11:G11');
  4585. $worksheet->setCellValue('E11', "Fecha de adquisición: $equipmentInfo[FECHA_ADQUISICION]");
  4586. $worksheet->mergeCells('H11:J11');
  4587. $worksheet->setCellValue('H11', "Fecha de inicio de la garantía: $equipmentInfo[FECHA_INICIO_GARANTIA]");
  4588. $worksheet->mergeCells('K11:M11');
  4589. $worksheet->setCellValue('K11', "Fecha de término de la garantía: $equipmentInfo[FECHA_TERMINO_GARANTIA]");
  4590. /*FIN COLUMNA 9*/
  4591. /*INICIO COLUMNA 10*/
  4592. $worksheet->mergeCells('B12:D12');
  4593. $worksheet->setCellValue('B12', "Proveedor: $equipmentInfo[PROVEEDOR]");
  4594. $requiredSoftware = is_null($equipmentInfo['TIPO_CODIFICACION_DESTINO']) ? 'Ningúno' : $equipmentInfo['TIPO_CODIFICACION_DESTINO'];
  4595. $worksheet->mergeCells('E12:G12');
  4596. $worksheet->setCellValue('E12', "Software requerido: $requiredSoftware");
  4597. $softwareVersion = is_null($equipmentInfo['VERSION_SOFTWARE']) ? 'No aplica' : $equipmentInfo['VERSION_SOFTWARE'];
  4598. $worksheet->mergeCells('H12:J12');
  4599. $worksheet->setCellValue('H12', "Versión del software: $softwareVersion");
  4600. $worksheet->mergeCells('K12:M12');
  4601. $worksheet->setCellValue('K12', "Estado de funcionamiento: $equipmentInfo[ESTADO_FUNCIONAMIENTO]");
  4602. /*FIN COLUMNA 10*/
  4603. /*INICIO COLUMNA 11*/
  4604. $worksheet->mergeCells('B13:G13');
  4605. $worksheet->setCellValue('B13', "Usuario que registró: $equipmentInfo[USUARIO_REGISTRO]");
  4606. $worksheet->mergeCells('H13:M13');
  4607. $worksheet->setCellValue('H13', "Fecha de registro: $equipmentInfo[FECHA_REGISTRO]");
  4608. /*FIN COLUMNA 11*/
  4609. /*INICIO COLUMNA 12*/
  4610. $usrMod = is_null($equipmentInfo['USUARIO_MODIFICACION']) ? '-' : $equipmentInfo['USUARIO_MODIFICACION'];
  4611. $worksheet->mergeCells('B14:G14');
  4612. $worksheet->setCellValue('B14', "Usuario que modificó: $usrMod");
  4613. $fecMod = is_null($equipmentInfo['FECHA_MODIFICACION']) ? '-' : $equipmentInfo['FECHA_MODIFICACION'];
  4614. $worksheet->mergeCells('H14:M14');
  4615. $worksheet->setCellValue('H14', "Fecha última modificación: $fecMod");
  4616. /*FIN COLUMNA 12*/
  4617. $startRow = 2;
  4618. $startCol = 2;
  4619. $maxRow = $startRow + 12;
  4620. $maxCol = $startCol + 11;
  4621. for($row = $startRow; $row <= $maxRow; $row++){
  4622. for($col = $startCol; $col <= $maxCol; $col++){
  4623. $colStr = Coordinate::stringFromColumnIndex($col);
  4624. $worksheet->getStyle($colStr . $row)->getBorders()->getOutline()->setBorderStyle(Border::BORDER_THIN)->setColor(new Color('55000000'));
  4625. }
  4626. }
  4627. return $spreadsheet;
  4628. }
  4629. public function getEquipmentTypes($idUser, $line){
  4630. DB::enableQueryLog();
  4631. $idUser = $this->encryptionController->decrypt($idUser);
  4632. if(!$idUser){
  4633. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4634. }
  4635. $usr = DB::table('S002V01TUSUA')->where([
  4636. ['USUA_NULI', '=', $line],
  4637. ['USUA_IDUS', '=', $idUser],
  4638. ])->first();
  4639. if(is_null($usr)){
  4640. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4641. }
  4642. $equipmentTypes = DB::table('S002V01TEQUI')->select([
  4643. DB::raw('COUNT(*) AS CANTIDAD_EQUIPAMIENTOS'),
  4644. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  4645. ])->groupBy('EQUI_TIPO')->get()->all();
  4646. $now = $this->functionsController->now();
  4647. $nowStr = $now->toDateTimeString();
  4648. $actions = DB::getQueryLog();
  4649. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4650. $idac = $this->functionsController->registerActivity(
  4651. $line,
  4652. 'S002V01M07GEEQ',
  4653. 'S002V01F01ADEQ',
  4654. 'S002V01P12GCTE',
  4655. 'Consulta',
  4656. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la cantidad de equipamientos por tipo.",
  4657. $idUser,
  4658. $nowStr,
  4659. );
  4660. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4661. return $this->responseController->makeResponse(false, 'EXITO.', $equipmentTypes);
  4662. }
  4663. public function getEquipmentsByType($equipmentType, $idUser, $line) {
  4664. DB::enableQueryLog();
  4665. $idUser = $this->encryptionController->decrypt($idUser);
  4666. if(!$idUser){
  4667. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4668. }
  4669. $usr = DB::table('S002V01TUSUA')->where([
  4670. ['USUA_NULI', '=', $line],
  4671. ['USUA_IDUS', '=', $idUser],
  4672. ])->first();
  4673. if(is_null($usr)){
  4674. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4675. }
  4676. $equipmentType = urldecode($equipmentType);
  4677. $equipments = DB::table('S002V01TEQUI')->select([
  4678. 'EQUI_COEQ AS CODIGO',
  4679. 'EQUI_TIPO AS TIPO',
  4680. 'EQUI_MODE AS MODELO',
  4681. 'EQUI_IDEQ AS ID_EQUIPO',
  4682. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  4683. 'EQUI_GAIM AS GALERIA_IMAGENES',
  4684. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  4685. 'EQUI_TICO AS TIPO_CODIGO',
  4686. 'EQUI_EQPA AS EQUIPO_PADRE',
  4687. ])->where([
  4688. ['EQUI_NULI', '=', $line],
  4689. ['EQUI_TIPO', '=', $equipmentType],
  4690. ])->get()->all();
  4691. $idUserEnc = $this->encryptionController->encrypt($idUser);
  4692. foreach($equipments as $key=>$equipment){
  4693. $children = DB::table('S002V01TEQUI')->where([
  4694. ['EQUI_NULI', '=', $line],
  4695. ['EQUI_EQPA', '=', $equipment->CODIGO],
  4696. ])->get()->all();
  4697. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  4698. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  4699. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  4700. $imagesGalleryArr = json_decode($equipment->GALERIA_IMAGENES, true);
  4701. $imagesGalleryFn = [];
  4702. foreach($imagesGalleryArr as $imageCode){
  4703. $imageCodeEnc = $this->encryptionController->encrypt($imageCode);
  4704. $publicUri = $this->documentManagementController->privateGetPublicDocumentURL(
  4705. $imageCodeEnc,
  4706. $idUserEnc,
  4707. $line
  4708. );
  4709. $response = json_decode($publicUri->original, true);
  4710. if($response['error']){
  4711. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  4712. }else{
  4713. $uriEnc = $this->encryptionController->encrypt($response['response']['public_uri']);
  4714. $imagesGalleryFn[] = $uriEnc;
  4715. }
  4716. }
  4717. $equipment->GALERIA_IMAGENES = json_encode($imagesGalleryFn);
  4718. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  4719. $equipments[$key] = $equipment;
  4720. }
  4721. $now = $this->functionsController->now();
  4722. $nowStr = $now->toDateTimeString();
  4723. $actions = DB::getQueryLog();
  4724. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4725. $idac = $this->functionsController->registerActivity(
  4726. $line,
  4727. 'S002V01M07GEEQ',
  4728. 'S002V01F01ADEQ',
  4729. 'S002V01P12GCTE',
  4730. 'Consulta',
  4731. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos de tipo $equipmentType.",
  4732. $idUser,
  4733. $nowStr,
  4734. );
  4735. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4736. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  4737. }
  4738. public function getEquipmentsByKilometer($startPK, $endPK, $idUser, $line) {
  4739. DB::enableQueryLog();
  4740. $idUser = $this->encryptionController->decrypt($idUser);
  4741. if(!$idUser){
  4742. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4743. }
  4744. $usr = DB::table('S002V01TUSUA')->where([
  4745. ['USUA_NULI', '=', $line],
  4746. ['USUA_IDUS', '=', $idUser],
  4747. ])->first();
  4748. if(is_null($usr)){
  4749. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4750. }
  4751. $startPK = floatval($startPK);
  4752. $endPK = floatVal($endPK);
  4753. $equipments = DB::table('S002V01TEQUI')->select([
  4754. 'EQUI_COEQ AS CODIGO',
  4755. 'EQUI_TIPO AS TIPO',
  4756. 'EQUI_MODE AS MODELO',
  4757. 'EQUI_IDEQ AS ID_EQUIPO',
  4758. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  4759. 'EQUI_GAIM AS GALERIA_IMAGENES',
  4760. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  4761. 'EQUI_TICO AS TIPO_CODIGO',
  4762. 'EQUI_EQPA AS EQUIPO_PADRE',
  4763. 'EQUI_KIOR AS KILOMETRO_ORIGEN',
  4764. 'EQUI_KIDE AS KILOMETRO_DESTINO'
  4765. ])->where('EQUI_NULI', '=', $line)
  4766. ->whereBetween('EQUI_KIOR', [$startPK, $endPK])
  4767. ->orWhereBetween('EQUI_KIDE', [$startPK, $endPK])->get()->all();
  4768. foreach($equipments as $key=>$equipment){
  4769. $children = DB::table('S002V01TEQUI')->where([
  4770. ['EQUI_NULI', '=', $line],
  4771. ['EQUI_EQPA', '=', $equipment->CODIGO],
  4772. ])->get()->all();
  4773. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  4774. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  4775. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  4776. $equipment->GALERIA_IMAGENES = $this->encryptionController->encrypt($equipment->GALERIA_IMAGENES);
  4777. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  4778. $equipments[$key] = $equipment;
  4779. }
  4780. $now = $this->functionsController->now();
  4781. $nowStr = $now->toDateTimeString();
  4782. $actions = DB::getQueryLog();
  4783. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4784. $idac = $this->functionsController->registerActivity(
  4785. $line,
  4786. 'S002V01M07GEEQ',
  4787. 'S002V01F01ADEQ',
  4788. 'S002V01P13LOEQ',
  4789. 'Consulta',
  4790. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos entre los kilómetros $startPK y $endPK.",
  4791. $idUser,
  4792. $nowStr,
  4793. );
  4794. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4795. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  4796. }
  4797. public function getEquipmentsByTrainArea($car, $area, $idUser, $line) {
  4798. DB::enableQueryLog();
  4799. $idUser = $this->encryptionController->decrypt($idUser);
  4800. if(!$idUser){
  4801. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4802. }
  4803. $usr = DB::table('S002V01TUSUA')->where([
  4804. ['USUA_NULI', '=', $line],
  4805. ['USUA_IDUS', '=', $idUser],
  4806. ])->first();
  4807. if(is_null($usr)){
  4808. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4809. }
  4810. $car = $this->encryptionController->decrypt($car);
  4811. if(!$car){
  4812. return $this->responseController->makeResponse(true, 'El código del coche no está encriptado correctamente', [], 400);
  4813. }
  4814. $area = $this->encryptionController->decrypt($area);
  4815. if(!$area){
  4816. return $this->responseController->makeResponse(true, 'El código del área no está encriptado correctamente', [], 400);
  4817. }
  4818. $equipments = DB::table('S002V01TEQUI')->select([
  4819. 'EQUI_COEQ AS CODIGO',
  4820. 'EQUI_TIPO AS TIPO',
  4821. 'EQUI_MODE AS MODELO',
  4822. 'EQUI_IDEQ AS ID_EQUIPO',
  4823. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  4824. 'EQUI_GAIM AS GALERIA_IMAGENES',
  4825. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  4826. 'EQUI_TICO AS TIPO_CODIGO',
  4827. 'EQUI_EQPA AS EQUIPO_PADRE',
  4828. ])->where([
  4829. ['EQUI_NULI', '=', $line],
  4830. ['EQUI_OCOR', '=', $car],
  4831. ['EQUI_ARTR', '=', $area]
  4832. ])->get()->all();
  4833. foreach($equipments as $key=>$equipment){
  4834. $children = DB::table('S002V01TEQUI')->where([
  4835. ['EQUI_NULI', '=', $line],
  4836. ['EQUI_EQPA', '=', $equipment->CODIGO],
  4837. ])->get()->all();
  4838. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  4839. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  4840. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  4841. $equipment->GALERIA_IMAGENES = $this->encryptionController->encrypt($equipment->GALERIA_IMAGENES);
  4842. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  4843. $equipments[$key] = $equipment;
  4844. }
  4845. $now = $this->functionsController->now();
  4846. $nowStr = $now->toDateTimeString();
  4847. $actions = DB::getQueryLog();
  4848. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4849. $idac = $this->functionsController->registerActivity(
  4850. $line,
  4851. 'S002V01M07GEEQ',
  4852. 'S002V01F01ADEQ',
  4853. 'S002V01P13LOEQ',
  4854. 'Consulta',
  4855. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos del área $area en el coche $car.",
  4856. $idUser,
  4857. $nowStr,
  4858. );
  4859. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4860. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  4861. }
  4862. public function getEquipmentsByPCCIntersection($intersection, $element, $idUser, $line) {
  4863. DB::enableQueryLog();
  4864. $idUser = $this->encryptionController->decrypt($idUser);
  4865. if(!$idUser){
  4866. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4867. }
  4868. $usr = DB::table('S002V01TUSUA')->where([
  4869. ['USUA_NULI', '=', $line],
  4870. ['USUA_IDUS', '=', $idUser],
  4871. ])->first();
  4872. if(is_null($usr)){
  4873. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4874. }
  4875. $intersection = $this->encryptionController->decrypt($intersection);
  4876. if(!$intersection){
  4877. return $this->responseController->makeResponse(true, 'La interección no está encriptada correctamente', [], 400);
  4878. }
  4879. $element = $this->encryptionController->decrypt($element);
  4880. if(!$element){
  4881. return $this->responseController->makeResponse(true, 'El elemento de la intersección no está encriptado correctamente', [], 400);
  4882. }
  4883. $equipments = DB::table('S002V01TEQUI')->select([
  4884. 'EQUI_COEQ AS CODIGO',
  4885. 'EQUI_TIPO AS TIPO',
  4886. 'EQUI_MODE AS MODELO',
  4887. 'EQUI_IDEQ AS ID_EQUIPO',
  4888. 'EQUI_ESFU AS ESTADO_FUNCIONAMIENTO',
  4889. 'EQUI_GAIM AS GALERIA_IMAGENES',
  4890. 'EQUI_ELOR AS ELEMENTO_ORIGEN',
  4891. 'EQUI_TICO AS TIPO_CODIGO',
  4892. 'EQUI_EQPA AS EQUIPO_PADRE',
  4893. ])->where([
  4894. ['EQUI_NULI', '=', $line],
  4895. ['EQUI_IPCC', '=', $intersection],
  4896. ])->orWhere([
  4897. ['EQUI_ELOR', 'LIKE', "%$element%"],
  4898. ['EQUI_ELDE', 'LIKE', "%$element%"],
  4899. ])->get()->all();
  4900. foreach($equipments as $key=>$equipment){
  4901. $children = DB::table('S002V01TEQUI')->where([
  4902. ['EQUI_NULI', '=', $line],
  4903. ['EQUI_EQPA', '=', $equipment->CODIGO],
  4904. ])->get()->all();
  4905. $equipment->CODIGO = $this->encryptionController->encrypt($equipment->CODIGO);
  4906. $equipment->ID_EQUIPO = $this->encryptionController->encrypt($equipment->ID_EQUIPO);
  4907. $equipment->EQUIPO_PADRE = is_null($equipment->EQUIPO_PADRE) ? null : $this->encryptionController->encrypt($equipment->EQUIPO_PADRE);
  4908. $equipment->GALERIA_IMAGENES = $this->encryptionController->encrypt($equipment->GALERIA_IMAGENES);
  4909. $equipment->TIENE_HIJOS = count($children) > 0 ? 'Si' : 'No';
  4910. $equipments[$key] = $equipment;
  4911. }
  4912. $now = $this->functionsController->now();
  4913. $nowStr = $now->toDateTimeString();
  4914. $actions = DB::getQueryLog();
  4915. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4916. $idac = $this->functionsController->registerActivity(
  4917. $line,
  4918. 'S002V01M07GEEQ',
  4919. 'S002V01F01ADEQ',
  4920. 'S002V01P13LOEQ',
  4921. 'Consulta',
  4922. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los equipamientos de la intersección $intersection del PCC",
  4923. $idUser,
  4924. $nowStr,
  4925. );
  4926. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4927. return $this->responseController->makeResponse(false, 'EXITO.', $equipments);
  4928. }
  4929. public function getArborescenceByDate($date, $idUser, $line) {
  4930. DB::enableQueryLog();
  4931. $idUser = $this->encryptionController->decrypt($idUser);
  4932. if(!$idUser){
  4933. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  4934. }
  4935. $usr = DB::table('S002V01TUSUA')->where([
  4936. ['USUA_NULI', '=', $line],
  4937. ['USUA_IDUS', '=', $idUser],
  4938. ])->first();
  4939. if(is_null($usr)){
  4940. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  4941. }
  4942. $dateArr = explode('-', $date);
  4943. if(count($dateArr) != 3){
  4944. return $this->responseController->makeResponse(true, 'La fecha enviada no tiene un formato correcto YYYY-MM-DD.', [], 400);
  4945. }
  4946. $validDate = checkdate(intval($dateArr[1]), intval($dateArr[2]), intval($dateArr[0]));
  4947. if(!$validDate){
  4948. return $this->responseController->makeResponse(true, 'La fecha enviada es inválida.', [], 400);
  4949. }
  4950. $searchDate = new Carbon($date);
  4951. //CONSTRUCCIÓN DE LA ARBORESCENCIA
  4952. //Paso 1: Consultar las familias
  4953. $families = DB::table('S002V01TFAMI')->select([
  4954. 'FAMI_COFA AS CODIGO_FAMILIA',
  4955. 'FAMI_NOFA AS NOMBRE_FAMILIA',
  4956. ])->where([
  4957. ['FAMI_ESTA', '=', 'Activo'],
  4958. ['FAMI_NULI', '=', $line]
  4959. ])->get()->all();
  4960. $familyArborescenceArr = [];
  4961. foreach($families as $family){
  4962. //Paso 2: Consultar las subfamilias de cada familia
  4963. $subfamilies = DB::table('S002V01TSUBF')->select([
  4964. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  4965. 'SUBF_NOSU AS NOMBRE_SUBFAMILIA',
  4966. ])->where([
  4967. ['SUBF_NULI', '=', $line],
  4968. ['SUBF_COFA', '=', $family->CODIGO_FAMILIA],
  4969. ['SUBF_ESTA', '=', 'Activo']
  4970. ])->get()->all();
  4971. $subfamilyArborescenceArr = [];
  4972. foreach($subfamilies as $subfamily){
  4973. //Paso 3: Consultar los equipamientos padre
  4974. $equipments = DB::table('S002V01TEQUI')->select([
  4975. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  4976. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  4977. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  4978. 'EQUI_HICO AS HISTORIAL_CODIGOS'
  4979. ])->where([
  4980. ['EQUI_NULI', '=', $line],
  4981. ['EQUI_FAMI', '=', $family->CODIGO_FAMILIA],
  4982. ['EQUI_SUBF', '=', $subfamily->CODIGO_SUBFAMILIA],
  4983. ['EQUI_JERA', '=', 'Padre'],
  4984. ])->get()->all();
  4985. $equipmentArborescenceArr = [];
  4986. foreach($equipments as $equipment){
  4987. $codesHistory = json_decode($equipment->HISTORIAL_CODIGOS, true);
  4988. $codeFilt = array_filter($codesHistory, function($v, $k) use ($searchDate){
  4989. $codeDate = new Carbon($v['FECHA']);
  4990. return $codeDate->lte($searchDate);
  4991. }, ARRAY_FILTER_USE_BOTH);
  4992. if(count($codeFilt) > 0){
  4993. $lastCode = end($codeFilt);
  4994. $children = $this->getEquipmentChildren(
  4995. $lastCode['CODIGO'],
  4996. $line,
  4997. $family,
  4998. $subfamily,
  4999. $searchDate
  5000. );
  5001. $equipmentElement = $lastCode['CODIGO'] . ' - ' . $equipment->TIPO_EQUIPAMIENTO . ' - ' . $equipment->MODELO_EQUIPAMIENTO . ' (' . $equipment->ID_EQUIPAMIENTO . ')';
  5002. $equipmentArborescenceArr[] = [
  5003. 'ELEMENTO' => $this->encryptionController->encrypt($equipmentElement),
  5004. 'HIJOS' => $children,
  5005. ];
  5006. }
  5007. }
  5008. $subfamilyElement = $subfamily->NOMBRE_SUBFAMILIA . ' (' . $subfamily->CODIGO_SUBFAMILIA . ')';
  5009. $subfamilyArborescenceArr[] = [
  5010. 'ELEMENTO' => $this->encryptionController->encrypt($subfamilyElement),
  5011. 'HIJOS' => $equipmentArborescenceArr,
  5012. ];
  5013. }
  5014. $familyElement = $family->NOMBRE_FAMILIA . ' (' . $family->CODIGO_FAMILIA . ')';
  5015. $familyArborescenceArr[] = [
  5016. 'ELEMENTO' => $this->encryptionController->encrypt($familyElement),
  5017. 'HIJOS' => $subfamilyArborescenceArr,
  5018. ];
  5019. }
  5020. $now = $this->functionsController->now();
  5021. $nowStr = $now->toDateTimeString();
  5022. $actions = DB::getQueryLog();
  5023. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  5024. $idac = $this->functionsController->registerActivity(
  5025. $line,
  5026. 'S002V01M07GEEQ',
  5027. 'S002V01F01ADEQ',
  5028. 'S002V01P14VAFD',
  5029. 'Consulta',
  5030. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la arborescencia en la fecha $date",
  5031. $idUser,
  5032. $nowStr,
  5033. );
  5034. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  5035. return $this->responseController->makeResponse(false, 'EXITO.', $familyArborescenceArr);
  5036. }
  5037. private function getEquipmentChildren($equipmentCode, $line, $family, $subfamily, $searchDate) {
  5038. $children = DB::table('S002V01TEQUI')->select([
  5039. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  5040. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  5041. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  5042. 'EQUI_HICO AS HISTORIAL_CODIGOS'
  5043. ])->where([
  5044. ['EQUI_NULI', '=', $line],
  5045. ['EQUI_FAMI', '=', $family->CODIGO_FAMILIA],
  5046. ['EQUI_SUBF', '=', $subfamily->CODIGO_SUBFAMILIA],
  5047. ['EQUI_JERA', '=', 'Hijo'],
  5048. ])->whereRaw("JSON_SEARCH(
  5049. EQUI_HICO, 'one', ?, NULL, '$[*].PADRE'
  5050. )", [$equipmentCode])->get()->all();
  5051. $childrenFn = [];
  5052. foreach($children as $child){
  5053. $codesHistory = json_decode($child->HISTORIAL_CODIGOS, true);
  5054. $codeFilt = array_filter($codesHistory, function($v, $k) use ($searchDate){
  5055. $codeDate = new Carbon($v['FECHA']);
  5056. return $codeDate->lte($searchDate);
  5057. }, ARRAY_FILTER_USE_BOTH);
  5058. if(count($codeFilt) > 0){
  5059. $lastCode = end($codeFilt);
  5060. $children = $this->getEquipmentChildren(
  5061. $lastCode['CODIGO'],
  5062. $line,
  5063. $family,
  5064. $subfamily,
  5065. $searchDate
  5066. );
  5067. $childElement = $lastCode['CODIGO'] . ' - ' . $child->TIPO_EQUIPAMIENTO . ' - ' . $child->MODELO_EQUIPAMIENTO . ' (' . $child->ID_EQUIPAMIENTO . ')';
  5068. $childrenFn[] = [
  5069. 'ELEMENTO' => $this->encryptionController->encrypt($childElement),
  5070. 'HIJOS' => $children,
  5071. ];
  5072. }
  5073. }
  5074. return $childrenFn;
  5075. }
  5076. }