| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Support\Carbon;
- use Carbon\Exceptions\InvalidFormatException;
- use ElephantIO\Client;
- use Exception;
- use Illuminate\Validation\Rule;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Http\File;
- use Dompdf\Dompdf;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- use PhpOffice\PhpSpreadsheet\Style\Fill;
- use PhpOffice\PhpSpreadsheet\Style\Alignment;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- class CorrectiveMaintenanceController extends Controller{
- private $responseController;
- private $encryptionController;
- private $functionsController;
- private $documentManagementController;
- private $notificationsController;
- private $templatesUbic;
- public function __construct(){
- $this->responseController = new ResponseController();
- $this->encryptionController = new EncryptionController();
- $this->functionsController = new FunctionsController();
- $this->documentManagementController = new DocumentManagementController();
- $this->notificationsController = new NotificationsController();
- $this->templatesUbic = $this->functionsController->getBasePath() . "\storage\app\public\pdf_templates\\01_04_GMCO\\";
- }
- private function getSocketClient(){
- $url = 'http://localhost:3200';
- $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
- $socketClient->initialize();
- $socketClient->of('/');
- return $socketClient;
- }
- public function registerWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_responsible' => 'required|string',
- 'type_responsible' => 'required|string|in:U,S',
- 'description' => 'required|string|min:15',
- 'equipment' => 'required|string',
- 'start_date_time' => 'required|date',
- 'solution_time' => 'required|numeric',
- 'priority' => 'required|string',
- 'id_counter' => 'required|string',
- 'id_last_measure' => 'required|string',
- 'clasification' => 'required|string|max:50',
- 'staff' => 'required|json',
- 'security_management' => 'required|string',
- 'activation_type' => 'required|string|in:Manual,Automática',
- 'resources' => 'required|json',
- 'attached' => 'json',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
-
- $idUserResponsible = $this->encryptionController->decrypt($form['id_responsible']);
- if(!$idUserResponsible){
- return $this->responseController->makeResponse(true, 'El ID del usuario responsable no fue encriptado correctamente.', [], 400);
- }
- $usrResponsible = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUserResponsible]
- ])->first();
-
- if(is_null($usrResponsible)){
- return $this->responseController->makeResponse(true, 'El usuario responsable de atender la solicitud no existe.', [], 404);
- }
- $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
- if(!$equipmentCode){
- return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
- }
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $form['linea']],
- ['EQUI_COEQ', '=', $equipmentCode],
- ])->first();
-
- if(is_null($equipment)){
- return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404);
- }
- if(floatval($form['solution_time']) <= 0){
- return $this->responseController->makeResponse(true, 'El tiempo de solución estimado debe ser mayor a cero.', [], 400);
- }
- $priority = $this->encryptionController->decrypt($form['priority']);
- if(!$priority){
- return $this->responseController->makeResponse(true, 'La prioridad relacionada no fue encriptada correctamente.', [], 400);
- }
- $validPriorities = ['1', '2', '3', '4'];
- if(!in_array($priority, $validPriorities)){
- return $this->responseController->makeResponse(true, 'La prioridad relacionada es inválida.', [], 400);
- }
- $idCounter = $this->encryptionController->decrypt($form['id_counter']);
- if(!$idCounter){
- return $this->responseController->makeResponse(true, 'El ID del contador relacionado no fue encriptado correctamente.', [], 400);
- }
- $counter = DB::table('S002V01TCONA')->where([
- ['CONA_IDCO', '=', $idCounter],
- ['CONA_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($counter)){
- return $this->responseController->makeResponse(true, 'El contador relacionado no existe.', [], 404);
- }
- $idLastMeasure = $this->encryptionController->decrypt($form['id_last_measure']);
- if(!$idLastMeasure){
- return $this->responseController->makeResponse(true, 'El ID de la última medida del contador relacionado no fue encriptado correctamente.', [], 400);
- }
- $lastMeasure = DB::table('S002V01TMEDI')->select([
- 'MEDI_IDME AS ID_MEDIDA',
- 'MEDI_CORE AS CONTADOR',
- 'MEDI_VALO AS VALOR',
- 'MEDI_WSRE AS ID_SERVICIO_WEB',
- 'LSWE_URLX AS URL_SERVICIO_WEB',
- 'MEDI_HORE AS HORA_REGISTRO',
- ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
- ['MEDI_IDME', '=', $idLastMeasure],
- ['MEDI_NULI', '=', $form['linea']],
- ['MEDI_CORE', '=', $idCounter]
- ])->orderBy('MEDI_HORE', 'desc')->first();
-
- if(is_null($lastMeasure)){
- return $this->responseController->makeResponse(true, 'La última medida del contador relacionado no existe.', [], 404);
- }
- $staffArr = json_decode($form['staff'], true);
- if(count($staffArr) == 0){
- return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400);
- }
- $staff = [];
- foreach($staffArr as $key=>$specialty){
- $specialtyDec = $this->encryptionController->decrypt($specialty['SPECIALTY']);
- if(!$specialtyDec){
- return $this->responseController->makeResponse(true, "El código en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
- }
- $specialtyObj = DB::table('S002V01TGEES')->where([
- ['GEES_NULI', '=', $form['linea']],
- ['GEES_COES', '=', $specialtyDec]
- ])->first();
- if(is_null($specialtyObj)){
- return $this->responseController->makeResponse(true, "El item en la posición $key del arreglo de especialidades no existe.", [], 404);
- }
- $staff[] = [
- 'ID' => $specialtyDec,
- 'CANT' => $specialty['CANT']
- ];
- }
- $staffStrFn = json_encode($staff);
- $idManagement = $this->encryptionController->decrypt($form['security_management']);
- if(!$idManagement){
- return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
- }
- $management = DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_IDGS', '=', $idManagement]
- ])->first();
- if(is_null($management)){
- return $this->responseController->makeResponse(true, 'La gerencia de seguridad seleccionada no está registrada.', [], 404);
- }
- $resources = json_decode($form['resources'], true);
- if(empty($resources)){
- return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
- }
- foreach($resources as $key=>$item){
- if(!array_key_exists('ID', $item)){
- return $this->responseController->makeResponse(true, "No se pudo encontrar el ID del elemento en la posición $key del arreglo de recursos.", [], 400);
- }
- if($item['ID'] != 'SH'){
- $idItemDec = $this->encryptionController->decrypt($item['ID']);
- $resource = DB::table('S002V01TINST')->where([
- ['INST_NULI', '=', $form['linea']],
- ['INST_IDIS', '=', $idItemDec],
- ])->first();
- if(is_null($resource)){
- return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de recursos no existe.", [], 404);
- }
- $item['ID'] = $idItemDec;
- }
- $resources[$key] = $item;
- }
- $rhut = json_encode($resources);
- $attachedArrFn = [];
- if(isset($form['attached'])){
- $attachedArr = json_decode($form['attached'], true);
- foreach($attachedArr as $key=>$attached){
- $idDec = $this->encryptionController->decrypt($attached['id']);
- if(!$idDec){
- return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
- }
- if($attached['type'] == 'Existente'){
- $codeArr = explode('=', $idDec);
- $codeArr0 = explode('-', $codeArr[0]);
- $file = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $form['linea']],
- ['AFAL_COMO', '=', $codeArr0[1]],
- ['AFAL_CLDO', '=', $codeArr0[2]],
- ['AFAL_FECR', '=', $codeArr0[3]],
- ['AFAL_NUSE', '=', $codeArr0[4]],
- ['AFAL_NUVE', '=', $codeArr[1]],
- ])->first();
- if(is_null($file)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($file->AFAL_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
- $attachedArrFn[] = $idDec;
- }else if($attached['type'] == 'Nuevo'){
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $idDec],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($tempFile->ARTE_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
- $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
- if(!$finalFile[0]){
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- }else{
- $attachedArrFn[] = $finalFile[1];
- }
- }
- }
- }
- $activationType = $form['activation_type'][0];
- $attachedStrFn = json_encode($attachedArrFn);
- $lastMeasureStr = json_encode($lastMeasure);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryStr = json_encode([
- ['USUARIO' => $idUser, 'ESTADO' => 'PE', 'FECHA' => $nowStr]
- ]);
- $orderID = DB::table('S002V01TOTCO')->insertGetId([
- 'OTCO_NULI' => $form['linea'],
- 'OTCO_IDUR' => $idUserResponsible,
- 'OTCO_TURE' => $form['type_responsible'],
- 'OTCO_DEIN' => $form['description'],
- 'OTCO_EQIN' => $equipmentCode,
- 'OTCO_FIFA' => $form['start_date_time'],
- 'OTCO_TESO' => $form['solution_time'],
- 'OTCO_CORE' => $idCounter,
- 'OTCO_DRCO' => $lastMeasureStr,
- 'OTCO_PRIO' => $priority,
- 'OTCO_RHUT' => $rhut,
- 'OTCO_PEIN' => $staffStrFn,
- 'OTCO_TIAC' => $activationType,
- 'OTCO_DORE' => $attachedStrFn,
- 'OTCO_CLAS' => $form['clasification'],
- 'OTCO_GESE' => $idManagement,
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_ESOR' => 'PE',
- 'OTCO_USRE' => $idUser,
- 'OTCO_FERE' => $nowStr
- ]);
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$orderID",
- "Su usuario ha sido asignado como responsable de atender la orden de mantenimiento #$orderID.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($orderID)])
- ], [
- 'BOTON' => 'Asignar orden',
- 'FUNCION' => 'validateCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($orderID)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- [$idUserResponsible],
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $orderID,
- 'Correctivo'
- );
- $idOrderEnc = $this->encryptionController->encrypt($orderID);
- $socketData = ['idOrder' => $idOrderEnc];
- $this->getSocketClient()->emit('new_corrective_work_order', $socketData);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo correctivo #$orderID.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getWorkOrders($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
- }
- $orders = DB::table('S002V01TOTCO')->select([
- 'OTCO_IDOT AS ID_ORDEN',
- 'OTCO_EQIN AS CODIGO_EQUIPAMIENTO',
- 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
- 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
- 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
- 'OTCO_FIFA AS FECHA_INICIO',
- 'OTCO_CORE AS CONTADOR',
- 'OTCO_FTIN AS FECHA_FIN',
- 'OTCO_TIAC AS TIPO_ACTIVACION',
- 'OTCO_IDUR AS ID_RESPONSABLE',
- 'OTCO_TURE AS TIPO_RESPONSABLE',
- 'OTCO_PRIO AS PRIORIDAD',
- 'OTCO_ESOR AS ESTADO'
- ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN')
- ->where('OTCO_NULI', '=', $line)
- ->orderBy('OTCO_IDOT', 'desc')->get()->all();
- $subcontratistTypes = ['S' => 'Subcontratista', 'U' => 'Usuario'];
- $activationTypes = ['M' => 'Manual', 'A' => 'Automática'];
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
- foreach($orders as $key=>$order){
- if($order->TIPO_RESPONSABLE == 'U'){
- $userResponsible = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $order->ID_RESPONSABLE],
- ['USUA_NULI', '=', $line]
- ])->first();
- $userResponsibleName = $this->functionsController->joinName($userResponsible->USUA_NOMB, $userResponsible->USUA_APPA, $userResponsible->USUA_APMA);
- $order->ID_RESPONSABLE = $userResponsibleName . " (" . $order->ID_RESPONSABLE . ")";
- }else{
- $subcontratistResponsible = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $line],
- ['PESU_IDPS', '=', $order->ID_RESPONSABLE]
- ])->first();
- if(!is_null($subcontratistResponsible)){
- $order->ID_RESPONSABLE = $subcontratistResponsible->PESU_RASO . " (" . $subcontratistResponsible->PESU_REFI . ") (" . $order->ID_RESPONSABLE . ")";
- }else{
- $order->ID_RESPONSABLE = "N/D";
- }
- }
- $order->TIPO_RESPONSABLE = $subcontratistTypes[$order->TIPO_RESPONSABLE];
- $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN);
- $order->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($order->CODIGO_EQUIPAMIENTO);
- $order->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($order->ID_EQUIPAMIENTO);
- $order->CONTADOR = $this->encryptionController->encrypt($order->CONTADOR);
- $order->TIPO_ACTIVACION = $activationTypes[$order->TIPO_ACTIVACION];
- $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
- $order->ESTADO = $orderStates[$order->ESTADO];
- $orders[$key] = $order;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F01GEOP',
- 'S002V01P01COOP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento correctivo registradas.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $orders);
- }
- public function getWorkOrder($idOrder, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($idOrder);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->select([
- 'OTCO_IDOT AS ID_ORDEN',
- 'OTCO_DEIN AS DESCRIPCION',
- 'OTCO_EQIN AS CODIGO_EQUIPAMIENTO',
- 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
- 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
- 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
- 'OTCO_FIFA AS FECHA_INICIO',
- 'OTCO_TESO AS TIEMPO_ESTIMADO',
- 'OTCO_CORE AS CONTADOR',
- 'OTCO_DRCO AS MEDIDAS',
- 'OTCO_PRIO AS PRIORIDAD',
- 'OTCO_FTIN AS FECHA_FINAL',
- 'OTCO_DTIN AS DURACION_TOTAL',
- 'OTCO_RHUT AS RECURSOS',
- 'OTCO_PEIN AS PERSONAL',
- 'OTCO_TIAC AS TIPO_ACTIVACION',
- 'OTCO_IDUR AS ID_RESPONSABLE',
- 'OTCO_TURE AS TIPO_RESPONSABLE',
- 'OTCO_ANCO AS ANALISIS_COSTOS',
- 'OTCO_DORE AS DOCUMENTOS_RELACIONADOS',
- 'OTCO_CLAS AS CLASIFICACION',
- 'OTCO_COME AS COMENTARIOS',
- 'OTCO_GESE AS GERENCIA_SEGURIDAD',
- 'OTCO_HIES AS HISTORIAL_ESTATUS',
- 'OTCO_CAEX AS CAMPOS_EXTRA',
- 'OTCO_ESOR AS ESTADO',
- 'OTCO_USRE AS USUREG',
- 'OTCO_FERE AS FECREG',
- 'OTCO_USMO AS USUMOD',
- 'OTCO_FEMO AS FECMOD'
- ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTCO_EQIN')
- ->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $line]
- ])->first();
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
- }
-
- $subcontratistTypes = ['S' => 'Subcontratista', 'U' => 'Usuario'];
- if($order->TIPO_RESPONSABLE == 'U'){
- $userResponsible = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $order->ID_RESPONSABLE],
- ['USUA_NULI', '=', $line]
- ])->first();
- $userResponsibleName = $this->functionsController->joinName($userResponsible->USUA_NOMB, $userResponsible->USUA_APPA, $userResponsible->USUA_APMA);
- $order->ID_RESPONSABLE = $userResponsibleName . " (" . $order->ID_RESPONSABLE . ")";
- }else{
- $subcontratistResponsible = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $line],
- ['PESU_IDPS', '=', $order->ID_RESPONSABLE]
- ])->first();
- if(!is_null($subcontratistResponsible)){
- $order->ID_RESPONSABLE = $subcontratistResponsible->PESU_RASO . " (" . $subcontratistResponsible->PESU_REFI . ") (" . $order->ID_RESPONSABLE . ")";
- }
- }
- $order->TIPO_RESPONSABLE = $subcontratistTypes[$order->TIPO_RESPONSABLE];
- $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN);
- $order->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($order->CODIGO_EQUIPAMIENTO);
- $order->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($order->ID_EQUIPAMIENTO);
- $order->CONTADOR = $this->encryptionController->encrypt($order->CONTADOR);
- $measureArr = json_decode($order->MEDIDAS, true);
- if(!empty($measureArr)){
- $measureArr['CONTADOR'] = $this->encryptionController->encrypt($measureArr['CONTADOR']);
- $measureArr['ID_MEDIDA'] = $this->encryptionController->encrypt($measureArr['ID_MEDIDA']);
- $measureArr['ID_SERVICIO_WEB'] = $this->encryptionController->encrypt($measureArr['ID_SERVICIO_WEB']);
- }
- $order->MEDIDAS = json_encode($measureArr);
- $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
- $order->GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($order->GERENCIA_SEGURIDAD);
-
- $staffArr = json_decode($order->PERSONAL, true);
- foreach($staffArr as $key=>$val){
- $specialty = DB::table('S002V01TGEES')->where([
- ['GEES_NULI', '=', $line],
- ['GEES_COES', '=', $val['ID']]
- ])->first();
- $val['ID'] = $this->encryptionController->encrypt($val['ID']);
- $val['NAME'] = $specialty->GEES_NOES;
- $staffArr[$key] = $val;
- }
-
- $activationTypes = ['M' => 'Manual', 'A' => 'Automática'];
- $order->PERSONAL = json_encode($staffArr);
- $order->TIPO_ACTIVACION = $activationTypes[$order->TIPO_ACTIVACION];
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
- $resources = json_decode($order->RECURSOS, true);
- foreach($resources as $key=>$resource){
- if($resource['ID'] != 'SH'){
- $resourceObj = DB::table('S002V01TINST')->where([
- ['INST_NULI', '=', $line],
- ['INST_IDIS', '=', $resource['ID']],
- ])->join('S002V01TSTAR', 'STAR_IDIS', '=', 'INST_IDIS')
- ->join('S002V01TUNID', 'UNID_IDUN', '=', 'STAR_IDUN')->first();
- if(!is_null($resourceObj)){
- $resource['NAME'] = $resourceObj->INST_MODE;
- $resource['UNIT'] = $resourceObj->UNID_NOMB;
- }
- $resource['ID'] = $this->encryptionController->encrypt($resource['ID']);
- }
- $resources[$key] = $resource;
- }
- $order->RECURSOS = json_encode($resources);
- $order->ESTADO = $orderStates[$order->ESTADO];
- $documentsArr = json_decode($order->DOCUMENTOS_RELACIONADOS, true);
- $documentsFn = [];
- foreach($documentsArr as $document){
- $documentArr = explode('=', $document);
- $codeArr = explode('-', $documentArr[0]);
- $file = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $line],
- ['AFAL_COMO', '=', $codeArr[1]],
- ['AFAL_CLDO', '=', $codeArr[2]],
- ['AFAL_FECR', '=', $codeArr[3]],
- ['AFAL_NUSE', '=', $codeArr[4]],
- ['AFAL_NUVE', '=', $documentArr[1]]
- ])->first();
- $documentsFn[] = [
- 'id' => $this->encryptionController->encrypt($document),
- 'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE,
- 'size' => $file->AFAL_TAMA,
- 'type' => 'Existente'
- ];
- }
- $order->DOCUMENTOS_RELACIONADOS = json_encode($documentsFn);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $order->USUREG],
- ['USUA_NULI', '=', $line]
- ])->first();
- if(is_null($usrReg)){
- $order->USUREG = "AUTOMÁTICO (0)";
- }else{
- $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $order->USUREG = $nameReg . " (" . $order->USUREG . ")";
- }
- if(!is_null($order->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $order->USUMOD],
- ['USUA_NULI', '=', $line]
- ])->first();
-
- $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $order->USUMOD = $nameMod . " (" . $order->USUMOD . ")";
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F01GEOP',
- 'S002V01P01COOP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles de la orden #$idOrder de mantenimiento correctivo registradas.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $order);
- }
- public function updateWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'description' => 'required|string|min:15',
- 'equipment' => 'required|string',
- 'start_date_time' => 'required|date',
- 'solution_time' => 'required|numeric',
- 'priority' => 'required|string',
- 'id_counter' => 'required|string',
- 'id_last_measure' => 'required|string',
- 'clasification' => 'required|string|max:50',
- 'staff' => 'required|json',
- 'security_management' => 'required|string',
- 'activation_type' => 'required|string|in:Manual,Automática',
- 'resources' => 'required|json',
- 'attached' => 'json',
- 'id_order' => 'required|string'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }
- $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
- if(!$equipmentCode){
- return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
- }
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $form['linea']],
- ['EQUI_COEQ', '=', $equipmentCode],
- ])->first();
-
- if(is_null($equipment)){
- return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404);
- }
- if(floatval($form['solution_time']) <= 0){
- return $this->responseController->makeResponse(true, 'El tiempo de solución estimado debe ser mayor a cero.', [], 400);
- }
- $priority = $this->encryptionController->decrypt($form['priority']);
- if(!$priority){
- return $this->responseController->makeResponse(true, 'La prioridad relacionada no fue encriptada correctamente.', [], 400);
- }
- $validPriorities = ['1', '2', '3', '4'];
- if(!in_array($priority, $validPriorities)){
- return $this->responseController->makeResponse(true, 'La prioridad relacionada es inválida.', [], 400);
- }
- $idCounter = $this->encryptionController->decrypt($form['id_counter']);
- if(!$idCounter){
- return $this->responseController->makeResponse(true, 'El ID del contador relacionado no fue encriptado correctamente.', [], 400);
- }
- $counter = DB::table('S002V01TCONA')->where([
- ['CONA_IDCO', '=', $idCounter],
- ['CONA_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($counter)){
- return $this->responseController->makeResponse(true, 'El contador relacionado no existe.', [], 404);
- }
- $idLastMeasure = $this->encryptionController->decrypt($form['id_last_measure']);
- if(!$idLastMeasure){
- return $this->responseController->makeResponse(true, 'El ID de la última medida del contador relacionado no fue encriptado correctamente.', [], 400);
- }
- $lastMeasure = DB::table('S002V01TMEDI')->select([
- 'MEDI_IDME AS ID_MEDIDA',
- 'MEDI_CORE AS CONTADOR',
- 'MEDI_VALO AS VALOR',
- 'MEDI_WSRE AS ID_SERVICIO_WEB',
- 'LSWE_URLX AS URL_SERVICIO_WEB',
- 'MEDI_HORE AS HORA_REGISTRO',
- ])->join('S002V01TLSWE', 'LSWE_IDSW', '=', 'MEDI_WSRE')->where([
- ['MEDI_IDME', '=', $idLastMeasure],
- ['MEDI_NULI', '=', $form['linea']],
- ['MEDI_CORE', '=', $idCounter]
- ])->orderBy('MEDI_HORE', 'desc')->first();
-
- if(is_null($lastMeasure)){
- return $this->responseController->makeResponse(true, 'La última medida del contador relacionado no existe.', [], 404);
- }
- $staffArr = json_decode($form['staff'], true);
- if(count($staffArr) == 0){
- return $this->responseController->makeResponse(true, 'El arreglo del personal está vacío.', [], 400);
- }
- $staffArrFn = [];
- foreach($staffArr as $key=>$specialty){
- $specialtyDec = $this->encryptionController->decrypt($specialty['SPECIALTY']);
- if(!$specialtyDec){
- return $this->responseController->makeResponse(true, "El código en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
- }
- $specialtyObj = DB::table('S002V01TGEES')->where([
- ['GEES_NULI', '=', $form['linea']],
- ['GEES_COES', '=', $specialtyDec]
- ])->first();
- if(is_null($specialtyObj)){
- return $this->responseController->makeResponse(true, "El item en la posición $key del arreglo de especialidades no existe.", [], 404);
- }
- $staffArrFn[] = [
- 'ID' => $specialtyDec,
- 'CANT' => $specialty['CANT']
- ];
- }
- $staffStrFn = json_encode($staffArrFn);
- $idManagement = $this->encryptionController->decrypt($form['security_management']);
- if(!$idManagement){
- return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
- }
- $management = DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_IDGS', '=', $idManagement]
- ])->first();
- if(is_null($management)){
- return $this->responseController->makeResponse(true, 'La gerencia de seguridad seleccionada no está registrada.', [], 404);
- }
- $resources = json_decode($form['resources'], true);
- if(empty($resources)){
- return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
- }
- foreach($resources as $key=>$item){
- if(!array_key_exists('ID', $item)){
- return $this->responseController->makeResponse(true, "No se pudo encontrar el ID del elemento en la posición $key del arreglo de recursos.", [], 400);
- }
- if($item['ID'] != 'SH'){
- $idItemDec = $this->encryptionController->decrypt($item['ID']);
- $resource = DB::table('S002V01TINST')->where([
- ['INST_NULI', '=', $form['linea']],
- ['INST_IDIS', '=', $idItemDec],
- ])->first();
- if(is_null($resource)){
- return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de recursos no existe.", [], 404);
- }
- $item['ID'] = $idItemDec;
- }
- $resources[$key] = $item;
- }
- $rhut = json_encode($resources);
- $attachedArrFn = [];
- if(isset($form['attached'])){
- $attachedArr = json_decode($form['attached'], true);
- foreach($attachedArr as $key=>$attached){
- $idDec = $this->encryptionController->decrypt($attached['id']);
- if(!$idDec){
- return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
- }
- if($attached['type'] == 'Existente'){
- $codeArr = explode('=', $idDec);
- $codeArr0 = explode('-', $codeArr[0]);
- $file = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $form['linea']],
- ['AFAL_COMO', '=', $codeArr0[1]],
- ['AFAL_CLDO', '=', $codeArr0[2]],
- ['AFAL_FECR', '=', $codeArr0[3]],
- ['AFAL_NUSE', '=', $codeArr0[4]],
- ['AFAL_NUVE', '=', $codeArr[1]],
- ])->first();
- if(is_null($file)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($file->AFAL_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
- $attachedArrFn[] = $idDec;
- }else if($attached['type'] == 'Nuevo'){
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $idDec],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($tempFile->ARTE_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
- $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
- if(!$finalFile){
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- }else{
- $attachedArrFn[] = $finalFile[1];
- }
- }
- }
- }
- $activationType = $form['activation_type'][0];
- $attachedStrFn = json_encode($attachedArrFn);
- $lastMeasureStr = json_encode($lastMeasure);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_DEIN' => $form['description'],
- 'OTCO_EQIN' => $equipmentCode,
- 'OTCO_FIFA' => $form['start_date_time'],
- 'OTCO_TESO' => $form['solution_time'],
- 'OTCO_CORE' => $idCounter,
- 'OTCO_DRCO' => $lastMeasureStr ,
- 'OTCO_PRIO' => $priority,
- 'OTCO_FTIN' => $order->OTCO_FTIN,
- 'OTCO_DTIN' => $order->OTCO_DTIN,
- 'OTCO_RHUT' => $rhut,
- 'OTCO_PEIN' => $staffStrFn,
- 'OTCO_TIAC' => $activationType,
- 'OTCO_ANCO' => $order->OTCO_ANCO,
- 'OTCO_DORE' => $attachedStrFn,
- 'OTCO_CLAS' => $form['clasification'],
- 'OTCO_COME' => $order->OTCO_COME,
- 'OTCO_GESE' => $idManagement,
- 'OTCO_CAEX' => $order->OTCO_CAEX,
- 'OTCO_ESOR' => $order->OTCO_ESOR,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function deleteWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryArr = json_decode($order->OTCO_HIES, true);
- $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EL', 'FECHA' => $nowStr];
- $statusHistoryStr = json_encode($statusHistoryArr);
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_ESOR' => 'EL',
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Eliminación',
- "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function approveWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'config' => 'required|json',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }else if($order->OTCO_ESOR == 'EL'){
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }else if($order->OTCO_ESOR != 'PE'){
- $status = $orderStates[$order->OTCO_ESOR];
- return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
- }
- $staffConfigArr = json_decode($form['config'], true);
- $audience = [];
- foreach($staffConfigArr as $key=>$val){
- if(!array_key_exists('SPECIALTY', $val) || !array_key_exists('STAFF', $val)){
- return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
- }
- $specialtyDec = $this->encryptionController->decrypt($val['SPECIALTY']);
- if(!$specialtyDec){
- return $this->responseController->makeResponse(true, "El identificador de la especialidad en el item $key del arreglo de configuración de operarios no fue encriptado correctamente.", [], 400);
- }
- if(gettype($val['STAFF']) != 'array'){
- return $this->responseController->makeResponse(true, "El contenedor de oerarios en el item $key del arreglo de configuración de operarios es inválido-.", [], 400);
- }
- foreach($val['STAFF'] as $key0=>$val0){
- if(!array_key_exists('ID', $val0) || !array_key_exists('TYPE', $val0)){
- return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
- }
- $idDec = $this->encryptionController->decrypt($val0['ID']);
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_IDPE', '=', $idDec]
- ])->first();
- if(is_null($employee)){
- return $this->responseController->makeResponse(true, "El perario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios tiene un formato inválido.", [], 404);
- }
- $audience[] = $employee->PERS_IDUS;
- }
- }
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "Se ha generado la orden de mantenimiento correctivo #$idOrder y requiere su atención.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Atender orden',
- 'FUNCION' => 'attendCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryArr = json_decode($order->OTCO_HIES, true);
- $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'VA', 'FECHA' => $nowStr, 'PERSONAL' => $audience];
- $statusHistoryStr = json_encode($statusHistoryArr);
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_ESOR' => 'VA',
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") validó la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function updateApprovedWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'config' => 'required|json',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }else if($order->OTCO_ESOR == 'EL'){
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }else if($order->OTCO_ESOR != 'VA'){
- return $this->responseController->makeResponse(true, "La orden noo está validada.", [], 401);
- }
- $staffConfigArr = json_decode($form['config'], true);
- $audience = [];
- foreach($staffConfigArr as $key=>$val){
- if(!array_key_exists('SPECIALTY', $val) || !array_key_exists('STAFF', $val)){
- return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
- }
- $specialtyDec = $this->encryptionController->decrypt($val['SPECIALTY']);
- if(!$specialtyDec){
- return $this->responseController->makeResponse(true, "El identificador de la especialidad en el item $key del arreglo de configuración de operarios no fue encriptado correctamente.", [], 400);
- }
- if(gettype($val['STAFF']) != 'array'){
- return $this->responseController->makeResponse(true, "El contenedor de oerarios en el item $key del arreglo de configuración de operarios es inválido-.", [], 400);
- }
- foreach($val['STAFF'] as $key0=>$val0){
- if(!array_key_exists('ID', $val0) || !array_key_exists('TYPE', $val0)){
- return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
- }
- $idDec = $this->encryptionController->decrypt($val0['ID']);
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_IDPE', '=', $idDec]
- ])->first();
- if(is_null($employee)){
- return $this->responseController->makeResponse(true, "El perario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios tiene un formato inválido.", [], 404);
- }
- $audience[] = $employee->PERS_IDUS;
- }
- }
- $statusHistoryArr = json_decode($order->OTCO_HIES, true);
- $statusApprovedFilt = array_filter($statusHistoryArr, function($v, $k) {
- return $v['ESTADO'] == 'VA';
- }, ARRAY_FILTER_USE_BOTH);
- $keysFiltered = array_keys($statusApprovedFilt);
- $approvedKey = end($keysFiltered);
- $statusApproved = $statusApprovedFilt[$approvedKey];
- $staff = $statusApproved['PERSONAL'];
- $newAudience = [];
- foreach($audience as $item){
- if(!in_array($item, $staff)){
- $newAudience[] = $item;
- $staff[] = $item;
- }
- }
- $statusApproved['PERSONAL'] = $staff;
- $statusHistoryArr[$approvedKey] = $statusApproved;
- $statusHistoryStr = json_encode($statusHistoryArr);
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "Se ha generado la orden de mantenimiento correctivo #$idOrder y requiere su atención.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Atender orden',
- 'FUNCION' => 'attendCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- $newAudience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_ESOR' => 'VA',
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function startWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }else if($order->OTCO_ESOR == 'EL'){
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }else if($order->OTCO_ESOR != 'VA'){
- $status = $orderStates[$order->OTCO_ESOR];
- return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
- }else if($order->OTCO_IDUR != $idUser){
- return $this->responseController->makeResponse(true, "El usuario que solicitó la acción no tiene los permisos necesarios.", [], 401);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryArr = json_decode($order->OTCO_HIES, true);
- $validatedStatusFilt = array_filter($statusHistoryArr, function($v, $k) {
- return $v['ESTADO'] == 'VA';
- }, ARRAY_FILTER_USE_BOTH);
- $validatedStatus = end($validatedStatusFilt);
- $audience = [];
- foreach($validatedStatus['ATENCION'] as $item){
- if($item['RESPUESTA'] == 'A') $audience[] = $item['ID'];
- }
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "Inicio de la ejecución de la orden de mantenimiento #$idOrder.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => 'EP', 'FECHA' => $nowStr];
- $statusHistoryStr = json_encode($statusHistoryArr);
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_ESOR' => 'EP',
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") inició la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function updateWorkOrderStatus(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'status' => 'required|string|in:RE,CE,CA',
- 'comments' => 'required|string|min:15'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }else if($order->OTCO_ESOR == 'EL'){
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }
-
- $status = $form['status'];
- switch($status){
- case 'RE':
- if($order->OTCO_ESOR != 'PE'){
- $status = $orderStates[$order->OTCO_ESOR];
- return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
- }
- break;
- case 'CE':
- if($order->OTCO_ESOR != 'EP' && $order->OTCO_ESOR != 'CP'){
- $status = $orderStates[$order->OTCO_ESOR];
- return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
- }
- break;
- case 'CA':
- if($order->OTCO_ESOR != 'VA'){
- $status = $orderStates[$order->OTCO_ESOR];
- return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
- }
- break;
- }
- if($order->OTCO_ESOR == 'EP' && $status == 'CE'){
- $status = 'CP';
- }
-
- /*$message = '';
- if($status == 'CE' && is_null($order->OTCO_ANCO)){
- $status = 'CP';
- $message = 'La orden no puede cerrarse complentamente hasta asignar el análisis de costos.';
- }else{
- $message = 'Actualización correcta.';
- }*/
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $ftin = null;
- $dtin = null;
- //if(($status == 'CE' || $status == 'CP') && is_null($order->OTCO_FTIN)){
- if($status == 'CP' && is_null($order->OTCO_FTIN)){
- $ftin = $nowStr;
- $startDate = new Carbon($order->OTCO_FIFA);
- $diffInSecs = $now->diffInSeconds($startDate);
- $diffInMins = $this->functionsController->floatDiv($diffInSecs, 60);
- $dtin = $this->functionsController->floatDiv($diffInMins, 60);
- }else{
- $ftin = $order->OTCO_FTIN;
- $dtin = $order->OTCO_DTIN;
- }
- $statusHistoryArr = json_decode($order->OTCO_HIES, true);
- $validatedStatusFilt = array_filter($statusHistoryArr, function($v, $k) {
- return $v['ESTADO'] == 'VA';
- }, ARRAY_FILTER_USE_BOTH);
- $validatedStatus = end($validatedStatusFilt);
- $attendance = $validatedStatus['ATENCION'];
- $enabledUsersToClose = [];
- foreach($attendance as $item){
- if($item['RESPUESTA'] == 'A') $enabledUsersToClose[] = $item['ID'];
- }
- if(!in_array($idUser, $enabledUsersToClose)){
- return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
- }
- $closeUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $audience = [$order->OTCO_IDUR];
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "El usuario $closeUserName ($idUser) cerró la orden de mantenimiento #$idOrder con los siguientes comentarios: $form[comments].",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => $status, 'FECHA' => $nowStr];
- $statusHistoryStr = json_encode($statusHistoryArr);
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_ESOR' => $status,
- 'OTCO_COME' => $form['comments'],
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_FTIN' => $ftin,
- 'OTCO_DTIN' => $dtin,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, "EXITO");
- }
- public function closeWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }else if($order->OTCO_ESOR == 'EL'){
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }else if($idUser != $order->OTCO_IDUR){
- return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
- }
-
- $status = 'CE';
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $closeUserName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $audience = [$order->OTCO_USRE];
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "El usuario $closeUserName ($idUser) validó el cierre la orden de mantenimiento #$idOrder.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- $statusHistoryArr[] = ['USUARIO' => $idUser, 'ESTADO' => $status, 'FECHA' => $nowStr];
- $statusHistoryStr = json_encode($statusHistoryArr);
- DB::table('S002V01TOTCO')->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $form['linea']]
- ])->update([
- 'OTCO_ESOR' => $status,
- 'OTCO_HIES' => $statusHistoryStr,
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F04GEOT',
- 'S002V01P01GEOT',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden de trabajo correctivo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, "EXITO");
- }
- public function getWorkOrderClasifications($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
- }
- $clasifications = DB::table('S002V01TOTCO')->select([
- DB::raw('DISTINCT(OTCO_CLAS) AS CLASIFICACION')
- ])->get()->all();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F01GEOP',
- 'S002V01P01COOP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las clasificaciones registradas.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $clasifications);
- }
- public function getResponsibleUsers($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
- }
- $profiles = DB::table('S002V01TPERF')->where('PERF_NULI', '=', $line)->get()->all();
- $profilesWithAccess = [];
- foreach($profiles as $profile){
- $permissions = json_decode($profile->PERF_PERM, true);
- $permissionsArr = $permissions['permissions'];
- $correctiveMaintenanceFilt = array_filter($permissionsArr, function($v, $k) {
- return $v['id'] == 'S002V01M09GMCO';
- }, ARRAY_FILTER_USE_BOTH);
-
- $correctiveMaintenance = end($correctiveMaintenanceFilt);
- if(intval($correctiveMaintenance['access']) > 0){
- $submodules = $correctiveMaintenance['children'];
- $workOrdersFilt = array_filter($submodules, function($v, $k) {
- return $v['id'] == 'S002V01S01ORTR';
- }, ARRAY_FILTER_USE_BOTH);
- $workOrders = end($workOrdersFilt);
- if(intval($workOrders['access']) > 0){
- $functions = $workOrders['children'];
- $operationsManagementFilt = array_filter($functions, function($v, $k) {
- return $v['id'] == 'S002V01F01GEOP';
- }, ARRAY_FILTER_USE_BOTH);
- $operationsManagement = end($operationsManagementFilt);
- if(intval($operationsManagement['access']) > 0){
- $profilesWithAccess[] = $profile->PERF_IDPE;
- }
- }
- }
- }
- $usersWithAccess = [];
- foreach($profilesWithAccess as $idProfile){
- $users = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_PERF', '=', $idProfile],
- ['USUA_ESTA', '=', 'Activo']
- ])->get()->all();
- foreach($users as $user){
- $userName = $this->functionsController->joinName($user->USUA_NOMB, $user->USUA_APPA, $user->USUA_APMA);
- $usersWithAccess[] = [
- 'ID' => $this->encryptionController->encrypt($user->USUA_IDUS),
- 'NOMBRE' => $userName,
- ];
- }
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F01GEOP',
- 'S002V01P01COOP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los usuarios con acceso a la gestión de las operaciones.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $usersWithAccess);
- }
- public function transferWorkOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'id_new_user' => 'required|string',
- 'type' => 'required|string|in:U,S'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }else if($order->OTCO_ESOR == 'EL'){
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }else if($order->OTCO_ESOR != 'PE'){
- $status = $orderStates[$order->OTCO_ESOR];
- return $this->responseController->makeResponse(true, "La orden está $status.", [], 401);
- }
- if($order->OTCO_TURE == 'U' && $order->OTCO_IDUR != $idUser){
- return $this->responseController->makeResponse(true, "El usuario que realizó la solicitud no es el responsable de atenderla.", [], 401);
- }else if($order->OTCO_TURE == 'S'){
- $users = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_TICO', '=', 'Subcontratista'],
- ['PERS_IDPS', '=', $order->OTCO_IDUR],
- ])->get()->all();
- $enabledUsers = [];
- foreach($users as $user){
- $enabledUsers[] = $user->PERS_IDUS;
- }
- if(!in_array($idUser, $enabledUsers)){
- return $this->responseController->makeResponse(true, "El usuario que realizó la solicitud no es el responsable de atenderla.", [], 401);
- }
- }
- $audience = [];
- $idNewUser = $this->encryptionController->decrypt($form['id_new_user']);
- if(!$idNewUser){
- return $this->responseController->makeResponse(true, 'El ID del nuevo encargado no fue encriptado correctamente.', [], 400);
- }
- if($form['type'] == 'U'){
- $newUser = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idNewUser]
- ])->first();
-
- if(is_null($newUser)){
- return $this->responseController->makeResponse(true, 'El usuario seleccionado no existe.', [], 404);
- }
-
- $audience[] = $idNewUser;
- }else if($form['type'] == 'S'){
- $subcontratist = DB::table('S002V01TPESU')->where([
- ['PESU_IDPS', '=', $idNewUser],
- ['PESU_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($subcontratist)){
- return $this->responseController->makeResponse(true, 'El subcontratista seleccionado no existe.', [], 404);
- }
-
- $users = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_TICO', '=', 'Subcontratista'],
- ['PERS_IDPS', '=', $idNewUser],
- ])->get()->all();
- foreach($users as $user){
- $audience[] = $user->PERS_IDUS;
- }
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->update([
- 'OTCO_IDUR' => $idNewUser,
- 'OTCO_TURE' => $form['type'],
- 'OTCO_USMO' => $idUser,
- 'OTCO_FEMO' => $nowStr
- ]);
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "Su usuario ha sido asignado como responsable de atender la orden de mantenimiento #$idOrder.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openCorrectiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Validar orden',
- 'FUNCION' => 'validateCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F06TROT',
- '-',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") traspasó la orden de trabajo correctivo al usuario o subcontratista #$idNewUser.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function registerSecurityManagement(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'lada1' => 'required|string|max:8',
- 'phone1' => 'required|string|min:10|max:11',
- 'ext1' => 'string|max:5',
- 'lada2' =>'string|max:8',
- 'phone2' => 'string|min:10|max:11',
- 'ext2' => 'string|max:5',
- 'email' => 'required|string|max:150',
- 'id_manager' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idManager = $this->encryptionController->decrypt($form['id_manager']);
- if(!$idManager){
- return $this->responseController->makeResponse(true, 'El ID del gerente no fue encriptado correctamente.', [], 400);
- }
- $manager = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idManager]
- ])->first();
-
- if(is_null($manager)){
- return $this->responseController->makeResponse(true, 'El usuario seleccionado como gerente no existe.', [], 404);
- }
- $email = $form['email'];
- if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
- return $this->responseController->makeResponse(true, 'El formato del correo electrónico enviado es inválido.', [], 400);
- }
- $emailVerified = DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_COEL', '=', $email]
- ])->get()->all();
- if(count($emailVerified) > 0){
- return $this->responseController->makeResponse(true, 'El correo electrónico enviado ya ha sido registrado.', [], 400);
- }
- $lada1 = DB::table('S002V01TPAIS')->where([
- ['PAIS_NULI', '=', $form['linea']],
- ['PAIS_LADA', '=', $form['lada1']]
- ])->first();
-
- if(is_null($lada1)){
- return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono principal es inválida.', [], 400);
- }else if(!$this->functionsController->validPhoneNumber($form['phone1'])){
- return $this->responseController->makeResponse(true, 'El número de teléfono principal es inválido.', [], 400);
- }else if(isset($form['ext1']) && !is_numeric($form['ext1'])){
- return $this->responseController->makeResponse(true, 'La extensión de teléfono principal es inválida.', [], 400);
- }
- $ext1 = isset($form['ext1']) ? $form['ext1']: null;
- $lad2 = null;
- $tel2 = null;
- $ext2 = null;
- if(isset($form['lada2']) || isset($form['phone2'])){
- if(!isset($form['lada2']) || !isset($form['phone2'])){
- if(!isset($form['lada2'])){
- return $this->responseController->makeResponse(true, 'La lada del teléfono secundario es obligatoria cuando se envía el teléfono o la extensión secundarios', [], 400);
- }
- if(!isset($form['phone2'])){
- return $this->responseController->makeResponse(true, 'El teléfono secundario es obligatorio cuando se envía la lada o la extensión secundarias', [], 400);
- }
- }
- $lada2 = DB::table('S002V01TPAIS')->where([
- ['PAIS_NULI', '=', $form['linea']],
- ['PAIS_LADA', '=', $form['lada2']]
- ])->first();
-
- if(is_null($lada2)){
- return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono secundario es inválida.', [], 400);
- }else if(!$this->functionsController->validPhoneNumber($form['phone2'])){
- return $this->responseController->makeResponse(true, 'El número de teléfono secundario es inválido.', [], 400);
- }else if(isset($form['ext2']) && !is_numeric($form['ext2'])){
- return $this->responseController->makeResponse(true, 'La extensión de teléfono secundario es inválida.', [], 400);
- }
- $lad2 = $form['lada2'];
- $tel2 = $form['phone2'];
- $ext2 = isset($form['ext2']) ? $form['ext2'] : null;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $idManagement = DB::table('S002V01TGESE')->insertGetId([
- 'GESE_NULI' => $form['linea'],
- 'GESE_LAD1' => $form['lada1'],
- 'GESE_TEL1' => $form['phone1'],
- 'GESE_EXT1' => $ext1,
- 'GESE_LAD2' => $lad2,
- 'GESE_TEL2' => $tel2,
- 'GESE_EXT2' => $ext2,
- 'GESE_COEL' => $email,
- 'GESE_GERE' => $idManager,
- 'GESE_USRE' => $idUser,
- 'GESE_FERE' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P02GSAU',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró la gerencia de seguridad #$idManagement.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getSegurityManagements($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
- }
- $securityManagements = DB::table('S002V01TGESE')->select([
- 'GESE_IDGS AS ID_GERENCIA_SEGURIDAD',
- 'GESE_LAD1 AS LADA_TELEFONO_PRINCIPAL',
- 'GESE_TEL1 AS TELEFONO_PRINCIPAL',
- 'GESE_EXT1 AS EXTENSION_TELEFONO_PRINCIPAL',
- 'GESE_LAD2 AS LADA_TELEFONO_SECUNDARIO',
- 'GESE_TEL2 AS TELEFONO_SECUNDARIO',
- 'GESE_EXT2 AS EXTENSION_TELEFONO_SECUNDARIO',
- 'GESE_COEL AS CORREO_GERENCIA',
- 'GESE_GERE AS GERENTE',
- 'GESE_ESTA AS ESTADO',
- 'GESE_USRE AS USUREG',
- 'GESE_FERE AS FECREG',
- 'GESE_USMO AS USUMOD',
- 'GESE_FEMO AS FECMOD'
- ])->where('GESE_NULI', '=', $line)->get()->all();
- foreach($securityManagements as $key=>$item){
- $workOrders = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $line],
- ['OTCO_GESE', '=', $item->ID_GERENCIA_SEGURIDAD]
- ])->get()->all();
-
- $item->NUMERO_ORDENES = count($workOrders);
- $item->ID_GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($item->ID_GERENCIA_SEGURIDAD);
- $manager = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $item->GERENTE]
- ])->first();
- $managerName = $this->functionsController->joinName($manager->USUA_NOMB, $manager->USUA_APPA, $manager->USUA_APMA);
- $item->GERENTE = $managerName . " (" . $item->GERENTE . ")";
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $item->USUREG]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $item->USUREG = $usrRegName . " (" . $item->USUREG . ")";
- if(!is_null($item->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $item->USUMOD]
- ])->first();
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $item->USUMOD = $usrModName . " (" . $item->USUMOD . ")";
- }
- $securityManagements[$key] = $item;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P02GSAU',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las gerencias de seguridad registradas.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $securityManagements);
- }
- public function getSecurityManagement($idManagement, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
- }
- $idManagement = $this->encryptionController->decrypt($idManagement);
- if(!$idManagement){
- return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
- }
- $management = DB::table('S002V01TGESE')->select([
- 'GESE_IDGS AS ID_GERENCIA_SEGURIDAD',
- 'GESE_LAD1 AS LADA_TELEFONO_PRINCIPAL',
- 'GESE_TEL1 AS TELEFONO_PRINCIPAL',
- 'GESE_EXT1 AS EXTENSION_TELEFONO_PRINCIPAL',
- 'GESE_LAD2 AS LADA_TELEFONO_SECUNDARIO',
- 'GESE_TEL2 AS TELEFONO_SECUNDARIO',
- 'GESE_EXT2 AS EXTENSION_TELEFONO_SECUNDARIO',
- 'GESE_COEL AS CORREO_GERENCIA',
- 'GESE_GERE AS GERENTE',
- 'GESE_ESTA AS ESTADO',
- 'GESE_USRE AS USUREG',
- 'GESE_FERE AS FECREG',
- 'GESE_USMO AS USUMOD',
- 'GESE_FEMO AS FECMOD'
- ])->where([
- ['GESE_NULI', '=', $line],
- ['GESE_IDGS', '=', $idManagement]
- ])->first();
- if(is_null($management)){
- return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404);
- }
- $workOrders = DB::table('S002V01TOTCO')->select([
- 'OTCO_IDOT AS ID_ORDEN'
- ])->where([
- ['OTCO_NULI', '=', $line],
- ['OTCO_GESE', '=', $idManagement]
- ])->get()->all();
- foreach($workOrders as $key=>$order){
- $order->ID_ORDEN = $this->encryptionController->encrypt($order->ID_ORDEN);
- $workOrders[$key] = $order;
- }
- $management->ORDENES_TRABAJO = $workOrders;
- $management->ID_GERENCIA_SEGURIDAD = $this->encryptionController->encrypt($management->ID_GERENCIA_SEGURIDAD);
- $manager = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $management->GERENTE]
- ])->first();
- $managerName = $this->functionsController->joinName($manager->USUA_NOMB, $manager->USUA_APPA, $manager->USUA_APMA);
- $management->GERENTE = $managerName . " (" . $management->GERENTE . ")";
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $management->USUREG]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $management->USUREG = $usrRegName . " (" . $management->USUREG . ")";
- if(!is_null($management->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $management->USUMOD]
- ])->first();
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $management->USUMOD = $usrModName . " (" . $management->USUMOD . ")";
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P02GSAU',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la gerencias de seguridad #$idManagement.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $management);
- }
- public function updateSecurityManagement(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'lada1' => 'required|string|max:8',
- 'phone1' => 'required|string|min:10|max:11',
- 'ext1' => 'string|max:5',
- 'lada2' =>'string|max:8',
- 'phone2' => 'string|min:10|max:11',
- 'ext2' => 'string|max:5',
- 'email' => 'required|string|max:150',
- 'id_manager' => 'required|string',
- 'id_management' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idManagement = $this->encryptionController->decrypt($form['id_management']);
- if(!$idManagement){
- return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
- }
- $management = DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_IDGS', '=', $idManagement]
- ])->first();
- if(is_null($management)){
- return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404);
- }
- $idManager = $this->encryptionController->decrypt($form['id_manager']);
- if(!$idManager){
- return $this->responseController->makeResponse(true, 'El ID del gerente no fue encriptado correctamente.', [], 400);
- }
- $manager = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idManager]
- ])->first();
-
- if(is_null($manager)){
- return $this->responseController->makeResponse(true, 'El usuario seleccionado como gerente no existe.', [], 404);
- }
- $email = $form['email'];
- if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
- return $this->responseController->makeResponse(true, 'El formato del correo electrónico enviado es inválido.', [], 400);
- }
- $emailVerified = DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_COEL', '=', $email],
- ['GESE_IDGS', '!=', $idManagement]
- ])->get()->all();
- if(count($emailVerified) > 0){
- return $this->responseController->makeResponse(true, 'El correo electrónico enviado ya ha sido registrado.', [], 400);
- }
- $lada1 = DB::table('S002V01TPAIS')->where([
- ['PAIS_NULI', '=', $form['linea']],
- ['PAIS_LADA', '=', $form['lada1']]
- ])->first();
-
- if(is_null($lada1)){
- return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono principal es inválida.', [], 400);
- }else if(!$this->functionsController->validPhoneNumber($form['phone1'])){
- return $this->responseController->makeResponse(true, 'El número de teléfono principal es inválido.', [], 400);
- }else if(isset($form['ext1']) && !is_numeric($form['ext1'])){
- return $this->responseController->makeResponse(true, 'La extensión de teléfono principal es inválida.', [], 400);
- }
- $ext1 = isset($form['ext1']) ? $form['ext1']: null;
- $lad2 = null;
- $tel2 = null;
- $ext2 = null;
- if(isset($form['lada2']) || isset($form['phone2'])){
- if(!isset($form['lada2']) || !isset($form['phone2'])){
- if(!isset($form['lada2'])){
- return $this->responseController->makeResponse(true, 'La lada del teléfono secundario es obligatoria cuando se envía el teléfono o la extensión secundarios', [], 400);
- }
- if(!isset($form['phone2'])){
- return $this->responseController->makeResponse(true, 'El teléfono secundario es obligatorio cuando se envía la lada o la extensión secundarias', [], 400);
- }
- }
- $lada2 = DB::table('S002V01TPAIS')->where([
- ['PAIS_NULI', '=', $form['linea']],
- ['PAIS_LADA', '=', $form['lada2']]
- ])->first();
-
- if(is_null($lada2)){
- return $this->responseController->makeResponse(true, 'La lada seleccionada para el teléfono secundario es inválida.', [], 400);
- }else if(!$this->functionsController->validPhoneNumber($form['phone2'])){
- return $this->responseController->makeResponse(true, 'El número de teléfono secundario es inválido.', [], 400);
- }else if(isset($form['ext2']) && !is_numeric($form['ext2'])){
- return $this->responseController->makeResponse(true, 'La extensión de teléfono secundario es inválida.', [], 400);
- }
- $lad2 = $form['lada2'];
- $tel2 = $form['phone2'];
- $ext2 = isset($form['ext2']) ? $form['ext2'] : null;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_IDGS', '=', $idManagement]
- ])->update([
- 'GESE_LAD1' => $form['lada1'],
- 'GESE_TEL1' => $form['phone1'],
- 'GESE_EXT1' => $ext1,
- 'GESE_LAD2' => $lad2,
- 'GESE_TEL2' => $tel2,
- 'GESE_EXT2' => $ext2,
- 'GESE_COEL' => $email,
- 'GESE_GERE' => $idManager,
- 'GESE_USMO' => $idUser,
- 'GESE_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P02GSAU',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la gerencia de seguridad #$idManagement.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function deleteSecurityManagement(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_management' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idManagement = $this->encryptionController->decrypt($form['id_management']);
- if(!$idManagement){
- return $this->responseController->makeResponse(true, 'El ID de la gerencia de seguridad no está encriptado correctamente', [], 400);
- }
- $management = DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_IDGS', '=', $idManagement]
- ])->first();
- if(is_null($management)){
- return $this->responseController->makeResponse(true, 'La gerencia de seguridad consultada no está registrada.', [], 404);
- }
- $workOrders = DB::table('S002V01TOTCO')->select([
- 'OTCO_IDOT AS ID_ORDEN'
- ])->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_GESE', '=', $idManagement],
- ['OTCO_ESOR', '!=', 'EL'],
- ])->get()->all();
- if(count($workOrders) > 0){
- return $this->responseController->makeResponse(true, 'La gerencia no se puede eliminar porque tiene órdenes de trabajo relacionadas.', [], 401);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TGESE')->where([
- ['GESE_NULI', '=', $form['linea']],
- ['GESE_IDGS', '=', $idManagement]
- ])->update([
- 'GESE_ESTA' => 'Eliminado',
- 'GESE_USMO' => $idUser,
- 'GESE_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P02GSAU',
- 'Eliminación',
- "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la gerencia de seguridad #$idManagement.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function registerBlock(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'blocked' => 'required|string',
- 'type' => 'required|string|in:USR,SUB'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idBlocked = $this->encryptionController->decrypt($form['blocked']);
- if(!$idBlocked){
- return $this->responseController->makeResponse(true, 'El ID que desea bloquear no fue encriptado correctamente.', [], 400);
- }
- $blockedTypes = ['USR' => 'Empleado', 'SUB' => 'Subcontratista'];
- $blockedType = $blockedTypes[$form['type']];
- if($blockedType == 'Empleado'){
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_IDPE', '=', $idBlocked],
- ['PERS_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($employee)){
- return $this->responseController->makeResponse(true, 'El empleado que desea bloquear no está registrado.', [], 404);
- }
- }else{
- $subcontratist = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $form['linea']],
- ['PESU_IDPS', '=', $idBlocked]
- ])->first();
-
- if(is_null($subcontratist)){
- return $this->responseController->makeResponse(true, 'El subcontratista que desea bloquear no está registrado.', [], 404);
- }
- }
- $checkStatus = DB::table('S002V01TBIBL')->where([
- ['BIBL_NULI', '=', $form['linea']],
- ['BIBL_BLOQ', '=', $idBlocked],
- ['BIBL_TIBL', '=', $blockedType],
- ['BIBL_ESTA', '=', 'Activo']
- ])->get()->all();
- if(count($checkStatus)){
- return $this->responseController->makeResponse(true, "El $blockedType que desea bloquear ya se encuentra bloqueado.", [], 401);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TBIBL')->insert([
- 'BIBL_NULI' => $form['linea'],
- 'BIBL_BLOQ' => $idBlocked,
- 'BIBL_TIBL' => $blockedType,
- 'BIBL_USRE' => $idUser,
- 'BIBL_FERE' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P04REBL',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") bloqueó al $blockedType #$idBlocked.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getBlockRegisters($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
- }
- $blockRegisters = DB::table('S002V01TBIBL')->select([
- 'BIBL_IDBL AS ID_BLOQUEO',
- 'BIBL_BLOQ AS BLOQUEADO',
- 'BIBL_TIBL AS TIPO_BLOQUEADO',
- 'BIBL_ESTA AS ESTADO',
- 'BIBL_USRE AS USUREG',
- 'BIBL_FERE AS FECREG',
- 'BIBL_USMO AS USUMOD',
- 'BIBL_FEMO AS FECMOD'
- ])->where('BIBL_NULI', '=', $line)->get()->all();
- foreach($blockRegisters as $key=>$register){
- $register->ID_BLOQUEO = $this->encryptionController->encrypt($register->ID_BLOQUEO);
- if($register->TIPO_BLOQUEADO == 'Subcontratista'){
- $subcontratist = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $line],
- ['PESU_IDPS', '=', $register->BLOQUEADO]
- ])->first();
- $register->BLOQUEADO = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $register->BLOQUEADO . ")";
- }else{
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPE', '=', $register->BLOQUEADO]
- ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->first();
- if(!is_null($employee)){
- $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
- $register->BLOQUEADO = $employeeName . " (" . $register->BLOQUEADO . ")";
- }
- }
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $register->USUREG]
- ])->first();
- if(!is_null($usrReg)){
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $register->USUREG = $usrRegName . " (" . $register->USUREG . ")";
- }
- if(!is_null($register->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $register->USUMOD]
- ])->first();
- if(!is_null($usrMod)){
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $register->USUMOD = $usrModName . " (" . $register->USUMOD . ")";
- }
- }
- $blockRegisters[$key] = $register;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P03BLOQ',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los bloqueos registrados.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $blockRegisters);
- }
- public function unblockRegister(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_register' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idBlocked = $this->encryptionController->decrypt($form['id_register']);
- if(!$idBlocked){
- return $this->responseController->makeResponse(true, 'El ID del bloqueo no fue encriptado correctamente.', [], 400);
- }
- $register = DB::table('S002V01TBIBL')->where([
- ['BIBL_NULI', '=', $form['linea']],
- ['BIBL_IDBL', '=', $idBlocked]
- ])->first();
-
- if(is_null($register)){
- return $this->responseController->makeResponse(true, 'El bloqueo que desea revocar no está registrado.', [], 404);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TBIBL')->where([
- ['BIBL_NULI', '=', $form['linea']],
- ['BIBL_IDBL', '=', $idBlocked]
- ])->update([
- 'BIBL_ESTA' => 'Anulado',
- 'BIBL_USMO' => $idUser,
- 'BIBL_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F03GESE',
- 'S002V01P04REBL',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") anuló el bloqueo #$idBlocked.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getWorkOrderStatusHistory($idOrder, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($idOrder);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->select([
- 'OTCO_HIES AS HISTORIAL',
- ])->where([
- ['OTCO_IDOT', '=', $idOrder],
- ['OTCO_NULI', '=', $line]
- ])->first();
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
- }
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
- $statusHistoryArr = json_decode($order->HISTORIAL, true);
- foreach($statusHistoryArr as $key=>$item){
- $item['ESTADO'] = $orderStates[$item['ESTADO']];
- $usrSta = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $item['USUARIO']]
- ])->first();
- $usrStaName = $this->functionsController->joinName($usrSta->USUA_NOMB, $usrSta->USUA_APPA, $usrSta->USUA_APMA);
- $item['USUARIO'] = $usrStaName . " (" . $item['USUARIO'] . ")";
- $statusHistoryArr[$key] = $item;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F01GEOT',
- '-',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de estados de la orden #$idOrder de mantenimiento correctivo.",
- $idUser,
- $nowStr,
- 'S002V01S03PRIN'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $statusHistoryArr);
- }
- public function generateReport(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'report_type' => 'required|string|in:TODAS,MANUA,AUTOM,ESTAD',
- 'start_date' => 'date',
- 'end_date' => 'date',
- 'order_state' => 'required_if:report_type,=,ESTAD|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $systemParamsExists = file_exists($this->functionsController->getBasePath() .'\storage\app\files\system-params.json');
- if(!$systemParamsExists){
- return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500);
- }
- $paramsStr = file_get_contents($this->functionsController->getBasePath() .'\storage\app\files\system-params.json');
- $paramsArr = json_decode($paramsStr, true);
- $ordersBuilder = DB::table('S002V01TOTCO')->select([
- 'OTCO_IDOT AS ID_ORDEN',
- 'OTCO_IDUR AS USUARIO_RESPONSABLE',
- 'OTCO_TURE AS TIPO_USUARIO_RESPONSABLE',
- 'OTCO_DEIN AS DESCRIPCION',
- 'OTCO_EQIN AS EQUIPAMIENTO',
- 'OTCO_FIFA AS FECHA_REGISTRO_FALLA',
- 'OTCO_TESO AS TIEMPO_ESTIMADO',
- 'OTCO_CORE AS CONTADOR',
- 'OTCO_DRCO AS MEDIDA_REGISTRADA',
- 'OTCO_PRIO AS PRIORIDAD',
- 'OTCO_FTIN AS FECHA_FINALIZACION',
- 'OTCO_DTIN AS DURACION_TOTAL',
- 'OTCO_RHUT AS RECURSOS',
- 'OTCO_PEIN AS PERSONAL',
- 'OTCO_TIAC AS TIPO_ACTIVACION',
- 'OTCO_ANCO AS ANALISIS_COSTOS',
- 'OTCO_DORE AS DOCUMENTOS',
- 'OTCO_CLAS AS CLASIFICACION',
- 'OTCO_COME AS COMENTARIOS',
- 'OTCO_GESE AS GERENCIA_SGURIDAD',
- 'OTCO_HIES AS HISTORIAL_ESTADOS',
- 'OTCO_ESOR AS ESTADO',
- 'OTCO_USRE AS USUREG',
- 'OTCO_FERE AS FECREG',
- 'OTCO_USMO AS USUMOD',
- 'OTCO_FEMO AS FECMOD'
- ])->where('OTCO_NULI', '=', $form['linea']);
- if(isset($form['start_date'])){
- $ordersBuilder->where('OTCO_FERE', '>=', $form['start_date']);
- }
- if(isset($form['end_date'])){
- $ordersBuilder->where('OTCO_FERE', '<=', $form['end_date']);
- }
-
- $orderStates = [
- 'PE' => 'Pendiente', 'VA' => 'Validado', 'RE' => 'Rechazado',
- 'EP' => 'En progreso', 'CE' => 'Cerrado', 'CP' => 'Cerrado pendiente',
- 'CA' => 'Cancelado', 'EL' => 'Eliminado'
- ];
- if(isset($form['order_state']) && !array_key_exists($form['order_state'], $orderStates)){
- return $this->responseController->makeResponse(true, 'El estado solicitado para las órdenes de mantenimiento correctivo es inválido.', [], 400);
- }else if(isset($form['order_state']) && array_key_exists($form['order_state'], $orderStates)){
- $ordersBuilder->where('OTCO_ESOR', '=', $form['order_state']);
- }
- if($form['report_type'] == 'MANUA'){
- $ordersBuilder->where('OTCO_TIAC', '=', 'M');
- }
- if($form['report_type'] == 'AUTOM'){
- $ordersBuilder->where('OTCO_TIAC', '=', 'A');
- }
- $workOrders = $ordersBuilder->get()->all();
- foreach($workOrders as $order){
- $order->ID_ORDEN = "#" . $order->ID_ORDEN;
- if($order->TIPO_USUARIO_RESPONSABLE == 'S'){
- $subcontratist = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $form['linea']],
- ['PESU_IDPS', '=', $order->USUARIO_RESPONSABLE]
- ])->first();
- $order->USUARIO_RESPONSABLE = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $subcontratist->PESU_IDPS . ")";
- $order->TIPO_USUARIO_RESPONSABLE = 'Subcontratista';
- }else if($order->TIPO_USUARIO_RESPONSABLE == 'U'){
- $usrResp = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $order->USUARIO_RESPONSABLE]
- ])->first();
-
- $nameUsrResp = $this->functionsController->joinName($usrResp->USUA_NOMB, $usrResp->USUA_APPA, $usrResp->USUA_APMA);
- $order->USUARIO_RESPONSABLE = $nameUsrResp . " (" . $order->USUARIO_RESPONSABLE . ")";
- $order->TIPO_USUARIO_RESPONSABLE = 'Empleado';
- }
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $form['linea']],
- ['EQUI_COEQ', '=', $order->EQUIPAMIENTO]
- ])->first();
- $order->EQUIPAMIENTO = $order->EQUIPAMIENTO . ' - ' . $equipment->EQUI_TIPO . ' - ' . $equipment->EQUI_MODE . ' (' . $equipment->EQUI_IDEQ . ')';
- $order->FECHA_REGISTRO_FALLA = $this->functionsController->formatDateTime($order->FECHA_REGISTRO_FALLA);
- $order->TIEMPO_ESTIMADO = $order->TIEMPO_ESTIMADO . "h";
- $counterActivator = DB::table('S002V01TACTI')->where([
- ['ACTI_NULI', '=', $form['linea']],
- ['ACTI_CORE', '=', $order->CONTADOR]
- ])->first();
- $measureArr = json_decode($order->MEDIDA_REGISTRADA, true);
- $activationConfig = json_decode($counterActivator->ACTI_COAC, true);
- if($counterActivator->ACTI_TIAC == 'Medida' || $counterActivator->ACTI_TIAC == 'Valor'){
- $unit = DB::table('S002V01TLIME')->where([
- ['LIME_IDME', '=', $activationConfig['unit']],
- ['LIME_MAGN', '=', $activationConfig['magnitude']],
- ])->first();
- $order->MEDIDA_REGISTRADA = "Medida #" . $measureArr['ID_MEDIDA'] . ". Valor registrado: " . $measureArr['VALOR'] .
- ' ' . $unit->LIME_ACME . ". Fecha de registro: " . $this->functionsController->formatDateTime($measureArr['HORA_REGISTRO']) .
- ". Servicio web de recepción: " . $measureArr['URL_SERVICIO_WEB'] . " (" . $measureArr['ID_SERVICIO_WEB'] . ")";
- }else if($counterActivator->ACTI_TIAC == 'Sintoma'){
- $symptom = DB::table('S002V01TLISI')->where([
- ['LISI_IDSI', '=', $activationConfig['sign']],
- ['LISI_NULI', '=', $form['linea']]
- ])->first();
- $unit = DB::table('S002V01TLIME')->where([
- ['LIME_IDME', '=', $symptom->LISI_IDME],
- ['LIME_MAGN', '=', $activationConfig['magnitude']],
- ])->first();
- $order->MEDIDA_REGISTRADA = "Medida #" . $measureArr['ID_MEDIDA'] . ". Valor registrado: " . $measureArr['VALOR'] .
- ' ' . $unit->LIME_ACME . ". Fecha de registro: " . $this->functionsController->formatDateTime($measureArr['HORA_REGISTRO']) .
- ". Servicio web de recepción: " . $measureArr['URL_SERVICIO_WEB'] . " (" . $measureArr['ID_SERVICIO_WEB'] . ")";
- }else{
- $order->MEDIDA_REGISTRADA = 'No aplica';
- }
- $order->CONTADOR = "#" . $order->CONTADOR;
- $orderPriorities = $paramsArr['order_priorities'];
- $priorityFilt = array_filter($orderPriorities, function($v, $k) use($order) {
- return $v['value'] == $order->PRIORIDAD;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($priorityFilt) < 1){
- $order->PRIORIDAD = 'Desconocido';
- }else{
- $priority = end($priorityFilt);
- $order->PRIORIDAD = $priority['label'] . " (" . $order->PRIORIDAD . ")";
- }
- if(is_null($order->FECHA_FINALIZACION)) {
- $order->FECHA_FINALIZACION = '-';
- }else{
- $order->FECHA_FINALIZACION = $this->functionsController->formatDateTime($order->FECHA_FINALIZACION);
- }
- if(is_null($order->DURACION_TOTAL)) {
- $order->DURACION_TOTAL = '-';
- }else{
- $order->DURACION_TOTAL = $order->DURACION_TOTAL . "h";
- }
- $resourcesArr = json_decode($order->RECURSOS, true);
- if(count($resourcesArr) < 1){
- $order->RECURSOS = 'Ninguno';
- }else{
- //Pendiente procesar los recursos
- }
- $staffArr = json_decode($order->PERSONAL, true);
- $staffStr = "";
- foreach($staffArr as $item){
- if($item['TYPE'] == 'EQ'){
- $workTeam = DB::table('S002V01TEQMA')->where([
- ['EQMA_IDEQ', '=', $item['ID']],
- ['EQMA_NULI', '=', $form['linea']]
- ])->first();
- $staffStr .= "equipo de trabajo " . $workTeam->EQMA_NOMB . " (" . $item['ID'] . "), ";
- }else if($item['TYPE'] == 'SU'){
- $subcontratist = DB::table('S002V01TPESU')->where([
- ['PESU_IDPS', '=', $item['ID']],
- ['PESU_NULI', '=', $form['linea']]
- ])->first();
- $staffStr .= "subcontratista " . $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $item['ID'] . "), ";
- }else if($item['TYPE'] == 'EM'){
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_IDPE', '=', $item['ID']],
- ['PERS_NULI', '=', $form['linea']]
- ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->first();
- $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
- $staffStr .= "empleado " . $employeeName . " (" . $item['ID'] . "), ";
- }
- }
- $staffStr = substr($staffStr, 0, -2);
- $staffStr = ucfirst($staffStr);
-
- $order->PERSONAL = $staffStr;
- $order->TIPO_ACTIVACION = $order->TIPO_ACTIVACION == 'M' ? 'Manual' : 'Automática';
- if(is_null($order->ANALISIS_COSTOS)){
- $order->ANALISIS_COSTOS = 'Sin asignar';
- }else{
- //Pendiente revisar el análisis de costos
- }
- $documentsArr = json_decode($order->DOCUMENTOS, true);
- $documentsStr = "";
- if(count($documentsArr) < 1){
- $documentsStr = 'Ninguno';
- }else{
- foreach($documentsArr as $document){
- $documentsStr .= $document . ", ";
- }
- $documentsStr = substr($documentsStr, 0, -2);
- }
- $order->DOCUMENTOS = $documentsStr;
- if(is_null($order->COMENTARIOS)){
- $order->COMENTARIOS = 'Sin comentarios';
- }
- $order->GERENCIA_SGURIDAD = "Gerencia #" . $order->GERENCIA_SGURIDAD;
- $statusHistoryArr = json_decode($order->HISTORIAL_ESTADOS, true);
- $statusHistoryStr = "";
- foreach($statusHistoryArr as $item){
- $statusHistoryStr .= $orderStates[$item['ESTADO']] . ' - ' . $this->functionsController->formatDateTime($item['FECHA']);
- $usrState = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $item['USUARIO']],
- ['USUA_NULI', '=', $form['linea']]
- ])->first();
- $usrStateName = $this->functionsController->joinName($usrState->USUA_NOMB, $usrState->USUA_APPA, $usrState->USUA_APMA);
- $statusHistoryStr .= ' - ' . $usrStateName . ' (' . $item['USUARIO'] . '), ';
- }
- $statusHistoryStr = substr($statusHistoryStr, 0, -2);
- $order->HISTORIAL_ESTADOS = $statusHistoryStr;
- $order->ESTADO = $orderStates[$order->ESTADO];
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $order->USUREG],
- ['USUA_NULI', '=', $form['linea']]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $order->USUREG = $usrRegName . " (" . $order->USUREG . ")";
- $order->FECREG = $this->functionsController->formatDateTime($order->FECREG);
- if(!is_null($order->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $order->USUMOD],
- ['USUA_NULI', '=', $form['linea']]
- ])->first();
-
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $order->USUMOD = $usrModName . " (" . $order->USUMOD . ")";
- $order->FECMOD = $this->functionsController->formatDateTime($order->FECMOD);
- }else{
- $order->USUMOD = "-";
- $order->FECMOD = "-";
- }
- }
- $document = $this->reportWorkOrders($workOrders);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
-
- $dateTimeArr = explode(" ", $nowStr);
- $dateArr = explode("-", $dateTimeArr[0]);
- $year = substr($dateArr[0], 2);
- $como = 'GMCO';
- $cldo = 'IN';
- $fecr = $year . $dateArr[1] . $dateArr[2];
- $sec = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $form['linea']],
- ['AFAL_COMO', '=', $como],
- ['AFAL_CLDO', '=', $cldo],
- ])->orderBy('AFAL_NUSE', 'desc')->first();
- $nuse = "";
- if(is_null($sec)){
- $nuse = '000001';
- }else{
- $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
- $nuse = "";
- for($i = strlen($secu); $i < 6; $i++){
- $nuse .= "0";
- }
- $nuse = $nuse . $secu;
- }
- $timestamp = $now->timestamp;
- $noar = "informe_ordenes_mantenimiento_correctivo_$timestamp";
- $exte = "xlsx";
- $ver = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $form['linea']],
- ['AFAL_COMO', '=', $como],
- ['AFAL_CLDO', '=', $cldo],
- ['AFAL_NOAR', '=', $noar],
- ['AFAL_EXTE', '=', $exte],
- ])->orderBy('AFAL_NUVE', 'desc')->first();
- $nuve = "";
- if(is_null($ver)){
- $nuve = "01";
- }else{
- $vers = intval($ver->AFAL_NUVE) + 1;
- $nuve = $vers < 10 ? "0$vers" : "$vers";
- }
- $line = $form['linea'] < 10 ? "0$form[linea]" : "$form[linea]";
- $filePath = $this->functionsController->getBasePath() .'\public_files\\';
- $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
-
- $tempFile = $filePath . $fileName;
- if(file_exists($tempFile)){
- unlink($tempFile);
- }
- $writer = IOFactory::createWriter($document, 'Xlsx');
- $writer->save($tempFile);
- $ubic = Storage::putFile('files', new File($tempFile));
- $ubic = str_replace("/", "\\", $ubic);
- $ubic = $this->functionsController->getBasePath() ."\storage\app\\" . $ubic;
- $tama = filesize($ubic);
- $usac = json_encode([$idUser]);
- unlink($tempFile);
- DB::table('S002V01TAFAL')->insert([
- 'AFAL_NULI' => $line,
- 'AFAL_COMO' => $como,
- 'AFAL_CLDO' => $cldo,
- 'AFAL_FECR' => $fecr,
- 'AFAL_NUSE' => $nuse,
- 'AFAL_NUVE' => $nuve,
- 'AFAL_NOAR' => $noar,
- 'AFAL_EXTE' => $exte,
- 'AFAL_TAMA' => $tama,
- 'AFAL_UBIC' => $ubic,
- 'AFAL_USAC' => $usac,
- 'AFAL_USRE' => $idUser,
- 'AFAL_FERE' => $nowStr,
- ]);
- $idReport = DB::table('S002V01TIMCO')->insertGetId([
- 'IMCO_NULI' => $form['linea'],
- 'IMCO_TIIN' => $form['report_type'],
- 'IMCO_DORE' => $fileName,
- 'IMCO_USRE' => $idUser,
- 'IMCO_FERE' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02PRIN',
- 'S002V01P01REIN',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró el informe #$idReport.",
- $idUser,
- $nowStr,
- 'S002V01S03PRIN'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.', ['report' => $this->encryptionController->encrypt($fileName)]);
- }
- private function reportWorkOrders($workOrders) : Spreadsheet {
- $spreadsheet = new Spreadsheet;
- $spreadsheet->getProperties()
- ->setCreator('STC')
- ->setTitle('Historial de órdenes de trabajo de mantenimiento correctivo.')
- ->setSubject('Historial documento')
- ->setKeywords('Historial Órdenes Mantenimiento Correctivo')
- ->setCategory('Historial archivo');
- $worksheet = $spreadsheet->getActiveSheet();
- $worksheet->setTitle('ÓRDENES DE MANT CORRECTIVO');
- $columns = ['# ORDEN', 'RESPONSABLE', 'TIPO DE USUARIO RESPONSABLE', 'DESCRIPCIÓN', 'EQUIPAMIENTO', 'FECHA Y HORA DE REGISTRO DE LA FALLA',
- 'TIEMPO ESTIMADO DE DURACIÓN DE LA INTERVENCIÓN', 'CONTADOR RELACIONADO', 'MEDIDA REGISTRADA AL MOMENTO DE LA FALLA', 'PRIORIDAD',
- 'FECHA DE FINALIZACIÓN DE LA INTERVENCIÓN', 'DURACIÓN TOTAL DE LA INTERVENCIÓN', 'CONSUMIBLES UTILIZADOS', 'PERSONAL INVOLUCRADO',
- 'TIPO DE ACTIVACIÓN', 'ANÁLISIS DE COSTOS', 'DOCUMENTOS REQUERIDOS', 'CLASIFICACIÓN', 'COMENTARIOS REALIZADOS DURANTE LA INTERVENCIÓN',
- 'GERENCIA DE SEGURIDAD RELACIONADA', 'HISTORIAL DE ESTADOS', 'ESTADO DE LA ORDEN', 'USUARIO DE REGISTRO', 'FECHA DE REGISTRO', 'USUARIO DE ACTIALIZACIÓN',
- 'FECHA DE ACTUALIZACIÓN'];
-
- $startRow = 2;
- $startCol = 2;
- $maxRow = $startRow + count($workOrders) + 1;
- $maxCol = $startCol + count($columns) - 1;
- for($row = $startRow; $row <= $maxRow; $row++){
- $startColStr = Coordinate::stringFromColumnIndex($startCol);
- $maxColStr = Coordinate::stringFromColumnIndex($maxCol);
- if($row == 2){
- $worksheet->mergeCells($startColStr . $row . ':' . $maxColStr . $row);
- $worksheet->setCellValue($startColStr . $row, 'INFORME DE ÓRDENES DE MANTENIMIENTO CORRECTIVO')->getStyle($startColStr . $row)->getFill()
- ->setFillType(Fill::FILL_SOLID)
- ->getStartColor()->setRGB('B7BCC4');
- $worksheet->getStyle($startColStr . $row)->getFont()->setBold(true);
- $worksheet->getStyle($startColStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- }else if($row == 3){
- for($col = $startCol; $col <= $maxCol; $col++){
- $colStr = Coordinate::stringFromColumnIndex($col);
- $colInd = $col - 2;
- $column = $columns[$colInd];
- $worksheet->setCellValue($colStr . $row, $column);
- $worksheet->getStyle($colStr . $row)->getFont()->setBold(true);
- $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- }
- }else if($row > 3){
- $rowInd = $row - 4;
- $order = (array) $workOrders[$rowInd];
- $keys = array_keys($order);
- for($col = $startCol; $col <= $maxCol; $col++){
- $colInd = $col - 2;
- $key = $keys[$colInd];
- $value = $order[$key];
- $colStr = Coordinate::stringFromColumnIndex($col);
- if($key == 'ID_ORDEN' || $key == 'TIEMPO_ESTIMADO' || $key == 'CONTADOR' ||
- $key == 'DURACION_TOTAL' || $key == 'GERENCIA_SGURIDAD'){
- $worksheet->getStyle($colStr . $row)->getAlignment()->setHorizontal(Alignment::HORIZONTAL_CENTER);
- $worksheet->getColumnDimension($colStr)->setAutoSize(true);
- }else if($key == 'EQUIPAMIENTO' || $key == 'DESCRIPCION' || $key == 'MEDIDA_REGISTRADA' ||
- $key == 'PERSONAL' || $key == 'DOCUMENTOS' || $key == 'COMENTARIOS' || $key == 'HISTORIAL_ESTADOS'){
- $worksheet->getColumnDimension($colStr)->setWidth(48);
- $worksheet->getStyle($colStr . $row)->getAlignment()->setWrapText(true);
- }else{
- $worksheet->getColumnDimension($colStr)->setAutoSize(true);
- }
- $worksheet->getStyle($colStr . $row)->getAlignment()->setVertical(Alignment::HORIZONTAL_CENTER);
- $worksheet->setCellValue($colStr . $row, $value);
- }
- }
- }
- return $spreadsheet;
- }
- public function getReports($type, $startDate, $endDate, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $reportsBuilder = DB::table('S002V01TIMCO')->select([
- 'IMCO_IDIN AS ID_INFORME',
- 'IMCO_TIIN AS TIPO_INFORME',
- 'IMCO_DORE AS DOCUMENTO',
- 'IMCO_USRE AS USUREG',
- 'IMCO_FERE AS FECREG'
- ])->where('IMCO_NULI', '=', $line);
- if($type != '-'){
- $validReports = ['TODAS','MANUA','AUTOM','ESTAD'];
- if(!in_array($type, $validReports)){
- return $this->responseController->makeResponse(true, "El tipo de reportes solicitado es inválido.", [], 400);
- }
- $reportsBuilder->where('IMCO_TIIN', '=', $type);
- }
- if($startDate != '-'){
- $startDateArr = explode('-', $startDate);
- if(count($startDateArr) != 3){
- return $this->responseController->makeResponse(true, 'La fecha de inicio tiene un formato inválido.', [], 400);
- }
-
- try{
- $startDateObj = new Carbon($startDate);
- }catch(InvalidFormatException $e){
- return $this->responseController->makeResponse(true, "La fecha de inicio tiene un formato inválido: " . $e->getMessage(), [], 400);
- }
-
- $startDate = $startDateObj->toDateTimeString();
- $reportsBuilder->where('IMCO_FERE', '>=', $startDate);
- }
- if($endDate != '-'){
- $endDateArr = explode('-', $endDate);
- if(count($endDateArr) != 3){
- return $this->responseController->makeResponse(true, 'La fecha final tiene un formato inválido.', [], 400);
- }
-
- try{
- $endDateObj = new Carbon($endDate);
-
- $endDateObj->addDay();
- $endDateObj->subSecond();
- }catch(InvalidFormatException $e){
- return $this->responseController->makeResponse(true, "La fecha final tiene un formato inválido: " . $e->getMessage(), [], 400);
- }
-
- $endDate = $endDateObj->toDateTimeString();
- $reportsBuilder->where('IMCO_FERE', '<=', $endDate);
- }
- $reports = $reportsBuilder->get()->all();
- foreach($reports as $key=>$report){
- $report->ID_INFORME = $this->encryptionController->encrypt($report->ID_INFORME);
- $report->DOCUMENTO = $this->encryptionController->encrypt($report->DOCUMENTO);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $report->USUREG],
- ['USUA_NULI', '=', $line]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $report->USUREG = $usrRegName . " (" . $report->USUREG . ")";
- $reports[$key] = $report;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F02PRIN',
- '-',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los informes de tipo $type.",
- $idUser,
- $nowStr,
- 'S002V01S03PRIN'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $reports);
- }
- public function registerMaintnencePlan(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'equipment' => 'required|string',
- 'equipment_status' => 'required|string|in:DE,DP,EF',
- 'lru' => 'string',
- 'lru_status' => 'string|in:DE,DP,EF',
- 'description' => 'required|string|min:15',
- 'inm_time' => 'required|numeric',
- 'priority' => 'required|string',
- 'total_duration' => 'required|numeric',
- 'classification' => 'required|string|max:100',
- 'specialties' => 'required|json',
- 'specialties_conf' => 'required|json',
- 'resources' => 'required|json',
- 'attached' => 'required|json',
- 'symptom' => 'required|string',
- 'scada' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
- if(!$equipmentCode){
- return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400);
- }
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_COEQ', '=', $equipmentCode],
- ['EQUI_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($equipment)){
- return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404);
- }
- $lrui = null;
- $eflr = null;
- if(isset($form['lru'])){
- $lruCode = $this->encryptionController->decrypt($form['lru']);
- if(!$lruCode){
- return $this->responseController->makeResponse(true, 'El código del LRU no fue encriptado correctamente.', [], 400);
- }
- $lru = DB::table('S002V01TEQUI')->where([
- ['EQUI_COEQ', '=', $lruCode],
- ['EQUI_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($lru)){
- return $this->responseController->makeResponse(true, 'El LRU relacionado no existe.', [], 404);
- }
- if(!isset($form['lru_status'])){
- return $this->responseController->makeResponse(true, 'El estado del lru es obligatorio cuando se envía el campo lru.', [], 400);
- }
- $lrui = $lruCode;
- $eflr = $form['lru_status'];
- }
- $priorityDec = $this->encryptionController->decrypt($form['priority']);
- $systemParamsExists = file_exists($this->functionsController->getBasePath() .'\storage\app\files\system-params.json');
- if(!$systemParamsExists){
- return $this->responseController->makeResponse(true, 'El archivo de parámetros del sistema no fue encontrado.', [], 500);
- }
- $paramsStr = file_get_contents($this->functionsController->getBasePath() . '\storage\app\files\system-params.json');
- $paramsArr = json_decode($paramsStr, true);
- $orderPriorities = $paramsArr['order_priorities'];
- $priorityFilt = array_filter($orderPriorities, function($v, $k) use($priorityDec) {
- return $v['value'] == $priorityDec;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($priorityFilt) < 1){
- return $this->responseController->makeResponse(true, 'La prioridad seleccionada es inválida.', [], 400);
- }
- //PENDINTE REVISAR RECURSOS CON STOCK
- $attachedArr = json_decode($form['attached'], true);
- $attachedArrFn = [];
- foreach($attachedArr as $key=>$attached){
- $idDec = $this->encryptionController->decrypt($attached['id']);
- if(!$idDec){
- return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
- }
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $idDec],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($tempFile->ARTE_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
- $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
- if(!$finalFile[0]){
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- }else{
- $attachedArrFn[] = [
- 'ID' => $finalFile[1],
- 'TYPE' => $attached['type']
- ];
- }
- }
- $idSymptom = $this->encryptionController->decrypt($form['symptom']);
- if(!$idSymptom){
- return $this->responseController->makeResponse(true, 'El ID del síntoma no fue encriptado correctamente.', [], 400);
- }
- $symptom = DB::table('S002V01TLISI')->where([
- ['LISI_NULI', '=', $form['linea']],
- ['LISI_IDSI', '=', $idSymptom],
- ])->first();
-
- if(is_null($symptom)){
- return $this->responseController->makeResponse(true, 'El síntoma relacionado no existe.', [], 404);
- }
- $idSCADA = $this->encryptionController->decrypt($form['scada']);
- if(!$idSCADA){
- return $this->responseController->makeResponse(true, 'El ID del SCADA no fue encriptado correctamente.', [], 400);
- }
- $scada = DB::table('S002V01TLISC')->where([
- ['LISC_NULI', '=', $form['linea']],
- ['LISC_IDSC', '=', $idSCADA]
- ])->first();
-
- if(is_null($scada)){
- return $this->responseController->makeResponse(true, 'El SCADA relacionado no existe.', [], 404);
- }
- //Una vez que se aprueban los datos se registra el contador relacionado
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $idCounter = DB::table('S002V01TCONA')->insertGetId([
- 'CONA_NULI' => $form['linea'],
- 'CONA_INLE' => 5,
- 'CONA_UTIL' => 'min',
- 'CONA_TOIN' => 1,
- 'CONA_UTTI' => 'min',
- 'CONA_IDSC' => $idSCADA,
- 'CONA_COEQ' => is_null($lrui) ? $equipmentCode : $lrui,
- 'CONA_COVI' => '[]',
- 'CONA_USRE' => $idUser,
- 'CONA_FERE' => $nowStr
- ]);
- $repeatStartDate = new Carbon($now->toDateString());
- $repeatStart = str_replace(' ', 'T', $repeatStartDate->toDateTimeString());
- $repeatHourDate = new Carbon($nowStr);
- $hour = $repeatHourDate->hour;
- $hourStr = "";
- $minute = $repeatHourDate->minute;
- $minuteStr = "";
- if($minute > 0 && $minute <= 15){
- $minuteStr = "15";
- $hourStr = $hour < 10 ? "0$hour" : "$hour";
- }else if($minute > 15 && $minute <= 30){
- $minuteStr = "30";
- $hourStr = $hour < 10 ? "0$hour" : "$hour";
- }else if($minute > 30 && $minute <= 45){
- $minuteStr = "45";
- $hourStr = $hour < 10 ? "0$hour" : "$hour";
- }else{
- $minuteStr = "00";
- $hourAux = $hour + 1;
- $hourStr = $hourAux < 10 ? "0$hourAux" : "$hourAux";
- }
- $repeatHourStr = "$hourStr:$minuteStr:00";
- $symptomRepeat = [
- 'sign' => $idSymptom,
- 'color' => 'rgb(79, 195, 255)',
- 'repeat' => 'TD',
- 'startDate' => "$repeatStart.000Z",
- 'startHour' => $repeatHourStr,
- 'customRepeat' => '',
- ];
- //Se procede a crear un activador relacionado al contador nuevo
- $symptomRepeatStr = json_encode($symptomRepeat);
- $idActivator = DB::table('S002V01TACTI')->insertGetId([
- 'ACTI_NULI' => $form['linea'],
- 'ACTI_PRIO' => $priorityDec,
- 'ACTI_TIAC' => 'Sintoma',
- 'ACTI_COAC' => $symptomRepeatStr,
- 'ACTI_CORE' => $idCounter,
- 'ACTI_USRE' => $idUser,
- 'ACTI_FERE' => $nowStr,
- ]);
-
- $specialtiesArr = json_decode($form['specialties'], true);
- $specialtiesDec = [];
- foreach($specialtiesArr as $specialty){
- $specialtiesDec[] = $this->encryptionController->decrypt($specialty);
- }
- $specialtiesStr = json_encode($specialtiesDec);
- //Una vez obtenido el ID del nuevo contador relacionado se ingresa el plan de mantenimiento
- $come = isset($form['comments']) ? $form['comments'] : null;
- $dead = isset($form['extra_details']) ? $form['extra_details'] : null;
- $dore = json_encode($attachedArrFn);
-
- $idPlan = DB::table('S002V01TPMCO')->insertGetId([
- 'PMCO_NULI' => $form['linea'],
- 'PMCO_EQIN' => $equipmentCode,
- 'PMCO_LRUI' => $lrui,
- 'PMCO_EFEQ' => $form['equipment_status'],
- 'PMCO_EFLR' => $eflr,
- 'PMCO_DESC' => $form['description'],
- 'PMCO_TIES' => $form['inm_time'],
- 'PMCO_DTIN' => $form['total_duration'],
- 'PMCO_CLAS' => $form['classification'],
- 'PMCO_ESRE' => $specialtiesStr,
- 'PMCO_COES' => $form['specialties_conf'],
- 'PMCO_COME' => $come,
- 'PMCO_RECU' => $form['resources'],
- 'PMCO_DEAD' => $dead,
- 'PMCO_DORE' => $dore,
- 'PMCO_CORE' => $idCounter,
- 'PMCO_USRE' => $idUser,
- 'PMCO_FERE' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02PLAN',
- 'S002V01P01ASPL',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró el plan de mantenimiento correctivo #$idPlan.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.', [
- 'PLAN' => $this->encryptionController->encrypt($idPlan),
- 'ACTIVADOR' => $this->encryptionController->encrypt($idActivator),
- 'CONTADOR' => $this->encryptionController->encrypt($idCounter),
- ]);
- }
- public function getMaintenancePlans($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $plansList = DB::table('S002V01TPMCO')->select([
- 'PMCO_IDPM AS ID_PLAN',
- 'PMCO_EQIN AS EQUIPAMIENTO',
- 'PMCO_LRUI AS LRU',
- 'PMCO_TIES AS TIEMPO_INMOVILIZACION_ESTIMADO',
- 'PMCO_DTIN AS DURACION_TOTAL',
- 'PMCO_CLAS AS CLASIFICACION',
- 'PMCO_CORE AS CONTADOR',
- 'ACTI_IDAC AS ACTIVADOR',
- 'ACTI_PRIO AS PRIORIDAD',
- 'PMCO_ESTA AS ESTADO',
- 'PMCO_USRE AS USRREG',
- 'PMCO_FERE AS FECREG',
- 'PMCO_USMO AS USRMOD',
- 'PMCO_FEMO AS FECMOD',
- ])->join('S002V01TACTI', 'ACTI_CORE', '=', 'PMCO_CORE')->get()->all();
- foreach($plansList as $key=>$plan){
- $plan->ID_PLAN = $this->encryptionController->encrypt($plan->ID_PLAN);
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $line],
- ['EQUI_COEQ', '=', $plan->EQUIPAMIENTO]
- ])->first();
- $equipmentLabel = $plan->EQUIPAMIENTO . " - " . $equipment->EQUI_TIPO . " - " . $equipment->EQUI_MODE . " (" . $equipment->EQUI_IDEQ . ")";
- $plan->EQUIPAMIENTO = $this->encryptionController->encrypt($equipmentLabel);
- if(!is_null($plan->LRU)){
- $lru = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $line],
- ['EQUI_COEQ', '=', $plan->LRU]
- ])->first();
- $lruLabel = $plan->LRU . " - " . $lru->EQUI_TIPO . " - " . $lru->EQUI_MODE . " (" . $lru->EQUI_IDEQ . ")";
- $plan->LRU = $this->encryptionController->encrypt($lruLabel);
- }
-
- $plan->CONTADOR = $this->encryptionController->encrypt($plan->CONTADOR);
- $plan->ACTIVADOR = $this->encryptionController->encrypt($plan->ACTIVADOR);
- $plan->PRIORIDAD = $this->encryptionController->encrypt($plan->PRIORIDAD);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $plan->USRREG],
- ['USUA_NULI', '=', '1'],
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $plan->USRREG = $usrRegName . " (" . $plan->USRREG . ")";
- if(!is_null($plan->USRMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $plan->USRMOD],
- ['USUA_NULI', '=', '1'],
- ])->first();
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $plan->USRMOD = $usrModName . " (" . $plan->USRMOD . ")";
- }
- $plansList[$key] = $plan;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F02PLAN',
- 'S002V01P01ASPL',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los planes de mantenimiento registrados.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $plansList);
- }
- public function getMaintenancePlan($idPlan, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idPlan = $this->encryptionController->decrypt($idPlan);
- if(!$idPlan){
- return $this->responseController->makeResponse(true, 'El ID del plan de mantenimiento no está encriptado correctamente.', [], 400);
- }
- $plan = DB::table('S002V01TPMCO')->select([
- 'PMCO_IDPM AS ID_PLAN',
- 'PMCO_EQIN AS EQUIPAMIENTO',
- 'PMCO_LRUI AS LRU',
- 'PMCO_EFEQ AS ESTADO_FUNCIONAMIENTO_EQUIPAMIENTO',
- 'PMCO_EFLR AS ESTADO_FUNCIONAMIENTO_LRU',
- 'PMCO_DESC AS DESCRIPCION',
- 'PMCO_TIES AS TIEMPO_INMOVILIZACION_ESTIMADO',
- 'PMCO_DTIN AS DURACION_TOTAL',
- 'PMCO_CLAS AS CLASIFICACION',
- 'PMCO_ESRE AS ESPECIALIDADES_REQUERIDAS',
- 'PMCO_COES AS CONFIGURACION_OPERARIOS',
- 'PMCO_COME AS COMENTARIOS',
- 'PMCO_RECU AS RECURSOS',
- 'PMCO_DEAD AS DETALLES_ADICIONALES',
- 'PMCO_DORE AS DOCUMENTOS_RELACIONADOS',
- 'PMCO_CORE AS CONTADOR',
- 'CONA_IDSC AS SCADA',
- 'ACTI_IDAC AS ACTIVADOR',
- 'ACTI_PRIO AS PRIORIDAD',
- 'ACTI_COAC AS SINTOMA',
- 'PMCO_ESTA AS ESTADO',
- 'PMCO_USRE AS USRREG',
- 'PMCO_FERE AS FECREG',
- 'PMCO_USMO AS USRMOD',
- 'PMCO_FEMO AS FECMOD',
- ])->where([
- ['PMCO_NULI', '=', $line],
- ['PMCO_IDPM', '=', $idPlan]
- ])->join('S002V01TACTI', 'ACTI_CORE', '=', 'PMCO_CORE')
- ->join('S002V01TCONA', 'CONA_IDCO', '=', 'PMCO_CORE')->first();
- if(is_null($plan)){
- return $this->responseController->makeResponse(true, 'El plan solicitado no existe.', [], 404);
- }
- $plan->ID_PLAN = $this->encryptionController->encrypt($plan->ID_PLAN);
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $line],
- ['EQUI_COEQ', '=', $plan->EQUIPAMIENTO]
- ])->first();
- $equipmentLabel = $plan->EQUIPAMIENTO . " - " . $equipment->EQUI_TIPO . " - " . $equipment->EQUI_MODE . " (" . $equipment->EQUI_IDEQ . ")";
- $plan->EQUIPAMIENTO = $this->encryptionController->encrypt($equipmentLabel);
- if(!is_null($plan->LRU)){
- $lru = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $line],
- ['EQUI_COEQ', '=', $plan->LRU]
- ])->first();
- $lruLabel = $plan->LRU . " - " . $lru->EQUI_TIPO . " - " . $lru->EQUI_MODE . " (" . $lru->EQUI_IDEQ . ")";
- $plan->LRU = $this->encryptionController->encrypt($lruLabel);
- }
- $documentsArr = json_decode($plan->DOCUMENTOS_RELACIONADOS, true);
- $documentsFn = [];
- foreach($documentsArr as $document){
- $documentCodeArr0 = explode('=', $document['ID']);
- $documentCodeArr1 = explode('-', $documentCodeArr0[0]);
- $documentObj = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $line],
- ['AFAL_COMO', '=', $documentCodeArr1[1]],
- ['AFAL_CLDO', '=', $documentCodeArr1[2]],
- ['AFAL_FECR', '=', $documentCodeArr1[3]],
- ['AFAL_NUSE', '=', $documentCodeArr1[4]],
- ['AFAL_NUVE', '=', $documentCodeArr0[1]],
- ])->first();
- $documentsFn[] = [
- 'id' => $this->encryptionController->encrypt($document['ID']),
- 'name' => $document['ID'],
- 'size' => $documentObj->AFAL_TAMA,
- 'type' => $document['TYPE']
- ];
- }
- $plan->DOCUMENTOS_RELACIONADOS = json_encode($documentsFn);
- $plan->CONTADOR = $this->encryptionController->encrypt($plan->CONTADOR);
- $plan->SCADA = $this->encryptionController->encrypt($plan->SCADA);
- $plan->ACTIVADOR = $this->encryptionController->encrypt($plan->ACTIVADOR);
- $plan->PRIORIDAD = $this->encryptionController->encrypt($plan->PRIORIDAD);
- $activationConfig = json_decode($plan->SINTOMA, true);
- $plan->SINTOMA = $this->encryptionController->encrypt($activationConfig['sign']);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $plan->USRREG]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $plan->USRREG = $usrRegName . " (" . $plan->USRREG . ")";
- if(!is_null($plan->USRMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $plan->USRMOD]
- ])->first();
-
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $plan->USRMOD = $usrModName . " (" . $plan->USRMOD . ")";
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F02PLAN',
- 'S002V01P01ASPL',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó el plan de mantenimiento #$idPlan.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $plan);
- }
- public function updateMaintenancePlan(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_plan' => 'required|string',
- 'equipment' => 'required|string',
- 'equipment_status' => 'required|string|in:DE,DP,EF',
- 'lru' => 'string',
- 'lru_status' => 'string|in:DE,DP,EF',
- 'description' => 'required|string|min:15',
- 'inm_time' => 'required|numeric',
- 'total_duration' => 'required|numeric',
- 'classification' => 'required|string|max:100',
- 'specialties' => 'required|json',
- 'specialties_conf' => 'required|json',
- 'resources' => 'required|json',
- 'attached' => 'required|json',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idPlan = $this->encryptionController->decrypt($form['id_plan']);
- if(!$idPlan){
- return $this->responseController->makeResponse(true, 'El ID del plan de mantenimiento no fue encriptado correctamente.', [], 400);
- }
- $plan = DB::table('S002V01TPMCO')->where([
- ['PMCO_NULI', '=', $form['linea']],
- ['PMCO_IDPM', '=', $idPlan]
- ])->first();
-
- if(is_null($plan)){
- return $this->responseController->makeResponse(true, 'El plan que desea modificar no existe.', [], 404);
- }else if($plan->PMCO_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, 'El plan que desea modificar está eliminado.', [], 404);
- }
- $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
- if(!$equipmentCode){
- return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400);
- }
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_COEQ', '=', $equipmentCode],
- ['EQUI_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($equipment)){
- return $this->responseController->makeResponse(true, 'El equipamiento relacionado no existe.', [], 404);
- }
- $lrui = null;
- $eflr = null;
- if(isset($form['lru'])){
- $lruCode = $this->encryptionController->decrypt($form['lru']);
- if(!$lruCode){
- return $this->responseController->makeResponse(true, 'El código del LRU no fue encriptado correctamente.', [], 400);
- }
- $lru = DB::table('S002V01TEQUI')->where([
- ['EQUI_COEQ', '=', $lruCode],
- ['EQUI_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($lru)){
- return $this->responseController->makeResponse(true, 'El LRU relacionado no existe.', [], 404);
- }
- if(!isset($form['lru_status'])){
- return $this->responseController->makeResponse(true, 'El estado del lru es obligatorio cuando se envía el campo lru.', [], 400);
- }
- $lrui = $lruCode;
- $eflr = $form['lru_status'];
- }
- $planCounter = DB::table('S002V01TCONA')->where([
- ['CONA_NULI', '=', $form['linea']],
- ['CONA_IDCO', '=', $plan->PMCO_CORE]
- ])->first();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $counterEquipment = $planCounter->CONA_COEQ;
-
- if(is_null($lrui) && $counterEquipment != $equipmentCode){
- DB::table('S002V01TCONA')->where([
- ['CONA_NULI', '=', $form['linea']],
- ['CONA_IDCO', '=', $plan->PMCO_CORE]
- ])->update([
- 'CONA_COEQ' => $equipmentCode,
- 'CONA_USMO' => $idUser,
- 'CONA_FEMO' => $nowStr
- ]);
- }else if($lrui != $counterEquipment){
- DB::table('S002V01TCONA')->where([
- ['CONA_NULI', '=', $form['linea']],
- ['CONA_IDCO', '=', $plan->PMCO_CORE]
- ])->update([
- 'CONA_COEQ' => $lrui,
- 'CONA_USMO' => $idUser,
- 'CONA_FEMO' => $nowStr
- ]);
- }
-
- $specialtiesArr = json_decode($form['specialties'], true);
- if(count($specialtiesArr) == 0){
- return $this->responseController->makeResponse(true, 'El arreglo de especialidades está vacío.', [], 400);
- }
- $specialtiesDec = [];
- foreach($specialtiesArr as $specialty){
- $specialtiesDec[] = $this->encryptionController->decrypt($specialty);
- }
- $specialtiesStr = json_encode($specialtiesDec);
- $attachedArr = json_decode($form['attached'], true);
- if(count($attachedArr) == 0){
- return $this->responseController->makeResponse(true, 'El arreglo de documentos está vacío.', [], 400);
- }
- $attachedArrFn = [];
- foreach($attachedArr as $key=>$attached){
- $idDec = $this->encryptionController->decrypt($attached['id']);
- if(!$idDec){
- return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
- }
- if($attached['isFinalFile']){
- $documentCodeArr0 = explode('=', $idDec);
- $documentCodeArr1 = explode('-', $documentCodeArr0[0]);
- $file = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $form['linea']],
- ['AFAL_COMO', '=', $documentCodeArr1[1]],
- ['AFAL_CLDO', '=', $documentCodeArr1[2]],
- ['AFAL_FECR', '=', $documentCodeArr1[3]],
- ['AFAL_NUSE', '=', $documentCodeArr1[4]],
- ['AFAL_NUVE', '=', $documentCodeArr0[1]],
- ])->first();
-
- if(is_null($file)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($file->AFAL_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
-
- $attachedArrFn[] = [
- 'ID' => $idDec,
- 'TYPE' => $attached['type']
- ];
- }else{
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $idDec],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
-
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($tempFile->ARTE_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
-
- $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
- if(!$finalFile[0]){
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- }else{
- $attachedArrFn[] = [
- 'ID' => $finalFile[1],
- 'TYPE' => $attached['type']
- ];
- }
- }
- }
-
- $come = isset($form['comments']) ? $form['comments'] : null;
- $dead = isset($form['extra_details']) ? $form['extra_details'] : null;
- $dore = json_encode($attachedArrFn);
- DB::table('S002V01TPMCO')->where([
- ['PMCO_NULI', '=', $form['linea']],
- ['PMCO_IDPM', '=', $idPlan]
- ])->update([
- 'PMCO_EQIN' => $equipmentCode,
- 'PMCO_LRUI' => $lrui,
- 'PMCO_EFEQ' => $form['equipment_status'],
- 'PMCO_EFLR' => $eflr,
- 'PMCO_DESC' => $form['description'],
- 'PMCO_TIES' => $form['inm_time'],
- 'PMCO_DTIN' => $form['total_duration'],
- 'PMCO_CLAS' => $form['classification'],
- 'PMCO_ESRE' => $specialtiesStr,
- 'PMCO_COES' => $form['specialties_conf'],
- 'PMCO_COME' => $come,
- 'PMCO_RECU' => $form['resources'],
- 'PMCO_DEAD' => $dead,
- 'PMCO_DORE' => $dore,
- 'PMCO_USMO' => $idUser,
- 'PMCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02PLAN',
- 'S002V01P01ASPL',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el plan de mantenimiento correctivo #$idPlan.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function deleteMaintenancePlan(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_plan' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idPlan = $this->encryptionController->decrypt($form['id_plan']);
- if(!$idPlan){
- return $this->responseController->makeResponse(true, 'El ID del plan de mantenimiento no fue encriptado correctamente.', [], 400);
- }
- $plan = DB::table('S002V01TPMCO')->where([
- ['PMCO_NULI', '=', $form['linea']],
- ['PMCO_IDPM', '=', $idPlan]
- ])->first();
-
- if(is_null($plan)){
- return $this->responseController->makeResponse(true, 'El plan que desea modificar no existe.', [], 404);
- }else if($plan->PMCO_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, 'El plan que desea modificar está eliminado.', [], 404);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TPMCO')->where([
- ['PMCO_NULI', '=', $form['linea']],
- ['PMCO_IDPM', '=', $idPlan]
- ])->update([
- 'PMCO_ESTA' => 'Eliminado',
- 'PMCO_USMO' => $idUser,
- 'PMCO_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02PLAN',
- 'S002V01P01ASPL',
- 'Eliminación',
- "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el plan de mantenimiento correctivo #$idPlan.",
- $idUser,
- $nowStr,
- 'S002V01S02GEME'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function registerWorkGroup(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'work_group_name' => 'required|string|max:100|min:8',
- 'related_teams' => 'required|json',
- 'specialty' => 'required|string|max:100|min:8',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $relatedTeamsArr = json_decode($form['related_teams'], true);
- if(count($relatedTeamsArr) < 2){
- return $this->responseController->makeResponse(true, 'El arreglo de equipos relacionados debe contener al menos 2 elementos.', [], 400);
- }
- $relatedTeamsArrDec = [];
- foreach($relatedTeamsArr as $key=>$team){
- $itemDec = $this->encryptionController->decrypt($team);
- if(!$itemDec){
- return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no fue encriptado correctamente.", [], 400);
- }
- $workTeam = DB::table('S002V01TEQMA')->where([
- ['EQMA_NULI', '=', $form['linea']],
- ['EQMA_IDEQ', '=', $itemDec]
- ])->first();
- if(is_null($workTeam)){
- return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no existe.", [], 404);
- }else if($workTeam->EQMA_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados está eliminado.", [], 404);
- }
- $relatedTeamsArrDec[] = $itemDec;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $relatedTeamsStr = json_encode($relatedTeamsArrDec);
- $idWorkGroup = DB::table('S002V01TGMCO')->insertGetId([
- 'GMCO_NULI' => $form['linea'],
- 'GMCO_NGMC' => $form['work_group_name'],
- 'GMCO_EQRE' => $relatedTeamsStr,
- 'GMCO_ESPE' => $form['specialty'],
- 'GMCO_USRE' => $idUser,
- 'GMCO_FERE' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02AEMA',
- 'S002V01P01AEOP',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró el grupo de trabajo $form[work_group_name] ($idWorkGroup).",
- $idUser,
- $nowStr,
- 'S002V01S04FUFL'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getWorkGroups($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $workGroups = DB::table('S002V01TGMCO')->select([
- 'GMCO_IDGM AS ID_GRUPO',
- 'GMCO_NGMC AS NOMBRE_GRUPO',
- 'GMCO_ESPE AS ESPECIALIDAD',
- 'GMCO_ESTA AS ESTADO',
- 'GMCO_USRE AS USUREG',
- 'GMCO_FERE AS FECREG',
- 'GMCO_USMO AS USUMOD',
- 'GMCO_FEMO AS FECMOD'
- ])->where('GMCO_NULI', '=', $line)->get()->all();
- foreach($workGroups as $key=>$group){
- $group->ID_GRUPO = $this->encryptionController->encrypt($group->ID_GRUPO);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $group->USUREG],
- ['USUA_NULI', '=', $line]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $group->USUREG = $usrRegName . " (" . $group->USUREG . ')';
- if(!is_null($group->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $group->USUMOD],
- ['USUA_NULI', '=', $line]
- ])->first();
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $group->USUMOD = $usrModName . " (" . $group->USUMOD . ')';
- }
- $workGroups[$key] = $group;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F02AEMA',
- 'S002V01P01AEOP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los grupos de trabajo registrados.",
- $idUser,
- $nowStr,
- 'S002V01S04FUFL'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $workGroups);
- }
- public function getWorkGroup($idGroup, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idGroup = $this->encryptionController->decrypt($idGroup);
- if(!$idGroup){
- return $this->responseController->makeResponse(true, 'El ID del grupo de trabajo no está encriptado correctamente', [], 400);
- }
- $workGroup = DB::table('S002V01TGMCO')->select([
- 'GMCO_IDGM AS ID_GRUPO',
- 'GMCO_NGMC AS NOMBRE_GRUPO',
- 'GMCO_EQRE AS EQUIPOS_RELACIONADOS',
- 'GMCO_ESPE AS ESPECIALIDAD',
- 'GMCO_ESTA AS ESTADO',
- 'GMCO_USRE AS USUREG',
- 'GMCO_FERE AS FECREG',
- 'GMCO_USMO AS USUMOD',
- 'GMCO_FEMO AS FECMOD'
- ])->where([
- ['GMCO_IDGM', '=', $idGroup],
- ['GMCO_NULI', '=', $line]
- ])->first();
- if(is_null($workGroup)){
- return $this->responseController->makeResponse(true, 'El grupo de trabajo consultado no está registrado.', [], 404);
- }
- $workGroup->ID_GRUPO = $this->encryptionController->encrypt($workGroup->ID_GRUPO);
- $relatedTeamsArr = json_decode($workGroup->EQUIPOS_RELACIONADOS, true);
-
- $relatedTeams = [];
- foreach($relatedTeamsArr as $team){
- $teamInfo = DB::table('S002V01TEQMA')->where([
- ['EQMA_NULI', '=', $line],
- ['EQMA_IDEQ', '=', $team]
- ])->first();
- if(!is_null($teamInfo)){
- $relatedTeams[] = [
- 'ID_EQUIPO' => $this->encryptionController->encrypt($teamInfo->EQMA_IDEQ),
- 'NOMBRE_EQUIPO' => $teamInfo->EQMA_NOMB,
- 'ESPECIALIDAD' => $teamInfo->EQMA_ESPE
- ];
- }
- }
- $workGroup->EQUIPOS_RELACIONADOS = json_encode($relatedTeams);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $workGroup->USUREG],
- ['USUA_NULI', '=', $line]
- ])->first();
- $usrRegName = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $workGroup->USUREG = $usrRegName . " (" . $workGroup->USUREG . ')';
- if(!is_null($workGroup->USUMOD)){
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $workGroup->USUMOD],
- ['USUA_NULI', '=', $line]
- ])->first();
- $usrModName = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $workGroup->USUMOD = $usrModName . " (" . $workGroup->USUMOD . ')';
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M09GMCO',
- 'S002V01F02AEMA',
- 'S002V01P01AEOP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó el grupo de trabajo " . $workGroup->NOMBRE_GRUPO . " ($idGroup).",
- $idUser,
- $nowStr,
- 'S002V01S04FUFL'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $workGroup);
- }
- public function updateWorkGroup(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_work_group' => 'required|string',
- 'work_group_name' => 'required|string|max:100|min:8',
- 'related_teams' => 'required|json',
- 'specialty' => 'required|string|max:100|min:8',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idWorkGroup = $this->encryptionController->decrypt($form['id_work_group']);
- if(!$idWorkGroup){
- return $this->responseController->makeResponse(true, 'El ID del grupo de trabajo no fue encriptado correctamente.', [], 400);
- }
- $workGroup = DB::table('S002V01TGMCO')->where([
- ['GMCO_NULI', '=', $form['linea']],
- ['GMCO_IDGM', '=', $idWorkGroup]
- ])->first();
-
- if(is_null($workGroup)){
- return $this->responseController->makeResponse(true, 'El grupo de trabajo solicitado no existe.', [], 404);
- }
- $relatedTeamsArr = json_decode($form['related_teams'], true);
- if(count($relatedTeamsArr) < 2){
- return $this->responseController->makeResponse(true, 'El arreglo de equipos relacionados debe contener al menos 2 elementos.', [], 400);
- }
- $relatedTeamsArrDec = [];
- foreach($relatedTeamsArr as $key=>$team){
- $itemDec = $this->encryptionController->decrypt($team);
- if(!$itemDec){
- return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no fue encriptado correctamente.", [], 400);
- }
- $workTeam = DB::table('S002V01TEQMA')->where([
- ['EQMA_NULI', '=', $form['linea']],
- ['EQMA_IDEQ', '=', $itemDec]
- ])->first();
- if(is_null($workTeam)){
- return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados no existe.", [], 404);
- }else if($workTeam->EQMA_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El elemento en la posicion #$key del arreglo de equipos relacionados está eliminado.", [], 404);
- }
- $relatedTeamsArrDec[] = $itemDec;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $relatedTeamsStr = json_encode($relatedTeamsArrDec);
- DB::table('S002V01TGMCO')->where([
- ['GMCO_NULI', '=', $form['linea']],
- ['GMCO_IDGM', '=', $idWorkGroup]
- ])->update([
- 'GMCO_NGMC' => $form['work_group_name'],
- 'GMCO_EQRE' => $relatedTeamsStr,
- 'GMCO_ESPE' => $form['specialty'],
- 'GMCO_USMO' => $idUser,
- 'GMCO_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02AEMA',
- 'S002V01P01AEOP',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el grupo de trabajo $form[work_group_name] ($idWorkGroup).",
- $idUser,
- $nowStr,
- 'S002V01S04FUFL'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function deleteWorkGroup(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_work_group' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idWorkGroup = $this->encryptionController->decrypt($form['id_work_group']);
- if(!$idWorkGroup){
- return $this->responseController->makeResponse(true, 'El ID del grupo de trabajo no fue encriptado correctamente.', [], 400);
- }
- $workGroup = DB::table('S002V01TGMCO')->where([
- ['GMCO_NULI', '=', $form['linea']],
- ['GMCO_IDGM', '=', $idWorkGroup]
- ])->first();
-
- if(is_null($workGroup)){
- return $this->responseController->makeResponse(true, 'El grupo de trabajo solicitado no existe.', [], 404);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TGMCO')->where([
- ['GMCO_NULI', '=', $form['linea']],
- ['GMCO_IDGM', '=', $idWorkGroup]
- ])->update([
- 'GMCO_ESTA' => 'Eliminado',
- 'GMCO_USMO' => $idUser,
- 'GMCO_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
-
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M09GMCO',
- 'S002V01F02AEMA',
- 'S002V01P01AEOP',
- 'Eliminación',
- "El usuario $name (" . $usr->USUA_IDUS . ") eliminó el grupo de trabajo #$idWorkGroup.",
- $idUser,
- $nowStr,
- 'S002V01S04FUFL'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getNoMeasuresFormFields($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $noMeasuresFormFields = DB::table('S002V01TCAPE')->select([
- 'CAPE_VERS AS VERSION',
- 'CAPE_FEAC AS FECHA_ACTUALIZACION',
- 'CAPE_CAMP AS CAMPOS'
- ])->where([
- ['CAPE_NULI', '=', $line],
- ['CAPE_TIFO', '=', 'RSM']
- ])->orderBy('CAPE_VERS', 'desc')->first();
- if(is_null($noMeasuresFormFields)){
- return $this->responseController->makeResponse(false, 'EXITO', []);
- }
- $fieldsArr = json_decode($noMeasuresFormFields->CAMPOS, true);
- foreach($fieldsArr as $key=>$field){
- if(array_key_exists('fieldID', $field)){
- $field['fieldID'] = $this->encryptionController->encrypt($field['fieldID']);
- }
- $fieldsArr[$key] = $field;
- }
- $noMeasuresFormFields->CAMPOS = $fieldsArr;
- return $this->responseController->makeResponse(false, 'EXITO', $noMeasuresFormFields);
- }
- public function saveNoMeasuresFormFields(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'form_fields' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
-
- $formFields = $this->encryptionController->decrypt($form['form_fields']);
- if(!$formFields){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $lastFormVersion = DB::table('S002V01TCAPE')->where([
- ['CAPE_NULI', '=', $form['linea']],
- ['CAPE_TIFO', '=', 'RSM']
- ])->orderBy('CAPE_VERS', 'desc')->first();
- $lastVersion = 0;
- if(is_null($lastFormVersion)){
- $lastVersion = 1;
- }else{
- $lastVersion = intval($lastFormVersion->CAPE_VERS) + 1;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TCAPE')->insert([
- 'CAPE_NULI' => $form['linea'],
- 'CAPE_TIFO' => 'RSM',
- 'CAPE_VERS' => $lastVersion,
- 'CAPE_FEAC' => $nowStr,
- 'CAPE_USAC' => $idUser,
- 'CAPE_CAMP' => $formFields
- ]);
-
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function saveNoMeasuresOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'data' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $noMeasuresFormFields = DB::table('S002V01TCAPE')->select([
- 'CAPE_VERS AS VERSION',
- 'CAPE_FEAC AS FECHA_ACTUALIZACION',
- 'CAPE_CAMP AS CAMPOS'
- ])->where([
- ['CAPE_NULI', '=', $form['linea']],
- ['CAPE_TIFO', '=', 'RSM']
- ])->orderBy('CAPE_VERS', 'desc')->first();
- if(is_null($noMeasuresFormFields)){
- return $this->responseController->makeResponse(true, 'No se encontró algún formulario registrado.', [], 404);
- }
- $noMeasuresFormFieldsArr = json_decode($noMeasuresFormFields->CAMPOS, true);
- $formData = $this->encryptionController->decrypt($form['data']);
- if(!$formData){
- return $this->responseController->makeResponse(true, 'El formulario enviado no fue encriptado correctamente.', [], 400);
- }
- $formDataArr = json_decode($formData, true);
- if(is_null($formDataArr)){
- return $this->responseController->makeResponse(true, 'El formulario enviado no tiene un formato válido.', [], 400);
- }
- $errorsArr = [];
- $formDataFn = [];
- foreach($formDataArr as $control=>$value){
- $isEncrypted = $this->encryptionController->decrypt($value);
- if($isEncrypted){
- $value = $isEncrypted;
- }
- $controlFilt = array_filter($noMeasuresFormFieldsArr, function($v, $k) use($control) {
- return $v['fieldID'] == $control;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($controlFilt) > 0){
- $controlObj = end($controlFilt);
- $controlValidators = json_decode($controlObj['validators'], true);
-
- if(in_array('CARE', $controlValidators)){
- if($value == null || is_null($value)){
- $errorsArr[] = "El campo $controlObj[label] es obligatorio.";
- }
- }
- if(in_array('NUME', $controlValidators)){
- $validNumber = $this->functionsController->validNumber($value, $controlObj['includeDecimal']);
- if(!$validNumber){
- $errorsArr[] = "El campo $controlObj[label] tiene un valor inválido.";
- }
- }
-
- if(in_array('LOMI', $controlValidators)){
- $minLengthNum = intval($controlObj['minLength']);
- if(strlen($value) < $minLengthNum){
- $errorsArr[] = "El campo $controlObj[label] debe contener al menos $minLengthNum caracteres.";
- }
- }
- if(in_array('LOMA', $controlValidators)){
- $maxLengthNum = intval($controlObj['maxLength']);
- if(strlen($value) > $maxLengthNum){
- $errorsArr[] = "El campo $controlObj[label] puede contener hasta $maxLengthNum caracteres.";
- }
- }
- $selectorOptions = [];
- foreach($controlObj['selectorOptions'] as $option){
- if(array_key_exists('value', $option)){
- $valueEnc = $this->encryptionController->decrypt($option['value']);
- if($valueEnc){
- $option['value'] = $valueEnc;
- }
- $selectorOptions[] = $option;
- }
- }
- if($controlObj['fieldType'] == 'SE-4' && !$controlObj['isMultiple']){
- $valueFilt = array_filter($selectorOptions, function($v, $k) use($value) {
- if(array_key_exists('value', $v) && $v['value'] == $value) return true;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($valueFilt) <= 0){
- $errorsArr[] = "El calor del campo $controlObj[label] es inválido.";
- }
- }
- $formDataFn[$control] = $value;
- }else{
- return $this->responseController->makeResponse(true, "El control $control no existe en la versión " . $noMeasuresFormFields->CAMPOS . " del formulario de órdenes sin mediciones", [], 400);
- }
- }
- if(count($errorsArr) > 0){
- return $this->responseController->makeResponse(true, 'Se encontraron uno o más errores.', $errorsArr, 400);
- }
-
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $formDataStrFn = json_encode($formDataFn);
- $idRegister = DB::table('S002V01TFCPE')->insertGetId([
- 'FCPE_NULI' => $form['linea'],
- 'FCPE_TIFO' => 'RSM',
- 'FCPE_VERS' => $noMeasuresFormFields->VERSION,
- 'FCPE_DATO' => $formDataStrFn,
- 'FCPE_FERE' => $nowStr,
- 'FCPE_USRE' => $idUser,
- ]);
- $idRegisterEnc = $this->encryptionController->encrypt($idRegister);
- return $this->responseController->makeResponse(false, 'EXITO', ['order' => $idRegisterEnc]);
- }
- public function getNoMeasuresOrders($idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $noMeasuresOrders = DB::table('S002V01TFCPE')->select([
- 'FCPE_IDRE AS ID_REGISTRO',
- 'FCPE_VERS AS VERSION_FORMULARIO',
- 'FCPE_ESTA AS ESTATUS',
- 'FCPE_FERE AS FECHA_REGISTRO',
- DB::raw("CONCAT(USRE.USUA_NOMB, ' ', USRE.USUA_APPA, IF(ISNULL(USRE.USUA_APMA), '', ' '), IF(ISNULL(USRE.USUA_APMA), '', USRE.USUA_APMA), ' (', FCPE_USRE, ')') AS USUARIO_REGISTRO"),
- 'FCPE_FEAC AS FECHA_ACTUALIZACION',
- DB::raw("IF(ISNULL(USMO.USUA_NOMB), '-', CONCAT(USMO.USUA_NOMB, ' ', USMO.USUA_APPA, IF(ISNULL(USMO.USUA_APMA), '', ' '), IF(ISNULL(USMO.USUA_APMA), '', USMO.USUA_APMA), ' (', FCPE_USAC, ')')) AS USUARIO_ACTUALIZACION")
- ])->join(DB::raw('S002V01TUSUA USRE'), 'USRE.USUA_IDUS', '=', 'FCPE_USRE')
- ->leftJoin(DB::raw('S002V01TUSUA USMO'), 'USMO.USUA_IDUS', '=', 'FCPE_USAC')
- ->orderBy('FCPE_IDRE', 'desc')->where([
- ['FCPE_NULI', '=', $line],
- ['FCPE_IOMC', '=', null]
- ])->get()->all();
- foreach($noMeasuresOrders as $key=>$order){
- $order->ID_REGISTRO = $this->encryptionController->encrypt($order->ID_REGISTRO);
- $order->USUARIO_REGISTRO = $this->encryptionController->encrypt($order->USUARIO_REGISTRO);
- if(!is_null($order->USUARIO_ACTUALIZACION)){
- $order->USUARIO_ACTUALIZACION = $this->encryptionController->encrypt($order->USUARIO_ACTUALIZACION);
- }
- $noMeasuresOrders[$key] = $order;
- }
- return $this->responseController->makeResponse(false, 'EXITO', $noMeasuresOrders);
- }
- public function getNoMeasuresOrder($idRegister, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idRegister = $this->encryptionController->decrypt($idRegister);
- if(!$idRegister){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud no fue encriptado correctamente.', [], 400);
- }
- $noMeasuresOrder = DB::table('S002V01TFCPE')->select([
- 'FCPE_IDRE AS ID_REGISTRO',
- 'FCPE_VERS AS VERSION_FORMULARIO',
- 'FCPE_DATO AS DATOS',
- 'FCPE_VAPO AS VALIDADO_POR',
- 'FCPE_EXPE AS EXPEDIENTE',
- 'FCPE_ESTA AS ESTATUS',
- 'FCPE_ACRE AS ACTIVIDADES',
- 'FCPE_EVCI AS EVIDENCIA',
- 'FCPE_FERE AS FECHA_REGISTRO',
- DB::raw("CONCAT(USRE.USUA_NOMB, ' ', USRE.USUA_APPA, IF(ISNULL(USRE.USUA_APMA), '', ' '), IF(ISNULL(USRE.USUA_APMA), '', USRE.USUA_APMA), ' (', FCPE_USRE, ')') AS USUARIO_REGISTRO"),
- 'FCPE_FEAC AS FECHA_ACTUALIZACION',
- DB::raw("IF(ISNULL(USMO.USUA_NOMB), '-', CONCAT(USMO.USUA_NOMB, ' ', USMO.USUA_APPA, IF(ISNULL(USMO.USUA_APMA), '', ' '), IF(ISNULL(USMO.USUA_APMA), '', USMO.USUA_APMA), ' (', FCPE_USAC, ')')) AS USUARIO_ACTUALIZACION")
- ])->join(DB::raw('S002V01TUSUA USRE'), 'USRE.USUA_IDUS', '=', 'FCPE_USRE')
- ->leftJoin(DB::raw('S002V01TUSUA USMO'), 'USMO.USUA_IDUS', '=', 'FCPE_USAC')->where([
- ['FCPE_NULI', '=', $line],
- ['FCPE_TIFO', '=', 'RSM'],
- ['FCPE_IDRE', '=', $idRegister]
- ])->first();
- if(is_null($noMeasuresOrder)){
- return $this->responseController->makeResponse(true, 'La solicitud la consultada no está registrada.', [], 404);
- }
- $noMeasuresOrder->ID_REGISTRO = $this->encryptionController->encrypt($noMeasuresOrder->ID_REGISTRO);
- $orderForm = DB::table('S002V01TCAPE')->select([
- 'CAPE_VERS AS VERSION',
- 'CAPE_FEAC AS FECHA_ACTUALIZACION',
- 'CAPE_CAMP AS CAMPOS'
- ])->where([
- ['CAPE_NULI', '=', $line],
- ['CAPE_TIFO', '=', 'RSM'],
- ['CAPE_VERS', '=', $noMeasuresOrder->VERSION_FORMULARIO],
- ])->first();
- if(is_null($orderForm)){
- return $this->responseController->makeResponse(true, 'El formulario en el que se registró la orden solicitada no existe', [], 404);
- }
- $fieldsArr = json_decode($orderForm->CAMPOS, true);
- $dataArr = json_decode($noMeasuresOrder->DATOS, true);
- $dataArrFn = [];
- foreach($dataArr as $key=>$value){
- $fieldFilt = array_filter($fieldsArr, function($v, $k) use($key){
- $idNum = intval($v['fieldID']);
- return $idNum == $key;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($fieldFilt) > 0){
- $field = end($fieldFilt);
- if($field['fieldType'] == 'SE-4'){
- $selectorOptions = $field['selectorOptions'];
- foreach($selectorOptions as $option){
- if(array_key_exists('value', $option)){
- $valueDec = $this->encryptionController->decrypt($option['value']);
- if($valueDec == $value){
- $value = $option['value'];
- }
- }
- }
- }
- }
- $dataArrFn[$key] = $value;
- }
- foreach($fieldsArr as $key=>$value){
- if(array_key_exists('fieldID', $value)){
- $value['fieldID'] = $this->encryptionController->encrypt($value['fieldID']);
- }
- $fieldsArr[$key] = $value;
- }
- $dataStr = json_encode($dataArrFn);
- $noMeasuresOrder->DATOS = $this->encryptionController->encrypt($dataStr);
- $orderForm->CAMPOS = $fieldsArr;
- if(!is_null($noMeasuresOrder->ACTIVIDADES)){
- $activitiesArr = json_decode($noMeasuresOrder->ACTIVIDADES, true);
- foreach($activitiesArr as $key=>$activity){
- $activity['id'] = $this->encryptionController->encrypt($activity['id']);
- $activitiesArr[$key] = $activity;
- }
- $noMeasuresOrder->ACTIVIDADES = $activitiesArr;
- }
- if(!is_null($noMeasuresOrder->EVIDENCIA)){
- $evidenceArr = json_decode($noMeasuresOrder->EVIDENCIA, true);
- foreach($evidenceArr as $key=>$file){
- $evidenceArr[$key] = $this->encryptionController->encrypt($file);
- }
- $noMeasuresOrder->EVIDENCIA = $evidenceArr;
- }
- return $this->responseController->makeResponse(false, 'EXITO', [
- 'DATOS' => $noMeasuresOrder,
- 'FORMULARIO' => $orderForm
- ]);
- }
- public function updateNoMeasuresOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'data' => 'required|string',
- 'id_order' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }
- $noMeasuresFormFields = DB::table('S002V01TCAPE')->select([
- 'CAPE_VERS AS VERSION',
- 'CAPE_FEAC AS FECHA_ACTUALIZACION',
- 'CAPE_CAMP AS CAMPOS'
- ])->where([
- ['CAPE_NULI', '=', $form['linea']],
- ['CAPE_TIFO', '=', 'RSM'],
- ['CAPE_VERS', '=', $order->FCPE_VERS]
- ])->orderBy('CAPE_VERS', 'desc')->first();
- if(is_null($noMeasuresFormFields)){
- return $this->responseController->makeResponse(true, 'El formulario relacionado a la solicitud no existe.', [], 404);
- }
- $noMeasuresFormFieldsArr = json_decode($noMeasuresFormFields->CAMPOS, true);
- $formData = $this->encryptionController->decrypt($form['data']);
- if(!$formData){
- return $this->responseController->makeResponse(true, 'El formulario enviado no fue encriptado correctamente.', [], 400);
- }
- $formDataArr = json_decode($formData, true);
- if(is_null($formDataArr)){
- return $this->responseController->makeResponse(true, 'El formulario enviado no tiene un formato válido.', [], 400);
- }
- $errorsArr = [];
- $formDataFn = [];
- foreach($formDataArr as $control=>$value){
- $isEncrypted = $this->encryptionController->decrypt($value);
- if($isEncrypted){
- $value = $isEncrypted;
- }
- $controlFilt = array_filter($noMeasuresFormFieldsArr, function($v, $k) use($control) {
- return $v['fieldID'] == $control;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($controlFilt) > 0){
- $controlObj = end($controlFilt);
- $controlValidators = json_decode($controlObj['validators'], true);
-
- if(in_array('CARE', $controlValidators)){
- if($value == null || is_null($value)){
- $errorsArr[] = "El campo $controlObj[label] es obligatorio.";
- }
- }
- if(in_array('NUME', $controlValidators)){
- $validNumber = $this->functionsController->validNumber($value, $controlObj['includeDecimal']);
- if(!$validNumber){
- $errorsArr[] = "El campo $controlObj[label] tiene un valor inválido.";
- }
- }
-
- if(in_array('LOMI', $controlValidators)){
- $minLengthNum = intval($controlObj['minLength']);
- if(strlen($value) < $minLengthNum){
- $errorsArr[] = "El campo $controlObj[label] debe contener al menos $minLengthNum caracteres.";
- }
- }
- if(in_array('LOMA', $controlValidators)){
- $maxLengthNum = intval($controlObj['maxLength']);
- if(strlen($value) > $maxLengthNum){
- $errorsArr[] = "El campo $controlObj[label] puede contener hasta $maxLengthNum caracteres.";
- }
- }
- $selectorOptions = [];
- foreach($controlObj['selectorOptions'] as $option){
- if(array_key_exists('value', $option)){
- $valueEnc = $this->encryptionController->decrypt($option['value']);
- if($valueEnc){
- $option['value'] = $valueEnc;
- }
- $selectorOptions[] = $option;
- }
- }
- if($controlObj['fieldType'] == 'SE-4' && !$controlObj['isMultiple']){
- $valueFilt = array_filter($selectorOptions, function($v, $k) use($value) {
- if(array_key_exists('value', $v) && $v['value'] == $value) return true;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($valueFilt) <= 0){
- $errorsArr[] = "El calor del campo $controlObj[label] es inválido.";
- }
- }
- $formDataFn[$control] = $value;
- }else{
- return $this->responseController->makeResponse(true, "El control $control no existe en la versión " . $noMeasuresFormFields->CAMPOS . " del formulario de órdenes sin mediciones", [], 400);
- }
- }
- if(count($errorsArr) > 0){
- return $this->responseController->makeResponse(true, 'Se encontraron uno o más errores.', $errorsArr, 400);
- }
-
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $formDataStrFn = json_encode($formDataFn);
- DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->update([
- 'FCPE_DATO' => $formDataStrFn,
- 'FCPE_FEAC' => $nowStr,
- 'FCPE_USAC' => $idUser,
- ]);
- return $this->responseController->makeResponse(false, 'EXITO');
- }
- public function deleteNoMeasuresOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }else if($order->FCPE_ESTA == 'EL'){
- return $this->responseController->makeResponse(true, 'La solicitud seleccionada está eliminada.', [], 401);
- }
-
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->update([
- 'FCPE_ESTA' => 'EL',
- 'FCPE_FEAC' => $nowStr,
- 'FCPE_USAC' => $idUser,
- ]);
- return $this->responseController->makeResponse(false, 'EXITO');
- }
- public function noMeasuresOrderValidation(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'validated_by' => 'required|string',
- 'record' => 'required|string',
- 'validation' => 'required|string|in:Si,No'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }else if($order->FCPE_ESTA != 'PE'){
- return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está pendiente.', [], 401);
- }
- $validationStatus = $form['validation'] == 'Si' ? 'VA' : 'NV';
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->update([
- 'FCPE_VAPO' => $form['validated_by'],
- 'FCPE_EXPE' => $form['record'],
- 'FCPE_ESTA' => $validationStatus,
- 'FCPE_FEAC' => $nowStr,
- 'FCPE_USAC' => $idUser,
- ]);
- return $this->responseController->makeResponse(false, 'EXITO');
- }
- public function closeNoMeasuresOrder(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'evidence' => 'required|json',
- 'activities' => 'required|json',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }else if($order->FCPE_ESTA != 'VA'){
- return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está validada.', [], 401);
- }
- $activitiesArr = json_decode($form['activities'], true);
- if(count($activitiesArr) <= 0){
- return $this->responseController->makeResponse(true, 'El arreglo de actividades está vacío.', [], 400);
- }
- foreach($activitiesArr as $key=>$activity){
- if(!array_key_exists('id', $activity)){
- return $this->responseController->makeResponse(true,"El elemento $key de la lista de actividades tiene un formato inválido.", [], 400);
- }
- $activity['id'] = $this->encryptionController->decrypt($activity['id']);
- $activitiesArr[$key] = $activity;
- }
- $activitiesStr = json_encode($activitiesArr);
- $evidenceArr = json_decode($form['evidence'], true);
-
- if(count($evidenceArr) <= 0){
- return $this->responseController->makeResponse(true, 'El arreglo de evidencias está vacío.', [], 400);
- }
- $evidenceArrFn = [];
- foreach($evidenceArr as $key=>$attached){
- $idDec = $this->encryptionController->decrypt($attached['id']);
- if(!$idDec){
- return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
- }
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_IDAR', '=', $idDec],
- ['ARTE_NULI', '=', $form['linea']]
- ])->first();
- if(is_null($tempFile)){
- return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
- }else if($tempFile->ARTE_ESTA == 'Eliminado'){
- return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
- }
- $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMCO', 'OR', $tempFile, $idUser);
- if(!$finalFile[0]){
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- }else{
- $evidenceArrFn[] = $finalFile[1];
- }
- }
- $evidenceStr = json_encode($evidenceArrFn);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->update([
- 'FCPE_ESTA' => 'CE',
- 'FCPE_ACRE' => $activitiesStr,
- 'FCPE_EVCI' => $evidenceStr,
- 'FCPE_FEAC' => $nowStr,
- 'FCPE_USAC' => $idUser,
- ]);
- return $this->responseController->makeResponse(false, 'EXITO');
- }
- public function closedNoMeasuresOrderValidation(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'validation' => 'required|string|in:Si,No',
- 'validated_by' => 'required|string',
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }else if($order->FCPE_ESTA != 'CE'){
- return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está cerrada.', [], 401);
- }
- $validationStatus = $form['validation'] == 'Si' ? 'CV' : 'VA';
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->update([
- 'FCPE_CVPO' => $form['validated_by'],
- 'FCPE_ESTA' => $validationStatus,
- 'FCPE_FEAC' => $nowStr,
- 'FCPE_USAC' => $idUser,
- ]);
- return $this->responseController->makeResponse(false, 'EXITO');
- }
- public function generateNoMeasuresReport(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'report_type' => 'required|string|in:RITR,RIIF,RAAV',
- 'report_data' => 'required|string'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TFCPE')->where([
- ['FCPE_NULI', '=', $form['linea']],
- ['FCPE_IDRE', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }else if($order->FCPE_ESTA != 'CV'){
- return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está cerrada y validada.', [], 401);
- }
- $reportDataDec = $this->encryptionController->decrypt($form['report_data']);
- if(!$reportDataDec){
- return $this->responseController->makeResponse(true, 'Los datos del reporte no fueron encriptados correctamente.', [], 400);
- }
- $reportDataArr = json_decode($reportDataDec, true);
- $html = '';
- $crrcLogo = file_get_contents($this->functionsController->getBasePath() . "\storage\app\public\global_resources\logo_crrc.webp");
- $ingeropLogo = file_get_contents($this->functionsController->getBasePath() ."\storage\app\public\global_resources\logo_ingerop.png");
- $stcLogo = file_get_contents($this->functionsController->getBasePath() ."\storage\app\public\global_resources\logo_stc.webp");
- $stcShortLogo = file_get_contents($this->functionsController->getBasePath() ."\storage\app\public\global_resources\logo_stc_small.png");
- $crrcLogoStr = "data:image/svg+xml;base64," . base64_encode($crrcLogo);
- $ingeropLogoStr = "data:image/svg+xml;base64," . base64_encode($ingeropLogo);
- $stcLogoStr = "data:image/svg+xml;base64," . base64_encode($stcLogo);
- $stcShortLogoStr = "data:image/svg+xml;base64," . base64_encode($stcShortLogo);
- $noar = '';
- if($form['report_type'] == 'RITR'){
- $html = file_get_contents($this->templatesUbic . "01-GMCO-PL-010101-000001=01=PDF_REPORTE_KIZEO_01.html");
- $html = str_replace("%logo_crrc%", $crrcLogoStr, $html);
- $html = str_replace("%logo_stc%", $stcLogoStr, $html);
- $html = str_replace("%logo_ingerop%", $ingeropLogoStr, $html);
- $noar = "rep_int_trenes_mod_nm16_nm22_ord_$idOrder";
- }else if($form['report_type'] == 'RIIF'){
- $html = file_get_contents($this->templatesUbic . "01-GMCO-PL-010101-000001=01=PDF_REPORTE_KIZEO_02.html");
- $html = str_replace("%logo_stc_small%", $stcShortLogoStr, $html);
- $html = str_replace("%logo_crrc%", $crrcLogoStr, $html);
- $noar = "rep_inc_inst_fija_ord_$idOrder";
- }else if($form['report_type'] == 'RAAV'){
- $html = file_get_contents($this->templatesUbic . "01-GMCO-PL-010101-000001=01=PDF_REPORTE_KIZEO_03.html");
- $html = str_replace("%logo_crrc%", $crrcLogoStr, $html);
- $html = str_replace("%logo_stc%", $stcLogoStr, $html);
- $html = str_replace("%logo_ingerop%", $ingeropLogoStr, $html);
- $noar = "reg_aten_aver_ord_$idOrder";
- }
- if(strlen($html) <= 0){
- return $this->responseController->makeResponse(true, 'No se encontró ninguna plantilla para el reporte solicitado.', [], 404);
- }
- foreach($reportDataArr as $key=>$val){
- $keyInd = "##$key##";
- $val = is_null($val) ? ' ' : $val;
- $html = str_replace($keyInd, $val, $html);
- }
- $como = 'GMCO';
- $cldo = 'IN';
- $exte = "pdf";
- $line = intval($form['linea']) < 10 ? "0$form[linea]" : "$form[linea]";
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $nowArr = explode(" ", $nowStr);
- $dateArr = explode("-", $nowArr[0]);
- $year = substr($dateArr[0], 2);
- $fecr = $year . $dateArr[1] .$dateArr[2];
- $sec = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $line],
- ['AFAL_COMO', '=', $como],
- ['AFAL_CLDO', '=', $cldo],
- ])->orderBy('AFAL_NUSE', 'desc')->first();
- $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
- for($i = strlen($nuse); $i < 6; $i++){
- $nuse = "0$nuse";
- }
- $ver = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $line],
- ['AFAL_COMO', '=', $como],
- ['AFAL_CLDO', '=', $cldo],
- ['AFAL_NOAR', '=', $noar],
- ['AFAL_EXTE', '=', $exte],
- ])->orderBy('AFAL_NUVE', 'desc')->first();
- $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
- for($i = strlen($nuve); $i < 2; $i++){
- $nuve = "0$nuve";
- }
- $filePath = $this->functionsController->getBasePath() .'\public_files\\';
- $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
- $dompdf = new Dompdf();
- $dompdf->loadHtml($html);
- $dompdf->setPaper('A4', 'portrait');
- $dompdf->render();
- $output = $dompdf->output();
-
- $tempFile = $filePath . $fileName;
- if(!file_exists($tempFile)){
- fopen($tempFile, 'w');
- }
- file_put_contents($tempFile, $output);
- $ubic = Storage::putFile('files', new File($tempFile));
- $ubic = str_replace("/", "\\", $ubic);
- $ubic = $this->functionsController->getBasePath() ."\sam\storage\app\\" . $ubic;
- $tama = filesize($ubic);
- $usac = json_encode([$idUser]);
- unlink($tempFile);
- DB::table('S002V01TAFAL')->insert([
- 'AFAL_NULI' => $line,
- 'AFAL_COMO' => $como,
- 'AFAL_CLDO' => $cldo,
- 'AFAL_FECR' => $fecr,
- 'AFAL_NUSE' => $nuse,
- 'AFAL_NUVE' => $nuve,
- 'AFAL_NOAR' => $noar,
- 'AFAL_EXTE' => $exte,
- 'AFAL_TAMA' => $tama,
- 'AFAL_UBIC' => $ubic,
- 'AFAL_USAC' => $usac,
- 'AFAL_USRE' => $idUser,
- 'AFAL_FERE' => $nowStr,
- ]);
-
- return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
- }
- public function getWorkOrderStaff($idOrder, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($idOrder);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden relacionada no está encriptado correctamente', [], 400);
- }
- $workOrder = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $line],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
- if(is_null($workOrder)){
- return $this->responseController->makeResponse(true, 'La orden relacionada no está registrada.', [], 404);
- }
- $staffArr = json_decode($workOrder->OTCO_PEIN, true);
- $staffArrFn = [];
- foreach($staffArr as $val){
- if(array_key_exists('TYPE', $val)){
- if($val['TYPE'] == 'EQ'){
- $workTeamStaff = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_EQTR', '=', $val['ID']]
- ])->get()->all();
- foreach($workTeamStaff as $item){
- $itemID = $item->PERS_IDPE;
- $itemFilt = array_filter($staffArrFn, function($v, $k) use($itemID) {
- return $v['ID'] == $itemID;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($itemFilt) <= 0){
- $staffArrFn[] = [
- 'ID' => $itemID,
- 'ID_USER' => $item->USUA_IDUS,
- 'NAME' => $this->functionsController->joinName($item->USUA_NOMB, $item->USUA_APPA, $item->USUA_APMA),
- 'TYPE' => $item->PERS_TICO,
- ];
- }
- }
- }else if($val['TYPE'] == 'SU'){
- $subcontratistStaff = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPS', '=', $val['ID']]
- ])->get()->all();
- foreach($subcontratistStaff as $item){
- $itemID = $item->PERS_IDPE;
- $itemFilt = array_filter($staffArrFn, function($v, $k) use($itemID) {
- return $v['ID'] == $itemID;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($itemFilt) <= 0){
- $staffArrFn[] = [
- 'ID' => $itemID,
- 'ID_USER' => $item->USUA_IDUS,
- 'NAME' => $this->functionsController->joinName($item->USUA_NOMB, $item->USUA_APPA, $item->USUA_APMA),
- 'TYPE' => $item->PERS_TICO,
- ];
- }
- }
- }else if($val['TYPE'] == 'EM'){
- $employee =DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPE', '=', $val['ID']]
- ])->first();
- if(!is_null($employee)){
- $itemID = $employee->PERS_IDPE;
- $itemFilt = array_filter($staffArrFn, function($v, $k) use($itemID) {
- return $v['ID'] == $itemID;
- }, ARRAY_FILTER_USE_BOTH);
- if(count($itemFilt) <= 0){
- $staffArrFn[] = [
- 'ID' => $itemID,
- 'ID_USER' => $employee->USUA_IDUS,
- 'NAME' => $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA),
- 'TYPE' => $employee->PERS_TICO,
- ];
- }
- }
- }
- }
- }
- foreach($staffArrFn as $key=>$item){
- $item['ID'] = $this->encryptionController->encrypt($item['ID']);
- $item['ID_USER'] = $this->encryptionController->encrypt($item['ID_USER']);
- $staffArrFn[$key] = $item;
- }
- return $this->responseController->makeResponse(false, 'EXITO', $staffArr);
- }
- public function getWorkOrderAttendance($idOrder, $idUser, $line) {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($idOrder);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la orden relacionada no está encriptado correctamente', [], 400);
- }
- $workOrder = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $line],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
- if(is_null($workOrder)){
- return $this->responseController->makeResponse(true, 'La orden relacionada no está registrada.', [], 404);
- }
- $statusHistory = json_decode($workOrder->OTCO_HIES, true);
- $validatedHistoryFilt = array_filter($statusHistory, function($v, $k) {
- return $v['ESTADO'] == 'VA';
- }, ARRAY_FILTER_USE_BOTH);
- if(empty($validatedHistoryFilt)){
- return $this->responseController->makeResponse(true, 'La orden relacionada no está en el estado de validación', [], 404);
- }
- $validatedHistory = end($validatedHistoryFilt);
- $attendance = array_key_exists('ATENCION', $validatedHistory) ? $validatedHistory['ATENCION'] : [];
- $attendanceAux = [];
- foreach($attendance as $item){
- if($item['RESPUESTA'] == 'A'){
- $attendanceAux[] = $item;
- }
- }
- return $this->responseController->makeResponse(false, 'EXITO', $attendanceAux);
- }
- public function setWorkOrderAttendance(Request $request) {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'attendance' => 'required|string|in:A,R',
- 'data' => 'required|string'
- ]);
-
- if($validator->fails()){
- return $this->responseController->makeResponse(
- true,
- "Se encontraron uno o más errores.",
- $this->responseController->makeErrors(
- $validator->errors()->messages()
- ),
- 401
- );
- }
- $form = $request->all();
- $idUser = $this->encryptionController->decrypt($form['id_user']);
- if(!$idUser){
- return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $form['linea']],
- ['USUA_IDUS', '=', $idUser]
- ])->first();
-
- if(is_null($usr)){
- return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if(!$idOrder){
- return $this->responseController->makeResponse(true, 'El ID de la solicitud seleccionada no fue encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->first();
-
- if(is_null($order)){
- return $this->responseController->makeResponse(true, 'La orden que desea actualizar no existe.', [], 404);
- }else if($order->OTCO_ESOR != 'VA'){
- return $this->responseController->makeResponse(true, 'La solicitud seleccionada no está validada.', [], 401);
- }
- if($form['attendance'] == 'A' && !str_contains($form['data'], 'data:image/png')){
- return $this->responseController->makeResponse(true, 'El archivo de la firma capturada es inválido.', [], 400);
- }else if($form['attendance'] == 'R' && strlen($form['data']) < 10){
- return $this->responseController->makeResponse(true, 'La cadena de comentarios tiene una longitud menor a 10 caracteres.', [], 400);
- }
- $userAttendance = ["ID" => $idUser, "RESPUESTA" => $form['attendance']];
- $signature = null;
- $comments = null;
- if($form['attendance'] == 'A'){
- $filesPath = str_replace("app\\Http\\Controllers", "storage\\app\\files", __DIR__);
- if(!file_exists($filesPath)){
- return $this->responseController->makeResponse(true, 'No se encontró la ubicación de almacenamiento de archivos.', [], 400);
- }
- generateSignatureFileName:
- $signatureFileName = $this->generateSignatureImageName();
- $signatureFileDir = $filesPath . "\\" . $signatureFileName;
- $signatureFileExists = file_exists($signatureFileDir);
- if($signatureFileExists) goto generateSignatureFileName;
- $signatureFileData = str_replace("data:image/png;base64,", "", $form['data']);
- file_put_contents($signatureFileDir, base64_decode($signatureFileData));
- $now = $this->functionsController->now();
- $year = $now->year;
- $month = $now->month < 10 ? "0{$now->month}" : "0{$now->month}";
- $day = $now->day < 10 ? "0{$now->day}" : "{$now->day}";
- $fecr = substr("$year", -2) . $month . $day;
- $sec = DB::table('S002V01TAFAL')->where([
- ['AFAL_COMO', '=', "GMCO"],
- ['AFAL_CLDO', '=', "FO"],
- ['AFAL_NULI', '=', $form['linea']],
- ])->orderBy('AFAL_NUSE', 'desc')->first();
- $nuse = 1;
- if(!is_null($sec)){
- $nuse = intval($sec->AFAL_NUSE) + 1;
- }
- $noar = "firma_conformidad_" . $idUser;
- $exte = "png";
- $ver = DB::table('S002V01TAFAL')->where([
- ['AFAL_NULI', '=', $form['linea']],
- ['AFAL_COMO', '=', "GMCO"],
- ['AFAL_CLDO', '=', "FO"],
- ['AFAL_NOAR', '=', $noar],
- ['AFAL_EXTE', '=', $exte],
- ])->orderBy('AFAL_NUVE', 'desc')->first();
- $nuve = 1;
- if(!is_null($ver)){
- $nuve = intval($sec->AFAL_NUVE) + 1;
- }
- $tama = filesize($signatureFileDir);
- $code = intval($form['linea']) < 10 ? "0$form[linea]" : "$form[linea]";
- $code .= "-GMCO-FO-$fecr-";
- for($i = strlen($nuse); $i < 6; $i++){
- $code .= "0";
- }
- $code .= "$nuse=";
- $code .= $nuve < 10 ? "0$nuve=" : "$nuve=";
- $code .= "$noar.$exte";
- $usac = json_encode([$idUser]);
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TAFAL')->insert([
- 'AFAL_NULI' => $form['linea'],
- 'AFAL_COMO' => "GMCO",
- 'AFAL_CLDO' => "FO",
- 'AFAL_FECR' => $fecr,
- 'AFAL_NUSE' => $nuse,
- 'AFAL_NUVE' => $nuve,
- 'AFAL_NOAR' => $noar,
- 'AFAL_EXTE' => $exte,
- 'AFAL_TAMA' => $tama,
- 'AFAL_UBIC' => $signatureFileDir,
- 'AFAL_USAC' => $usac,
- 'AFAL_USRE' => $idUser,
- 'AFAL_FERE' => $nowStr
- ]);
- $signature = $code;
- }else if($form['attendance'] == 'R'){
- $comments = $form['data'];
- }
- if(!is_null($signature) || !is_null($comments)){
- $userAttendance['FIRMA'] = $signature;
- $userAttendance['COMENTARIOS'] = $comments;
- $statusHistoryArr = json_decode($order->OTCO_HIES, true);
- $validatedHistoryFilt = array_filter($statusHistoryArr, function($v, $k) {
- return $v['ESTADO'] == 'VA';
- }, ARRAY_FILTER_USE_BOTH);
- if(!empty($validatedHistoryFilt)){
- $validatedHistory = end($validatedHistoryFilt);
- $validatedHistoryKeys = array_keys($validatedHistoryFilt);
- $validatedHistoryKey = end($validatedHistoryKeys);
- $attendance = array_key_exists('ATENCION', $validatedHistory) ? $validatedHistory['ATENCION'] : [];
-
- $attendance[] = $userAttendance;
- $validatedHistory['ATENCION'] = $attendance;
- $statusHistoryArr[$validatedHistoryKey] = $validatedHistory;
- }
- $statusHistoryStr = json_encode($statusHistoryArr);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTCO')->where([
- ['OTCO_NULI', '=', $form['linea']],
- ['OTCO_IDOT', '=', $idOrder]
- ])->update([
- "OTCO_HIES" => $statusHistoryStr,
- "OTCO_USMO" => $idUser,
- "OTCO_FEMO" => $nowStr,
- ]);
- }
- $userName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $action = $form['attendance'] == 'A' ? 'aceptó' : 'rechazó';
- $notificationActions = [];
- if($form['attendance'] == 'A'){
- $notificationActions[] = [
- 'BOTON' => 'Revisar firma',
- 'FUNCION' => 'reviewSignatureInCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder), $this->encryptionController->encrypt($idUser)])
- ];
- }else if($form['attendance'] == 'R'){
- $notificationActions[] = [
- 'BOTON' => 'Revisar comentarios',
- 'FUNCION' => 'reviewCommentsInCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder), $this->encryptionController->encrypt($idUser)])
- ];
- $notificationActions[] = [
- 'BOTON' => 'Reasignar orden',
- 'FUNCION' => 'revalidateCorrectiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idOrder)])
- ];
- }
-
- $notificationActions[] = [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMCO/ORTR/GEOP')])
- ];
-
- $this->notificationsController->emitNotification(
- 'S002V01M09GMCO',
- "Orden de mantenimiento correctivo #$idOrder",
- "El usuario $userName ($idUser) $action atender la orden de mantenimiento #$idOrder.",
- $notificationActions,
- [$order->OTCO_IDUR],
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idOrder,
- 'Correctivo'
- );
- return $this->responseController->makeResponse(false, 'EXITO');
- }
- private function generateSignatureImageName(){
- $upperLetters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"];
- $lowerLetters = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
- $numbers = ["0","1","2","3","4","5","6","7","8","9"];
- $fileName = "";
- for($i = 0; $i < 40; $i++){
- $charTypeSelector = rand(0, 2);
- $selectedChar = "";
- switch($charTypeSelector){
- case 0:
- $charSelector = rand(0, count($upperLetters) - 1);
- $selectedChar = $upperLetters[$charSelector];
- break;
- case 1:
- $charSelector = rand(0, count($lowerLetters) - 1);
- $selectedChar = $lowerLetters[$charSelector];
- break;
- case 2:
- $charSelector = rand(0, count($numbers) - 1);
- $selectedChar = $numbers[$charSelector];
- break;
- }
- $selectedChar = empty($selectedChar) ? 'A' : $selectedChar;
- $fileName .= $selectedChar;
- }
- return $fileName . '.png';
- }
- }
|