EquipmentManagementController.php 337 KB

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