EquipmentManagementController.php 337 KB

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