EquipmentManagementController.php 272 KB

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