EquipmentManagementController.php 322 KB

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