EquipmentManagementController.php 275 KB

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