EquipmentManagementController.php 330 KB

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