EquipmentManagementController.php 322 KB

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