| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631 |
- <?php
- namespace App\Http\Controllers;
- use Illuminate\Http\Request;
- use Illuminate\Support\Facades\DB;
- use Illuminate\Support\Facades\Validator;
- use Illuminate\Support\Carbon;
- use Illuminate\Support\Facades\Log;
- use Dompdf\Dompdf;
- use Illuminate\Support\Facades\Storage;
- use Illuminate\Http\File;
- use PhpOffice\PhpSpreadsheet\IOFactory;
- use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
- use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
- use PhpOffice\PhpSpreadsheet\Spreadsheet;
- use ElephantIO\Client;
- class PreventiveMaintenanceController extends Controller
- {
- private $responseController;
- private $encryptionController;
- private $functionsController;
- private $templatesUbic;
- private $documentManagementController;
- private $notificationsController;
- public function __construct()
- {
- $this->responseController = new ResponseController();
- $this->encryptionController = new EncryptionController();
- $this->functionsController = new FunctionsController();
- $this->templatesUbic = $this->functionsController->getBasePath() . "\storage\app\public\pdf_templates\\01_03_GMPR\\";
- $this->documentManagementController = new DocumentManagementController();
- $this->notificationsController = new NotificationsController();
- }
- 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',
- 'description' => 'required|string',
- 'instructions' => 'required|json',
- 'start_date' => 'required|date',
- 'start_hour' => 'required|string',
- 'end_date' => 'date',
- 'end_hour' => 'string',
- 'equipment' => 'required|string',
- 'inm_time' => 'required|numeric',
- 'total_time' => 'required|numeric',
- 'resources' => 'required|json',
- 'activator' => 'required|string',
- 'attached' => 'json',
- 'exists' => 'required|string|in:S,N',
- 'id_order' => 'required_if:exists,=,S|string',
- 'clasification' => 'required|string|max:100',
- 'staff' => '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);
- }
- $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;
- }
- $rhre = json_encode($resources);
- $idActivator = $this->encryptionController->decrypt($form['activator']);
- if (!$idActivator) {
- return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400);
- }
- $activator = DB::table('S002V01TACTI')->where([
- ['ACTI_NULI', '=', $form['linea']],
- ['ACTI_IDAC', '=', $idActivator]
- ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first();
- if (is_null($activator)) {
- return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
- }
- $startDateTime = "$form[start_date] $form[start_hour]";
- $validStartDateTime = $this->functionsController->validateDate($startDateTime);
- if (!$validStartDateTime) {
- return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400);
- }
- $dateTimeStart = new Carbon($startDateTime);
- if ($activator->ACTI_TIAC == 'Calendario' || $activator->ACTI_TIAC == 'Sintoma') {
- $activatorConfig = json_decode($activator->ACTI_COAC, true);
- $activatorStartDate = explode('T', $activatorConfig['startDate'])[0];
- $activatorStartDateTime = "$activatorStartDate $activatorConfig[startHour]";
- $activatorStartDateTimeObj = new Carbon($activatorStartDateTime);
- if ($dateTimeStart->lt($activatorStartDateTimeObj)) {
- return $this->responseController->makeResponse(true, 'La fecha de inicio de la orden no puede ser menor a la fecha de inicio configurada en el activador.', [], 400);
- }
- }
- $ftap = '0001-01-01 00:00:00';
- if (isset($form['end_hour'])) {
- $endDateTime = "$form[end_date] $form[end_hour]";
- $validEndDateTime = $this->functionsController->validateDate($endDateTime);
- if (!$validEndDateTime) {
- return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400);
- }
- $dateTimeEnd = new Carbon("$endDateTime");
- if ($dateTimeStart->gt($dateTimeEnd)) {
- return $this->responseController->makeResponse(true, 'La hora de término es menor a la hora de inicio.', [], 400);
- }
- $ftap = $dateTimeEnd->toDateTimeString();
- }
- $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 equipaiento seleccionado no existe.', [], 404);
- } else if ($activator->CONA_COEQ != $equipmentCode) {
- return $this->responseController->makeResponse(true, 'El activador seleccionado no puede ser asignado al equipamiento relacionado, ya que el contador pertenece a otro equipo.', [], 401);
- } else if (floatval($form['inm_time']) > floatval($form['total_time'])) {
- return $this->responseController->makeResponse(true, 'El tiempo de inmovilización aproximado no puede ser mayor al tiempo de duración aproximada.', [], 400);
- }
- $staffArr = json_decode($form['staff'], true);
- if (empty($staffArr)) {
- return $this->responseController->makeResponse(true, 'El JSON de 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']
- ];
- }
- $instructionsArr = json_decode($form['instructions'], true);
- foreach ($instructionsArr as $key => $instruction) {
- $instructionInd = $key + 1;
- $instructionStartArr = explode(' ', $instruction['INICIO']);
- if (count($instructionStartArr) != 3) {
- return $this->responseController->makeResponse(true, "La fecha de inicio de la instrucción $instructionInd tiene un formato inválido.", [], 400);
- }
- $startHourArr = explode(':', $instructionStartArr[1]);
- $startHourInt = intval($startHourArr[0]);
- if ($instructionStartArr[2] == 'PM' && $startHourInt < 12) {
- $startHourInt = $startHourInt + 12;
- }
- $startOrigin = $instruction['INICIO'];
- $startHourStr = $startHourInt < 10 ? "0$startHourInt" : "$startHourInt";
- $instructionStartStr = "$startHourStr:$startHourArr[1]:00";
- $instruction['INICIO'] = "$instructionStartArr[0] $instructionStartStr";
- $instructionStartDateTime = new Carbon($instruction['INICIO']);
- if ($instructionStartDateTime->lt($dateTimeStart)) {
- return $this->responseController->makeResponse(true, "La fecha de inicio de la instrucción $instructionInd no puede ser menor a la fecha de inicio del activador.", [], 400);
- }
- $instructionEndArr = explode(' ', $instruction['FIN']);
- if (count($instructionEndArr) != 3) {
- return $this->responseController->makeResponse(true, "La fecha de término de la instrucción $instructionInd tiene un formato inválido.", [], 400);
- }
- $endHourArr = explode(':', $instructionEndArr[1]);
- $endHourInt = intval($endHourArr[0]);
- if ($instructionEndArr[2] == 'PM' && $endHourInt < 12) {
- $endHourInt = $endHourInt + 12;
- }
- $endOrigin = $instruction['FIN'];
- $endHourStr = $endHourInt < 10 ? "0$endHourInt" : "$endHourInt";
- $instructionEndStr = "$endHourStr:$endHourArr[1]:00";
- $instruction['FIN'] = "$instructionEndArr[0] $instructionEndStr";
- if (isset($form['end_hour'])) {
- $dateTimeEnd = new Carbon($ftap);
- $instructionEndDateTime = new Carbon($instruction['FIN']);
- if ($instructionEndDateTime->gt($dateTimeEnd)) {
- return $this->responseController->makeResponse(true, "La fecha de término de la instrucción $instructionInd no puede ser mayor a la fecha de término del activador.", [], 400);
- }
- }
- $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']);
- $instruction['INICIO'] = $startOrigin;
- $instruction['FIN'] = $endOrigin;
- $instructionsArr[$key] = $instruction;
- }
- $inin = json_encode($instructionsArr);
- $oppr = json_encode($staff);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $fiap = $dateTimeStart->toDateTimeString();
- $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'], 'GMPR', 'OR', $tempFile, $idUser);
- if (!$finalFile) {
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- } else {
- $attachedArrFn[] = $finalFile[1];
- }
- }
- }
- }
- $done = json_encode($attachedArrFn);
- if ($form['exists'] == 'S') {
- $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('S002V01TOTPR')->where([
- ['OTPR_IDOT', '=', $idOrder],
- ['OTPR_NULI', '=', $form['linea']]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404);
- }
- DB::table('S002V01TOTPR')->where([
- ['OTPR_IDOT', '=', $idOrder],
- ['OTPR_NULI', '=', $form['linea']]
- ])->update([
- 'OTPR_DEIN' => $form['description'],
- 'OTPR_ININ' => $inin,
- 'OTPR_EQIN' => $equipmentCode,
- 'OTPR_FIAP' => $fiap,
- 'OTPR_FTAP' => $ftap,
- 'OTPR_TIIN' => $form['inm_time'],
- 'OTPR_OPPR' => $oppr,
- 'OTPR_DTIN' => $form['total_time'],
- 'OTPR_RHRE' => $rhre,
- 'OTPR_DONE' => $done,
- 'OTPR_ACAS' => $idActivator,
- 'OTPR_CLAS' => $form['clasification'],
- 'OTPR_ESTA' => 'R',
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr,
- ]);
- } else {
- $idOrder = DB::table('S002V01TOTPR')->insertGetId([
- 'OTPR_NULI' => $form['linea'],
- 'OTPR_DEIN' => $form['description'],
- 'OTPR_ININ' => $inin,
- 'OTPR_EQIN' => $equipmentCode,
- 'OTPR_FIAP' => $fiap,
- 'OTPR_FTAP' => $ftap,
- 'OTPR_TIIN' => $form['inm_time'],
- 'OTPR_OPPR' => $oppr,
- 'OTPR_DTIN' => $form['total_time'],
- 'OTPR_RHRE' => $rhre,
- 'OTPR_DONE' => $done,
- 'OTPR_ACAS' => $idActivator,
- 'OTPR_CLAS' => $form['clasification'],
- 'OTPR_ESTA' => 'R',
- 'OTPR_USRE' => $idUser,
- 'OTPR_FERE' => $nowStr,
- ]);
- }
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P01ROTR',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo #$idOrder.",
- $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);
- }
- $workOrders = DB::table('S002V01TOTPR')->select([
- 'OTPR_IDOT AS IDORDEN',
- 'OTPR_EQIN AS EQUIPO',
- 'OTPR_FIAP AS FECHAINICIO',
- 'OTPR_FTAP AS FECHAFINAL',
- 'OTPR_ACAS AS ACTIVADOR',
- 'ACTI_TIAC AS TIPOACTIVADOR',
- 'ACTI_PRIO AS PRIORIDAD',
- 'OTPR_ESTA AS ESTATUS'
- ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')
- ->where('OTPR_NULI', '=', $line)
- ->orderBy('OTPR_IDOT', 'desc')->get()->all();
- foreach ($workOrders as $key => $order) {
- $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
- $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO);
- $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR);
- if (!is_null($order->PRIORIDAD)) {
- $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
- }
- if ($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null;
- if ($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null;
- $workOrders[$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,
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P01HOTP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo registradas.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $workOrders);
- }
- 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 no está encriptado correctamente.', [], 400);
- }
- $workOrder = DB::table('S002V01TOTPR')->select([
- 'OTPR_IDOT AS IDORDEN',
- 'OTPR_DEIN AS DESCRIPCION',
- 'OTPR_ININ AS INSTRUCCIONES',
- 'OTPR_EQIN AS EQUIPAMIENTO',
- 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
- 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
- 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
- 'OTPR_FIAP AS FECHAINICIO',
- 'OTPR_FTAP AS FECHAFINAL',
- 'OTPR_SEAN AS ANALISIS',
- 'OTPR_TIIN AS TIEMPOINMOESTI',
- 'OTPR_CLAS AS CLASIFICACION',
- 'OTPR_OPPR AS OPERARIOS',
- 'OTPR_DTIN AS DURACIONTOTAL',
- 'OTPR_RHRE AS RECURSOS',
- 'OTPR_DONE AS DOCUMENTOS',
- 'OTPR_RECO AS CONTRATOS',
- 'OTPR_ACAS AS ACTIVADOR',
- 'ACTI_TIAC AS TIPOACTIVADOR',
- 'ACTI_PRIO AS PRIORIDAD',
- 'OTPR_ESTA AS ESTADO',
- 'OTPR_USRE AS USUARIOREGISTRA',
- 'OTPR_FERE AS FECHAREGISTRO',
- 'OTPR_USMO AS USUARIOMODIFICA',
- 'OTPR_FEMO AS FECHAMODIFICACION',
- ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')
- ->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
- ['OTPR_IDOT', '=', $idOrder],
- ['OTPR_NULI', '=', $line],
- ])->first();
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden de trabajo consultada no existe.', [], 404);
- }
- $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN);
- $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO);
- $workOrder->ACTIVADOR = $this->encryptionController->encrypt($workOrder->ACTIVADOR);
- if (!is_null($workOrder->ID_EQUIPAMIENTO)) {
- $workOrder->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->ID_EQUIPAMIENTO);
- }
- if (!is_null($workOrder->PRIORIDAD)) {
- $workOrder->PRIORIDAD = $this->encryptionController->encrypt($workOrder->PRIORIDAD);
- }
- $workOrder->FECHAFINAL = $workOrder->FECHAFINAL == '0001-01-01 00:00:00' ? null : $workOrder->FECHAFINAL;
- $workOrder->FECHAINICIO = $workOrder->FECHAINICIO == '0001-01-01 00:00:00' ? null : $workOrder->FECHAINICIO;
- $instructionsArr = json_decode($workOrder->INSTRUCCIONES, true);
- foreach ($instructionsArr as $key => $instruction) {
- $instruction['ID'] = $this->encryptionController->encrypt($instruction['ID']);
- $instructionsArr[$key] = $instruction;
- }
- $workOrder->INSTRUCCIONES = json_encode($instructionsArr);
- $staffArr = json_decode($workOrder->OPERARIOS, 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;
- }
- $workOrder->OPERARIOS = json_encode($staffArr);
- $resources = json_decode($workOrder->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;
- }
- $workOrder->RECURSOS = json_encode($resources);
- $documentsArr = json_decode($workOrder->DOCUMENTOS, 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'
- ];
- }
- $workOrder->DOCUMENTOS = json_encode($documentsFn);
- if (!is_null($workOrder->ANALISIS)) {
- $analysisArr = json_decode($workOrder->ANALISIS, true);
- $teamsConf = $analysisArr['teamsConf'];
- foreach ($teamsConf as $key => $val) {
- $idEnc = $this->encryptionController->encrypt($val['ID']);
- $val['ID'] = $idEnc;
- $teamsConf[$key] = $val;
- }
- $analysisArr['teamsConf'] = $teamsConf;
- $workOrder->ANALISIS = json_encode($analysisArr);
- }
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $workOrder->USUARIOREGISTRA],
- ])->first();
- $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $workOrder->USUARIOREGISTRA = $nameReg . " (" . $workOrder->USUARIOREGISTRA . ")";
- if (!is_null($workOrder->USUARIOMODIFICA)) {
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $workOrder->USUARIOMODIFICA],
- ])->first();
- $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
- $workOrder->USUARIOMODIFICA = $nameMod . " (" . $workOrder->USUARIOMODIFICA . ")";
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P04COIN',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la orden de trabajo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $workOrder);
- }
- public function executePreventiveWorkOrder(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'configuration' => 'required|string',
- 'execution_date' => 'required|date'
- ]);
- 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 seleccionada no fue encriptado correctamente.', [], 400);
- }
- $workOrder = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- } else if ($workOrder->OTPR_ESTA == 'Eliminado') {
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
- }
- $configurationStr = $this->encryptionController->decrypt($form['configuration']);
- if (!$configurationStr) {
- return $this->responseController->makeResponse(true, 'La cadena de configuración no fue encriptada correctamente.', [], 400);
- }
- $configurationArr = json_decode($configurationStr, true);
- $staffArr = [];
- foreach ($configurationArr as $key => $value) {
- $specialty = DB::table('S002V01TGEES')->where([
- ['GEES_NULI', '=', $form['linea']],
- ['GEES_COES', '=', $key]
- ])->first();
- if (!is_null($specialty)) {
- $specialtyEmployees = [];
- foreach ($value as $key0 => $value0) {
- $idEmployeeDec = $this->encryptionController->decrypt($value0);
- if (!$idEmployeeDec) {
- return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key no fue encriptado correctamente.", [], 400);
- }
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_IDPE', '=', $idEmployeeDec]
- ])->first();
- if (is_null($employee)) {
- return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key no existe.", [], 404);
- } else if ($employee->PERS_ESTA == 'Eliminado') {
- return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key está eliminado.", [], 404);
- }
- $specialtyEmployees[] = $idEmployeeDec;
- }
- $staffArr[$key] = $specialtyEmployees;
- }
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $staffStr = json_encode($staffArr);
- $validExecutionDate = $this->functionsController->validateDate($form['execution_date']);
- if (!$validExecutionDate) {
- return $this->responseController->makeResponse(true, 'La fecha de ejecución tiene un formato inválido.', [], 400);
- }
- $execDate = new Carbon($form['execution_date']);
- $fecIni = new Carbon($workOrder->OTPR_FIAP);
- if ($fecIni->gt($execDate)) {
- $tmp = $fecIni->toDateTimeString() . '|' . $execDate->toDateTimeString();
- return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.' . $tmp, [], 400);
- }
- $execDateStr = $execDate->toDateString();
- $execution = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $form['linea']],
- ['BEOT_IDOT', '=', $form['id_order']],
- ['BEOT_FEPR', '=', $execDateStr]
- ])->first();
- if (!is_null($execution)) {
- $estatus = $execution->BEOT_TIAC;
- if ($estatus == 'Ejecucion') {
- return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya fue realizada.", [], 401);
- } else if ($estatus == 'Cancelacion') {
- return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr fue cancelada.", [], 401);
- } else if ($estatus == 'Finalizado') {
- return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha finalizado.", [], 401);
- }
- }
- DB::table('S002V01TBEOT')->insert([
- 'BEOT_NULI' => $form['linea'],
- 'BEOT_IDOT' => $idOrder,
- 'BEOT_FEPR' => $execDateStr,
- 'BEOT_TIAC' => 'Ejecucion',
- 'BEOT_OPER' => $staffStr,
- 'BEOT_FEEJ' => $nowStr,
- 'BEOT_USEJ' => $idUser,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F02EMOT',
- '-',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") ejecutó la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function cancelWorkOrder(Request $request)
- {
- //PENDIENTE REVISAR
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|integer',
- 'execution_date' => 'required|date',
- 'observations' => '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);
- }
- $workOrder = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $form['id_order']]
- ])->first();
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
- }
- $execDate = new Carbon($form['execution_date']);
- $fecIni = new Carbon($workOrder->OTPR_FIAP);
- if ($fecIni->gt($execDate)) {
- return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.', [], 400);
- }
- $execDateStr = $execDate->toDateString();
- $execution = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $form['linea']],
- ['BEOT_IDOT', '=', $form['id_order']],
- ['BEOT_FEPR', '=', $execDateStr]
- ])->first();
- if (!is_null($execution)) {
- $estatus = $execution->BEOT_TIAC;
- if ($estatus == 'Ejecucion') {
- return $this->responseController->makeResponse(true, "La programación de la orden para la fecha $execDateStr no se puede cancelar porque ya se ha iniciado su ejecución.", [], 401);
- } else if ($estatus == 'Finalizado') {
- return $this->responseController->makeResponse(true, "La programación de la orden para la fecha $execDateStr no se puede cancelar porque ya se ha finalizado.", [], 401);
- } else if ($estatus == 'Cancelacion') {
- return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha sido cancelada.", [], 401);
- }
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TBEOT')->insert([
- 'BEOT_NULI' => $form['linea'],
- 'BEOT_IDOT' => $form['id_order'],
- 'BEOT_FEPR' => $execDateStr,
- 'BEOT_TIAC' => 'Cancelacion',
- 'BEOT_OBSE' => $form['observations'],
- 'BEOT_FEEJ' => $nowStr,
- 'BEOT_USEJ' => $idUser,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F02EMOT',
- '-',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") canceló la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.",
- $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 solicitada no fue encriptado correctamente.', [], 400);
- }
- $workOrder = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
- } else if ($workOrder->OTPR_ESTA == 'E') {
- return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada', [], 401);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTPR')->where([
- ['OTPR_IDOT', '=', $idOrder],
- ['OTPR_NULI', '=', $form['linea']]
- ])->update([
- 'OTPR_ESTA' => 'E',
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F04EOTP',
- '-',
- 'Eliminación',
- "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo #$form[id_order].",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function updateWorkOrder(Request $request)
- {
- //PENDIENTE ELIMINAR
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|integer',
- 'title' => 'required|string',
- 'repeat' => 'required|json',
- 'start_date' => 'required|date',
- 'start_hour' => 'required|string',
- 'inm_time' => 'required|numeric',
- 'description' => 'required|string|max:100',
- 'clasification' => 'required|string|max:50',
- 'priority' => 'required|string|in:1,2,3',
- 'equipment' => 'required|string',
- 'analisis' => 'required|string',
- 'specialties' => '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);
- }
- $workOrder = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $form['id_order']]
- ])->first();
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
- }
- $repeArr = json_decode($form['repeat'], true);
- if (empty($repeArr)) {
- return $this->responseController->makeResponse(true, 'El JSON de repetición tiene un formato inválido.', [], 400);
- } else if (!array_key_exists('type', $repeArr)) {
- return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de repetición.', [], 400);
- } else if (!array_key_exists('config', $repeArr)) {
- return $this->responseController->makeResponse(true, 'El campo config no fue enviado en el JSON de repetición.', [], 400);
- }
- $hourArr = explode(' ', $form['start_hour']);
- $timeArr = '';
- if (count($hourArr) < 2) {
- return $this->responseController->makeResponse(true, 'La hora de inicio tiene un formato inválido.', [], 400);
- } else if ($hourArr[1] == 'PM') {
- $hour = explode(':', $hourArr[0]);
- $h = intval($hour[0]);
- if ($h != 12) {
- $h = $h + 12;
- }
- $hourStr = "$h:$hour[1]:00";
- $timeArr .= " $hourStr";
- } else if ($hourArr[1] == 'AM') {
- $hour = explode(':', $hourArr[0]);
- $h = intval($hour[0]);
- $hStr = $h < 10 ? "0$h" : "$h";
- $hStr .= ":$hour[1]:00";
- $timeArr .= " $hStr";
- } else {
- return $this->responseController->makeResponse(true, 'No se pudo determinar el periodo del horario.', [], 400);
- }
- $specialtiesArr = json_decode($form['specialties'], true);
- if (empty($specialtiesArr)) {
- return $this->responseController->makeResponse(true, 'El JSON de especialidades tiene un formato inválido.', [], 400);
- }
- foreach ($specialtiesArr as $specialty) {
- if (!array_key_exists('specialty', $specialty)) {
- return $this->responseController->makeResponse(true, 'El campo specialty no fue enviado en el JSON de especialidad.', [], 400);
- } else if (!array_key_exists('type', $specialty)) {
- return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de especialidad.', [], 400);
- } else if (!array_key_exists('staff', $specialty)) {
- return $this->responseController->makeResponse(true, 'El campo staff no fue enviado en el JSON de especialidad.', [], 400);
- }
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $documents = isset($form['attached']) ? $form['attached'] : null;
- DB::table('S002V01TOTPR')->where([
- ['OTPR_IDOT', '=', $form['id_order']],
- ['OTPR_NULI', '=', $form['linea']],
- ])->update([
- 'OTPR_TIOR' => $form['title'],
- 'OTPR_REPE' => $form['repeat'],
- 'OTPR_FIIN' => $form['start_date'],
- 'OTPR_HIIN' => $timeArr,
- 'OTPR_TIES' => $form['inm_time'],
- 'OTPR_DEIN' => $form['description'],
- 'OTPR_ANIN' => $form['analisis'],
- 'OTPR_CEIN' => $form['equipment'],
- 'OTPR_PERE' => $form['specialties'],
- 'OTPR_CLAS' => $form['clasification'],
- 'OTPR_PRIO' => $form['priority'],
- 'OTPR_DONE' => $documents,
- 'OTPR_USRE' => $idUser,
- 'OTPR_FERE' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P01ROTR',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo $form[title] ($form[id_order]).",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function geStartedtWorkOrders($idUser, $line)
- {
- //PENDIENTE REVISAR
- 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);
- }
- $startedWorkOrders = DB::table('S002V01TBEOT')->select([
- 'BEOT_IDRE AS IDREGISTRO',
- 'BEOT_IDOT AS IDORDEN',
- 'BEOT_FEPR AS FECHAPROGRAMA',
- 'BEOT_FEEJ AS FECHAEJECUCION',
- 'BEOT_USEJ AS USUARIOEJECUCION',
- 'BEOT_TIAC AS ESTADO',
- 'OTPR_TIOR AS TITULOORDEN',
- 'OTPR_HIIN AS HORAPROGRAMA',
- 'OTPR_TIES AS TIEMPOESTIMADO',
- 'OTPR_PRIO AS PRIORIDAD',
- ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')->where([
- ['BEOT_NULI', '=', $line],
- ])->get()->all();
- foreach ($startedWorkOrders as $workOrder) {
- $usrEje = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $workOrder->USUARIOEJECUCION]
- ])->first();
- $nameEje = $this->functionsController->joinName($usrEje->USUA_NOMB, $usrEje->USUA_APPA, $usrEje->USUA_APMA);
- $workOrder->USUARIOEJECUCION = $nameEje . " (" . $workOrder->USUARIOEJECUCION . ")";
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F05BEOT',
- 'S002V01P01HOEJ',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo en ejecución.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $startedWorkOrders);
- }
- public function endOrderExecution(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|integer',
- 'id_reg' => 'required|integer',
- 'observations' => '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);
- }
- $workOrder = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $form['id_order']]
- ])->first();
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
- }
- $register = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $form['linea']],
- ['BEOT_IDRE', '=', $form['id_reg']],
- ['BEOT_IDOT', '=', $form['id_order']]
- ])->first();
- if (is_null($register)) {
- return $this->responseController->makeResponse(true, 'El registro solicitado no existe', [], 404);
- } else if ($register->BEOT_TIAC == 'Cancelacion') {
- return $this->responseController->makeResponse(true, 'El registro solicitado fue cancelado', [], 401);
- } else if ($register->BEOT_TIAC == 'Finalizado') {
- return $this->responseController->makeResponse(true, 'El registro solicitado ya fue finalizado', [], 401);
- }
- $now = $this->functionsController->now();
- $executionDate = new Carbon($register->BEOT_FEEJ);
- $diff = $now->diffInMilliseconds($executionDate); //Milisegundos
- $diff = $diff / 1000; //Segundos
- $diff = $diff / 60; //Minutos
- $diff = $diff / 60; //Horas
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $form['linea']],
- ['BEOT_IDRE', '=', $form['id_reg']],
- ['BEOT_IDOT', '=', $form['id_order']]
- ])->update([
- "BEOT_TIAC" => 'Finalizado',
- "BEOT_DTEJ" => $diff,
- "BEOT_OBSE" => $form['observations'],
- "BEOT_FEFI" => $nowStr,
- "BEOT_USFI" => $idUser,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F05SEOR',
- '-',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") finalizó la ejecución del día " . $register->BEOT_FEPR . " de la orden #$form[id_order].",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getExecRegister($date, $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 orden relacionada no fue encriptado correctamente.', [], 400);
- }
- $dateArr = explode('|', $date);
- $workOrder = null;
- if (count($dateArr) == 2) {
- if ($dateArr[1] == 'O') {
- $workOrder = DB::table('S002V01TOTPR')->select(
- 'OTPR_IDOT AS IDORDEN',
- 'OTPR_DEIN AS DESCRIPCION',
- DB::raw("CONCAT(
- OTPR_EQIN, ' - ',
- EQUI_TIPO, ' - ',
- EQUI_MODE, ' (',
- EQUI_IDEQ, ')'
- ) AS EQUIPAMIENTO"),
- 'OTPR_FIAP AS FECHAINICIO',
- DB::raw("'Programada' AS ESTADODEEJECUCION"),
- DB::raw("'-' AS IDREG"),
- DB::raw("NULL AS OBSERVACIONES"),
- DB::raw("NULL AS OPERARIOS"),
- )->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idRegister],
- ])->first();
- } else {
- $validDate = $this->functionsController->validDate($dateArr[0]);
- if (!$validDate) {
- return $this->responseController->makeResponse(true, 'La fecha de ejecución enviada tiene un formato inválido.', [], 400);
- }
- $workOrder = DB::table('S002V01TBEOT')->select([
- 'BEOT_IDOT AS IDORDEN',
- 'OTPR_DEIN AS DESCRIPCION',
- DB::raw("CONCAT(
- OTPR_EQIN, ' - ',
- EQUI_TIPO, ' - ',
- EQUI_MODE, ' (',
- EQUI_IDEQ, ')'
- ) AS EQUIPAMIENTO"),
- 'OTPR_FIAP AS FECHAINICIO',
- 'BEOT_TIAC AS ESTADODEEJECUCION',
- 'BEOT_IDRE AS IDREG',
- 'BEOT_OBSE AS OBSERVACIONES',
- 'BEOT_OPER AS OPERARIOS'
- ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')
- ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $idRegister],
- ['BEOT_FEPR', '=', $dateArr[0]],
- ])->first();
- }
- } else {
- $workOrder = DB::table('S002V01TBEOT')->select([
- 'BEOT_IDOT AS IDORDEN',
- 'OTPR_DEIN AS DESCRIPCION',
- DB::raw("CONCAT(
- OTPR_EQIN, ' - ',
- EQUI_TIPO, ' - ',
- EQUI_MODE, ' (',
- EQUI_IDEQ, ')'
- ) AS EQUIPAMIENTO"),
- 'OTPR_FIAP AS FECHAINICIO',
- 'BEOT_TIAC AS ESTADODEEJECUCION',
- 'BEOT_IDRE AS IDREG',
- 'BEOT_OBSE AS OBSERVACIONES',
- 'BEOT_OPER AS OPERARIOS'
- ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')
- ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDRE', '=', $idRegister],
- ])->first();
- }
- if (is_null($workOrder)) {
- return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404);
- }
- $idOrder = $workOrder->IDORDEN;
- $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN);
- $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO);
- $workOrder->IDREG = $this->encryptionController->encrypt($workOrder->IDREG);
- if (!is_null($workOrder->OPERARIOS)) {
- $staffArr = json_decode($workOrder->OPERARIOS);
- $staffArrFn = [];
- foreach ($staffArr as $key => $val) {
- $specialtyObj = DB::table('S002V01TGEES')->where([
- ['GEES_NULI', '=', $line],
- ['GEES_COES', '=', $key]
- ])->first();
- $specialtyConf = [];
- if (!is_null($specialtyObj)) {
- $specialtyConf['CODIGO_ESPECIALIDAD'] = $this->encryptionController->encrypt($specialtyObj->GEES_COES);
- $specialtyConf['NOMBRE_ESPECIALIDAD'] = $specialtyObj->GEES_NOES;
- $staff = [];
- foreach ($val as $val0) {
- $employee = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPE', '=', $val0]
- ])->first();
- $employeeObj = [
- 'ID_EMPLEADO' => $this->encryptionController->encrypt($employee->PERS_IDPE),
- 'ID_USUARIO' => $this->encryptionController->encrypt($employee->USUA_IDUS),
- 'NOMBRE_EMPLEADO' => $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA),
- 'TIPO_EMPLEADO' => $employee->PERS_TICO
- ];
- $staff[] = $employeeObj;
- }
- $specialtyConf['OPERARIOS'] = $staff;
- }
- $staffArrFn[] = $specialtyConf;
- }
- $workOrder->OPERARIOS = $staffArrFn;
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F08VCPR',
- '-',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó el estado de la ejecución de la orden #" . $idOrder . " para la fecha $date.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $workOrder);
- }
- public function copyWorkOrder(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'equipment' => '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 que desea copiar no fue encriptado correctamente.', [], 400);
- }
- $workOrder = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($workOrder)) {
- 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 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 seleccionado no existe.', [], 404);
- } else if ($equipmentCode == $workOrder->OTPR_EQIN) {
- return $this->responseController->makeResponse(true, 'El equipo seleccionado es igual al de la orden copiada.', [], 400);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $idOrderNew = DB::table('S002V01TOTPR')->insertGetId([
- "OTPR_NULI" => $form['linea'],
- "OTPR_DEIN" => $workOrder->OTPR_DEIN,
- "OTPR_ININ" => $workOrder->OTPR_ININ,
- "OTPR_EQIN" => $equipmentCode,
- "OTPR_FIAP" => $workOrder->OTPR_FIAP,
- "OTPR_FTAP" => $workOrder->OTPR_FTAP,
- "OTPR_SEAN" => $workOrder->OTPR_SEAN,
- "OTPR_TIIN" => $workOrder->OTPR_TIIN,
- "OTPR_OPPR" => $workOrder->OTPR_OPPR,
- "OTPR_DTIN" => $workOrder->OTPR_DTIN,
- "OTPR_RHRE" => $workOrder->OTPR_RHRE,
- "OTPR_DONE" => '[]',
- "OTPR_RECO" => $workOrder->OTPR_RECO,
- "OTPR_ACAS" => $workOrder->OTPR_ACAS,
- "OTPR_CLAS" => $workOrder->OTPR_CLAS,
- "OTPR_ESTA" => 'R',
- "OTPR_USRE" => $idUser,
- "OTPR_FERE" => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F06COVE',
- '-',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") copió la orden #$idOrder para el equipamiento $equipmentCode dentro de la orden #$idOrderNew.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function savePresetWorkOrder(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'exists' => 'required|string|in:S,N',
- 'id_order' => 'required_if:exists,=,S|string',
- 'description' => 'required|string',
- 'instructions' => 'required|string',
- 'start_date' => 'required|string',
- 'start_hour' => 'required|string',
- 'end_date' => 'required|string',
- 'end_hour' => 'required|string',
- 'equipment' => 'required|string',
- 'inm_time' => 'required|string',
- 'total_time' => 'required|string',
- 'staff' => 'required|string',
- 'attached' => 'required|string',
- 'activator_type' => 'required|string',
- 'activator' => 'required|string',
- 'clasification' => 'required|string|max:100',
- 'resources' => '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);
- }
- $acas = '0';
- if ($form['activator'] != '-') {
- $idActivator = $this->encryptionController->decrypt($form['activator']);
- if (!$idActivator) {
- return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400);
- }
- $activator = DB::table('S002V01TACTI')->where([
- ['ACTI_NULI', '=', $form['linea']],
- ['ACTI_IDAC', '=', $idActivator]
- ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first();
- if (is_null($activator)) {
- return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
- }
- $acas = $idActivator;
- }
- $rhre = '[]';
- if ($form['resources'] != '[]') {
- $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;
- }
- $rhre = json_encode($resources);
- }
- $startDateTime = '0001-01-01 00:00:00';
- if ($form['start_date'] != '-' && $form['start_hour'] != '-') {
- $startDateTime = "$form[start_date] $form[start_hour]";
- $validStartDateTime = $this->functionsController->validateDate($startDateTime);
- if (!$validStartDateTime) {
- return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400);
- }
- }
- $endDateTime = '0001-01-01 00:00:00';
- if ($form['end_date'] != '-' && $form['end_hour'] != '-') {
- $endDateTime = "$form[end_date] $form[end_hour]";
- $validEndDateTime = $this->functionsController->validateDate($endDateTime);
- if (!$validEndDateTime) {
- return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400);
- }
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $dein = $form['description'];
- $eqin = '-';
- if ($form['equipment'] != '-') {
- $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 equipaiento seleccionado no existe.', [], 404);
- }
- $eqin = $equipmentCode;
- }
- $tiin = $form['inm_time'] == '-' ? 0 : floatval($form['inm_time']);
- $dtin = $form['total_time'] == '-' ? 0 : floatval($form['total_time']);
- $staffArr = json_decode($form['staff'], true);
- $staff = [];
- if ($form['staff'] != '-' && !empty($staffArr)) {
- $staffArr = json_decode($form['staff'], true);
- 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']
- ];
- }
- }
- $oppr = json_encode($staff);
- $clas = $form['clasification'];
- $inin = '[]';
- if ($form['instructions'] != '-') {
- $instructions = json_decode($form['instructions'], true);
- foreach ($instructions as $key => $instruction) {
- $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']);
- $instructions[$key] = $instruction;
- }
- $inin = json_encode($instructions);
- }
- $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'], 'GMPR', 'OR', $tempFile, $idUser);
- if (!$finalFile) {
- return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
- } else {
- $attachedArrFn[] = $finalFile[1];
- }
- }
- }
- }
- $done = json_encode($attachedArrFn);
- if ($form['exists'] == 'N') {
- $idOrder = DB::table('S002V01TOTPR')->insertGetId([
- 'OTPR_NULI' => $form['linea'],
- 'OTPR_DEIN' => $dein,
- 'OTPR_ININ' => $inin,
- 'OTPR_EQIN' => $eqin,
- 'OTPR_FIAP' => $startDateTime,
- 'OTPR_FTAP' => $endDateTime,
- 'OTPR_TIIN' => $tiin,
- 'OTPR_OPPR' => $oppr,
- 'OTPR_DTIN' => $dtin,
- 'OTPR_RHRE' => $rhre,
- 'OTPR_DONE' => $done,
- 'OTPR_ACAS' => $acas,
- 'OTPR_CLAS' => $clas,
- 'OTPR_ESTA' => 'B',
- 'OTPR_USRE' => $idUser,
- 'OTPR_FERE' => $nowStr,
- ]);
- } else {
- $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('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404);
- }
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder]
- ])->update([
- 'OTPR_DEIN' => $dein,
- 'OTPR_ININ' => $inin,
- 'OTPR_EQIN' => $eqin,
- 'OTPR_FIAP' => $startDateTime,
- 'OTPR_FTAP' => $endDateTime,
- 'OTPR_TIIN' => $tiin,
- 'OTPR_OPPR' => $oppr,
- 'OTPR_DTIN' => $dtin,
- 'OTPR_RHRE' => $rhre,
- 'OTPR_DONE' => $done,
- 'OTPR_ACAS' => $acas,
- 'OTPR_CLAS' => $clas,
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr,
- ]);
- }
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P02ROTP',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró un borrador para la orden de trabajo #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeresponse(false, "EXITO");
- }
- public function getActiveOrders($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);
- }
- $activeWorkOrders = DB::table('S002V01TOTPR')->select([
- 'OTPR_IDOT AS IDORDEN',
- 'OTPR_EQIN AS EQUIPAMIENTO',
- 'OTPR_FIAP AS FECHAINICIO',
- 'OTPR_FTAP AS FECHATERMINO',
- 'OTPR_TIIN AS TIEMPOESTIMADO',
- 'OTPR_DTIN AS TIEMPOTOTAL',
- 'OTPR_CLAS AS CLASIFICACION',
- 'OTPR_ACAS AS ACTIVADOR',
- 'ACTI_PRIO AS PRIORIDAD',
- 'ACTI_TIAC AS TIPOACTIVADOR'
- ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_ESTA', '=', 'A']
- ])->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,
- 'S002V01M10GMPR',
- 'S002V01F01ACMA',
- 'S002V01P01OTAC',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento preventivo activas.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $activeWorkOrders);
- }
- public function getPreventiveCalendar($fecIni, $fecFin, $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);
- }
- if (!$this->functionsController->validDate($fecIni)) {
- return $this->responseController->makeResponse(true, 'La fecha de inicio es inválida.', [], 400);
- }
- if (!$this->functionsController->validDate($fecFin)) {
- return $this->responseController->makeResponse(true, 'La fecha final es inválida.', [], 400);
- }
- $fecIniObj = new Carbon($fecIni . ' 00:00:00');
- $fecFinObj = new Carbon($fecFin . ' 23:59:59');
- $workOrders = DB::table('S002V01TOTPR')->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_ESTA', '=', 'A'],
- ])->get()->all();
- $programmedWorkOrders = [];
- foreach ($workOrders as $order) {
- $orderStart = new Carbon($order->OTPR_FIAP);
- if ($order->ACTI_TIAC == 'Calendario' || $order->ACTI_TIAC == 'Sintoma') {
- $repeatConfig = json_decode($order->ACTI_COAC, true);
- switch ($repeatConfig['repeat']) {
- case 'AN':
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addYear();
- }
- break;
- case 'ME':
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addMonth();
- }
- break;
- case 'SE':
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addWeek();
- }
- break;
- case 'TD':
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addDay();
- }
- break;
- case 'NR':
- if ($orderStart->gte($fecIniObj) && $orderStart->lte($fecFinObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- break;
- case 'PE':
- $customRepeat = json_decode($repeatConfig['customRepeat'], true);
- $repeatEvery = explode('|', $customRepeat['repeatEvery']);
- switch ($repeatEvery[1]) {
- case '0':
- //Repeticiones por día
- $days = intval($repeatEvery[0]);
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addDays($days);
- }
- break;
- case '1':
- //Repeticiones por semana
- $weeks = intval($repeatEvery[0]);
- $orderStartAux = new Carbon($orderStart->toDateTimeString());
- $repeatOn = $customRepeat['repeatOn'];
- while ($orderStart->lte($fecFinObj)) {
- $dayInd = $orderStartAux->dayOfWeek;
- for ($i = $dayInd; $i < 7; $i++) {
- $dayName = strtolower($orderStartAux->dayName);
- $dayKey = substr($dayName, 0, 3);
- $shouldRepeat = $repeatOn[$dayKey];
- if ($shouldRepeat && $orderStartAux->lte($fecFinObj) && $orderStartAux->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStartAux->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStartAux->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStartAux->addDay();
- }
- $orderStart->addWeeks($weeks);
- }
- break;
- case '2':
- //Repeticiones por mes
- $months = intval($repeatEvery[0]);
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addMonths($months);
- }
- break;
- case '3':
- //Repeticiones por año
- $years = intval($repeatEvery[0]);
- while ($orderStart->lte($fecFinObj)) {
- if ($orderStart->gte($fecIniObj)) {
- $reg = DB::table('S002V01TBEOT')->where([
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $order->OTPR_IDOT],
- ['BEOT_FEPR', '=', $orderStart->toDateString()]
- ])->first();
- $programmedWorkOrders[] = [
- "IDORDEN" => $order->OTPR_IDOT,
- "EVENTCOLOR" => $repeatConfig['color'],
- "DATE" => $orderStart->toDateString(),
- "TYPE" => $order->ACTI_TIAC,
- "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
- ];
- }
- $orderStart->addYears($years);
- }
- break;
- }
- break;
- }
- }
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F08VCPR',
- '-',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los eventos programados entre las fechas $fecIni y $fecFin.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $programmedWorkOrders);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function newUnprogrammedOrder(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'equipment' => 'required|string',
- 'resources' => 'required|json',
- 'comments' => 'required|string|min:35',
- 'staff' => '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);
- }
- $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 seleccionado no existe.', [], 404);
- }
- $staffArr = json_decode($form['staff'], true);
- if (empty($staffArr)) {
- return $this->responseController->makeResponse(true, 'El JSON de personal está vacío.', [], 400);
- }
- $staff = [];
- foreach ($staffArr as $val) {
- if (!array_key_exists('TYPE', $val) && !array_key_exists('ID', $val)) {
- return $this->responseController->makeResponse(true, "El arreglo del personal no tiene un formato válido.", [], 400);
- }
- $typeStr = '';
- if ($val['TYPE'] == 'EQ') {
- $typeStr = 'equipo de trabajo';
- } else if ($val['TYPE'] == 'SU') {
- $typeStr = 'subcontratista';
- } else if ($val['TYPE'] == 'EM') {
- $typeStr = 'empleado';
- }
- $key = $this->encryptionController->decrypt($val['ID']);
- if (!$key) {
- return $this->responseController->makeResponse(true, "El ID del $typeStr no fue encriptado correctamente.", [], 400);
- }
- $res = null;
- if ($val['TYPE'] == 'EQ') {
- $res = DB::table('S002V01TEQMA')->where([
- ['EQMA_NULI', '=', $form['linea']],
- ['EQMA_IDEQ', '=', $key],
- ])->first();
- } else if ($val['TYPE'] == 'SU') {
- $res = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $form['linea']],
- ['PESU_IDPS', '=', $key],
- ])->first();
- } else if ($val['TYPE'] == 'EM') {
- $res = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_IDPE', '=', $key],
- ])->first();
- }
- if (is_null($res)) {
- return $this->responseController->makeResponse(true, "El $typeStr no está registrado.", [], 400);
- }
- $staff[] = [
- 'ID' => $key,
- 'TYPE' => $val['TYPE']
- ];
- }
- $resources = json_decode($form['resources'], true);
- if (empty($resources)) {
- return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
- }
- $commentsArr = [
- 'CI' => $form['comments']
- ];
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryStr = json_encode([
- [
- 'FECHA' => $nowStr,
- 'ESTADO' => 'PE',
- 'USUARIO' => $idUser,
- ]
- ]);
- $commentsStr = json_encode($commentsArr);
- $staffStr = json_encode($staff);
- $idVisit = DB::table('S002V01TRVTN')->insertGetId([
- 'RVTN_NULI' => $form['linea'],
- 'RVTN_EQRE' => $equipmentCode,
- 'RVTN_DEIN' => $form['description'],
- 'RVTN_TIAC' => 'M',
- 'RVTN_PEIN' => $staffStr,
- 'RVTN_MAUT' => $form['resources'],
- 'RVTN_ESTA' => 'PE',
- 'RVTN_HIES' => $statusHistoryStr,
- 'RVTN_COME' => $commentsStr,
- 'RVTN_USRE' => $idUser,
- 'RVTN_FERE' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró la visita no programada #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getUnprogrammedVisits($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);
- }
- $visits = DB::table('S002V01TRVTN')->select([
- 'RVTN_IDVI AS IDVISITA',
- 'RVTN_EQRE AS EQUIPAMIENTO',
- 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
- 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
- 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
- 'RVTN_ESTA AS ESTADO',
- 'RVTN_USRE AS USRREG',
- 'RVTN_FERE AS FECREG',
- 'RVTN_FEMO AS FECMOD',
- 'RVTN_PRIO AS PRIORIDAD',
- 'RVTN_DEIN AS DESCRIPCION',
- 'RVTN_TIAC AS TIPO_ACTIVACION',
- 'usrReg.USUA_NOMB AS USRREG_NOMB',
- 'usrReg.USUA_APPA AS USRREG_APPA',
- 'usrReg.USUA_APMA AS USRREG_APMA'
- ])->where('RVTN_NULI', '=', $line)
- ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')
- ->leftJoin('S002V01TUSUA as usrReg', function ($join) {
- $join->on('usrReg.USUA_IDUS', '=', 'S002V01TRVTN.RVTN_USRE')
- ->on('usrReg.USUA_NULI', '=', 'S002V01TRVTN.RVTN_NULI');
- })
- ->orderBy('RVTN_IDVI', 'desc')->get()->all();
- foreach ($visits as $visit) {
- $visit->IDVISITA = $this->encryptionController->encrypt($visit->IDVISITA);
- $visit->EQUIPAMIENTO = $this->encryptionController->encrypt($visit->EQUIPAMIENTO);
- $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO);
- $nameReg = $this->functionsController->joinName($visit->USRREG_NOMB, $visit->USRREG_APPA, $visit->USRREG_APMA);
- if (!empty($nameReg)) {
- $visit->USRREG = trim((string) $nameReg) . " (" . $visit->USRREG . ")";
- }
- unset($visit->USRREG_NOMB, $visit->USRREG_APPA, $visit->USRREG_APMA);
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P02COVI',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la lista de visitas no programadas.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $visits);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getUnprogrammedVisit($idVisit, $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_IDUS', '=', $idUser],
- ['USUA_NULI', '=', $line]
- ])->first();
- if (is_null($usr)) {
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idVisit = $this->encryptionController->decrypt($idVisit);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->select([
- 'RVTN_IDVI AS IDVISITA',
- 'RVTN_EQRE AS EQUIPAMIENTO',
- 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
- 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
- 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
- 'RVTN_PEIN AS PERSONAL',
- 'RVTN_MAUT AS MATERIAL',
- 'RVTN_COME AS COMENTARIOS',
- 'RVTN_ESTA AS ESTADO',
- 'RVTN_USRE AS USRREG',
- 'RVTN_FERE AS FECREG',
- 'RVTN_UARE AS USAURE',
- 'RVTN_FARE AS FEAURE',
- 'RVTN_USCA AS USRCAN',
- 'RVTN_FECA AS FECCAN',
- 'RVTN_USFI AS USUFIN',
- 'RVTN_FEFI AS FECFIN',
- 'RVTN_USMO AS USRMOD',
- 'RVTN_FEMO AS FECMOD',
- ])->where([
- ['RVTN_IDVI', '=', $idVisit],
- ['RVTN_NULI', '=', $line]
- ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita consultada no existe.', [], 404);
- }
- $visit->IDVISITA = $this->encryptionController->encrypt($visit->IDVISITA);
- $visit->EQUIPAMIENTO = $this->encryptionController->encrypt($visit->EQUIPAMIENTO);
- $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO);
- $staffFn = [];
- $staffArr = json_decode($visit->PERSONAL, true);
- foreach ($staffArr as $item) {
- $name = '';
- if ($item['TYPE'] == 'EQ') {
- $workTeam = DB::table('S002V01TEQMA')->where([
- ['EQMA_NULI', '=', $line],
- ['EQMA_IDEQ', '=', $item['ID']]
- ])->first();
- $name = $workTeam->EQMA_NOMB;
- } else if ($item['TYPE'] == 'SU') {
- $subcontratist = DB::table('S002V01TPESU')->where([
- ['PESU_NULI', '=', $line],
- ['PESU_IDPS', '=', $item['ID']]
- ])->first();
- $name = $subcontratist->PESU_RASO;
- } else if ($item['TYPE'] == 'EM') {
- $employee = DB::table('S002V01TPERS')
- ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPE', '=', $item['ID']]
- ])->first();
- $name = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
- }
- $staffFn[] = [
- 'ID' => $this->encryptionController->encrypt($item['ID']),
- 'TYPE' => $item['TYPE'],
- 'NAME' => $name,
- ];
- }
- $visit->PERSONAL = json_encode($staffFn);
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $visit->USRREG],
- ])->first();
- $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $visit->USRREG . ")";
- $visit->USRREG = $nameReg;
- if (!is_null($visit->USAURE)) {
- $usaure = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $visit->USAURE],
- ])->first();
- $nameUre = $this->functionsController->joinName($usaure->USUA_NOMB, $usaure->USUA_APPA, $usaure->USUA_APMA) . " (" . $visit->USAURE . ")";
- $visit->USAURE = $nameUre;
- }
- if (!is_null($visit->USRCAN)) {
- $usrCan = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $visit->USRCAN],
- ])->first();
- $nameCan = $this->functionsController->joinName($usrCan->USUA_NOMB, $usrCan->USUA_APPA, $usrCan->USUA_APMA) . " (" . $visit->USRCAN . ")";
- $visit->USRCAN = $nameCan;
- }
- if (!is_null($visit->USUFIN)) {
- $usrFin = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $visit->USUFIN],
- ])->first();
- $nameFin = $this->functionsController->joinName($usrFin->USUA_NOMB, $usrFin->USUA_APPA, $usrFin->USUA_APMA) . " (" . $visit->USUFIN . ")";
- $visit->USUFIN = $nameFin;
- }
- if (!is_null($visit->USRMOD)) {
- $usrMod = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $visit->USRMOD],
- ])->first();
- $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA) . " (" . $visit->USRMOD . ")";
- $visit->USRMOD = $nameMod;
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P02COVI',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la visita no programada #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $visit);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function updateVisitStatus(Request $request)
- {
- DB::enableQueryLog();
- // RVTN_ESTA enum: 'PE','CA','RE','EL','VA','EP','CP','CE'
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_visit' => 'required|string',
- 'comments' => 'nullable|string|min:15',
- 'status' => 'required|string|in:PE,CA,RE,EL,VA,EP,CP,CE'
- ]);
- 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 del usuario que realizó la solicitud no está 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 consulta no está registrado.', [], 404);
- }
- $idVisit = $this->encryptionController->decrypt($form['id_visit']);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit],
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
- }
- $currentStatus = $visit->RVTN_ESTA;
- $newStatus = $form['status'];
- // Matriz de transiciones permitidas
- $allowedTransitions = [
- 'PE' => ['VA', 'RE', 'CA', 'EL'], // Pendiente
- 'VA' => ['EP', 'CA', 'EL'], // Validado
- 'EP' => ['CP', 'CA', 'EL'], // En proceso
- 'CP' => ['CE'], // Cerrado pendiente
- 'CE' => [], // Cerrado - Estado final
- 'CA' => [], // Cancelado - Estado final
- 'EL' => [], // Eliminado - Estado final
- 'RE' => [] // Rechazado - Estado final
- ];
- // Validar transición permitida
- $currentStatusTransitions = $allowedTransitions[$currentStatus] ?? [];
- // Si el estado actual no está en la matriz, no permitir cambios
- if (!array_key_exists($currentStatus, $allowedTransitions)) {
- return $this->responseController->makeResponse(true, "El estado actual {$currentStatus} no permite cambios.", [], 400);
- }
- // Validar si la transición está permitida
- if (!in_array($newStatus, $currentStatusTransitions)) {
- $statusNames = [
- 'PE' => 'Pendiente',
- 'CA' => 'Cancelado',
- 'RE' => 'Rechazado',
- 'EL' => 'Eliminado',
- 'VA' => 'Validado',
- 'EP' => 'En Proceso',
- 'CP' => 'Cerrado Pendiente',
- 'CE' => 'Cerrado'
- ];
- $currentStatusName = $statusNames[$currentStatus] ?? $currentStatus;
- $newStatusName = $statusNames[$newStatus] ?? $newStatus;
- return $this->responseController->makeResponse(true, "No se puede cambiar de {$currentStatusName} a {$newStatusName}. Transición no permitida.", [], 400);
- }
- // Obtener y actualizar historial de estados
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- if (!is_array($statusHistoryArr)) {
- $statusHistoryArr = [];
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- // Agregar nuevo estado al historial
- $statusHistoryArr[] = [
- 'FECHA' => $nowStr,
- 'ESTADO' => $newStatus,
- 'USUARIO' => $idUser
- ];
- $statusHistoryStr = json_encode($statusHistoryArr);
- // Preparar actualización
- $updateArr = [
- 'RVTN_ESTA' => $newStatus,
- 'RVTN_HIES' => $statusHistoryStr,
- 'RVTN_USMO' => $idUser,
- 'RVTN_FEMO' => $nowStr,
- ];
- // Asignar campos específicos según el estado
- if ($newStatus == 'PE') {
- // Pendiente - Ya registrado en creación
- } elseif ($newStatus == 'CA') {
- $updateArr['RVTN_USCA'] = $idUser;
- $updateArr['RVTN_FECA'] = $nowStr;
- // Registrar comentario de cancelación
- if (!empty($form['comments'])) {
- $commentsArr = json_decode($visit->RVTN_COME, true);
- if (!is_array($commentsArr)) {
- $commentsArr = [];
- }
- $commentsArr['COMENTARIO_CANCELACION'] = [
- 'ID' => $idUser,
- 'COMENTARIO' => $form['comments'],
- 'FECHA' => $nowStr
- ];
- $updateArr['RVTN_COME'] = json_encode($commentsArr);
- }
- } elseif ($newStatus == 'RE') {
- $updateArr['RVTN_UARE'] = $idUser;
- $updateArr['RVTN_FARE'] = $nowStr;
- // Registrar comentario de rechazo
- if (!empty($form['comments'])) {
- $commentsArr = json_decode($visit->RVTN_COME, true);
- if (!is_array($commentsArr)) {
- $commentsArr = [];
- }
- $commentsArr['COMENTARIO_RECHAZO'] = [
- 'ID' => $idUser,
- 'COMENTARIO' => $form['comments'],
- 'FECHA' => $nowStr
- ];
- $updateArr['RVTN_COME'] = json_encode($commentsArr);
- }
- } elseif ($newStatus == 'EL') {
- // Eliminado - podría necesitar campos específicos
- } elseif (in_array($newStatus, ['VA', 'EP', 'CP', 'CE'])) {
- $updateArr['RVTN_UARE'] = $idUser;
- $updateArr['RVTN_FARE'] = $nowStr;
- if ($newStatus == 'CE') {
- $updateArr['RVTN_USFI'] = $idUser;
- $updateArr['RVTN_FEFI'] = $nowStr;
- }
- }
- DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit],
- ])->update($updateArr);
- // Obtener audiencia para notificaciones (operarios y regulador)
- $audience = [];
- // Obtener operarios que aceptaron la invitación (del último estado VA)
- $statusHistoryForAudience = json_decode($visit->RVTN_HIES, true);
- if (is_array($statusHistoryForAudience)) {
- // Buscar el último estado VA
- $lastVAStatus = null;
- for ($i = count($statusHistoryForAudience) - 1; $i >= 0; $i--) {
- if ($statusHistoryForAudience[$i]['ESTADO'] === 'VA') {
- $lastVAStatus = $statusHistoryForAudience[$i];
- break;
- }
- }
- if ($lastVAStatus && isset($lastVAStatus['ATENCION']) && is_array($lastVAStatus['ATENCION'])) {
- foreach ($lastVAStatus['ATENCION'] as $item) {
- if (($item['RESPUESTA'] ?? '') === 'A') {
- $audience[] = $item['ID'];
- }
- }
- }
- }
- // Agregar regulador (quien registró la visita)
- if (!empty($visit->RVTN_USRE) && !in_array($visit->RVTN_USRE, $audience)) {
- $audience[] = $visit->RVTN_USRE;
- }
- // Preparar mensajes de notificación según el estado
- $statusMessages = [
- 'PE' => 'Pendiente',
- 'CA' => 'Cancelación',
- 'RE' => 'Rechazo',
- 'EL' => 'Eliminación',
- 'VA' => 'Validación',
- 'EP' => 'Inicio',
- 'CP' => 'Cerrado Pendiente',
- 'CE' => 'Cierre'
- ];
- $statusAction = $statusMessages[$newStatus] ?? 'Cambio de estado';
- $notificationTitle = "Visita Técnica No Programada #$idVisit";
- $notificationMessage = "La visita técnica no programada #$idVisit ha sido actualizada a estado: {$statusAction}.";
- // Notificación general para todos los cambios de estado
- if (in_array($newStatus, ['VA', 'RE', 'CA', 'EL', 'EP', 'CE', 'CP']) && !empty($audience)) {
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- $notificationTitle,
- $notificationMessage,
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- }
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la visita no programada #$idVisit a estado {$statusAction}.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- // Visitas técnicas no programadas (Preventivas)
- // Registrar comentario de finalización de un operario en estado CP
- public function registerOperatorClosingComment(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_visit' => 'required|string',
- 'comment' => '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 del usuario que realizó la solicitud no está 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 consulta no está registrado.', [], 404);
- }
- $idVisit = $this->encryptionController->decrypt($form['id_visit']);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit],
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
- }
- // Validar que la visita está en estado EP o CP
- if (!in_array($visit->RVTN_ESTA, ['EP', 'CP'])) {
- return $this->responseController->makeResponse(true, 'La visita no está en estado En Proceso o Cerrado Pendiente. Solo se pueden registrar comentarios de finalización en estos estados.', [], 400);
- }
- // Iniciar transacción
- DB::beginTransaction();
- try {
- // Obtener historial de estados
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- if (!is_array($statusHistoryArr)) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'No se encontró un historial de estados válido para la visita.', [], 500);
- }
- // Buscar el último estado VA para obtener la lista de operarios que aceptaron
- $lastVAStatus = null;
- $acceptedOperators = [];
- for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
- if ($statusHistoryArr[$i]['ESTADO'] === 'VA') {
- $lastVAStatus = $statusHistoryArr[$i];
- break;
- }
- }
- if (!$lastVAStatus || !isset($lastVAStatus['ATENCION']) || !is_array($lastVAStatus['ATENCION'])) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'No se encontró información de operarios asignados a la visita.', [], 404);
- }
- // Obtener lista de operarios que aceptaron
- foreach ($lastVAStatus['ATENCION'] as $item) {
- if (($item['RESPUESTA'] ?? '') === 'A') {
- $acceptedOperators[] = $item['ID'];
- }
- }
- // Validar que el usuario es uno de los operarios que aceptó
- if (!in_array($idUser, $acceptedOperators)) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'El usuario no está autorizado para registrar comentarios de finalización. Solo los operarios que aceptaron la invitación pueden registrar comentarios.', [], 401);
- }
- // Buscar el objeto CP en el historial o crearlo si no existe
- $cpStatusIndex = null;
- $cpStatus = null;
- $isFirstComment = false;
- for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
- if ($statusHistoryArr[$i]['ESTADO'] === 'CP') {
- $cpStatusIndex = $i;
- $cpStatus = $statusHistoryArr[$i];
- break;
- }
- }
- // Si no existe objeto CP, crear uno nuevo y cambiar estado de EP a CP
- if ($cpStatusIndex === null) {
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $isFirstComment = true;
- $cpStatus = [
- 'FECHA' => $nowStr,
- 'ESTADO' => 'CP',
- 'USUARIO' => $idUser,
- 'COMENTARIOS_OPERARIOS' => []
- ];
- $cpStatusIndex = count($statusHistoryArr);
- $statusHistoryArr[] = $cpStatus;
- } else {
- // Asegurar que existe el array de comentarios
- if (!isset($cpStatus['COMENTARIOS_OPERARIOS']) || !is_array($cpStatus['COMENTARIOS_OPERARIOS'])) {
- $cpStatus['COMENTARIOS_OPERARIOS'] = [];
- }
- }
- // Obtener comentarios existentes para validación
- $existingCommentsArr = json_decode($visit->RVTN_COME, true);
- if (!is_array($existingCommentsArr)) {
- $existingCommentsArr = [];
- }
- // Validar que el operario no haya registrado comentario ya
- if (isset($existingCommentsArr['COMENTARIOS_OPERADORES']) && is_array($existingCommentsArr['COMENTARIOS_OPERADORES'])) {
- foreach ($existingCommentsArr['COMENTARIOS_OPERADORES'] as $existingComment) {
- if (isset($existingComment['ID']) && $existingComment['ID'] === $idUser) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'Ya ha registrado su comentario de finalización para esta visita.', [], 400);
- }
- }
- }
- // Registrar el comentario del operario
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $operatorName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $cpStatus['COMENTARIOS_OPERARIOS'][] = [
- 'ID' => $idUser,
- 'COMENTARIO' => $form['comment'],
- 'FECHA' => $nowStr
- ];
- // Actualizar el objeto en el historial
- $statusHistoryArr[$cpStatusIndex] = $cpStatus;
- $statusHistoryStr = json_encode($statusHistoryArr);
- // Contar comentarios registrados vs total de operarios
- $updatedCommentsArr = json_decode($visit->RVTN_COME, true);
- $commentsRegistered = isset($updatedCommentsArr['COMENTARIOS_OPERADORES']) ? count($updatedCommentsArr['COMENTARIOS_OPERADORES']) : 0;
- $totalOperators = count($acceptedOperators);
- $isComplete = $commentsRegistered >= $totalOperators;
- // Preparar actualización de la visita
- $updateArr = [
- 'RVTN_HIES' => $statusHistoryStr,
- 'RVTN_USMO' => $idUser,
- 'RVTN_FEMO' => $nowStr,
- ];
- // Si es el primer comentario, cambiar estado de EP a CP
- if ($isFirstComment) {
- $updateArr['RVTN_ESTA'] = 'CP';
- $updateArr['RVTN_UARE'] = $idUser;
- $updateArr['RVTN_FARE'] = $nowStr;
- }
- // Actualizar comentarios de operadores
- $commentsArr = json_decode($visit->RVTN_COME, true);
- if (!is_array($commentsArr)) {
- $commentsArr = [];
- }
- // Inicializar array de comentarios de operadores si no existe
- if (!isset($commentsArr['COMENTARIOS_OPERADORES']) || !is_array($commentsArr['COMENTARIOS_OPERADORES'])) {
- $commentsArr['COMENTARIOS_OPERADORES'] = [];
- }
- // Agregar comentario del operario
- $commentsArr['COMENTARIOS_OPERADORES'][] = [
- 'ID' => $idUser,
- 'COMENTARIO' => $form['comment'],
- 'FECHA' => $nowStr
- ];
- $commentsStr = json_encode($commentsArr);
- $updateArr['RVTN_COME'] = $commentsStr;
- // Actualizar la visita
- DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit],
- ])->update($updateArr);
- // Obtener regulador para notificaciones
- $regulatorId = $visit->RVTN_USRE;
- $regulatorAudience = !empty($regulatorId) ? [$regulatorId] : [];
- // Obtener audiencia completa (operarios y regulador) para notificación de cambio de estado
- $audience = [];
- if (!empty($lastVAStatus['ATENCION']) && is_array($lastVAStatus['ATENCION'])) {
- foreach ($lastVAStatus['ATENCION'] as $item) {
- if (($item['RESPUESTA'] ?? '') === 'A') {
- $audience[] = $item['ID'];
- }
- }
- }
- if (!empty($regulatorId) && !in_array($regulatorId, $audience)) {
- $audience[] = $regulatorId;
- }
- // Si es el primer comentario (cambio EP -> CP), notificar a todos
- if ($isFirstComment && !empty($audience)) {
- $notificationTitle = "Visita Técnica No Programada #$idVisit";
- $notificationMessage = "La visita técnica no programada #$idVisit ha pasado a estado Cerrado Pendiente.";
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- $notificationTitle,
- $notificationMessage,
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- }
- // Notificar al regulador por cada comentario registrado
- if (!empty($regulatorAudience)) {
- $notificationTitle = "Visita Técnica No Programada #$idVisit";
- $notificationMessage = "El usuario $operatorName ($idUser) registró comentario de finalización de la visita #$idVisit.";
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- $notificationTitle,
- $notificationMessage,
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $regulatorAudience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- }
- // Si todos los comentarios están completos, enviar notificación final
- if ($isComplete && !empty($regulatorAudience)) {
- $finalNotificationTitle = "Visita Técnica No Programada #$idVisit";
- $finalNotificationMessage = "La visita #$idVisit ya puede ser cerrada. Todos los operarios han registrado sus comentarios de finalización.";
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- $finalNotificationTitle,
- $finalNotificationMessage,
- [[
- 'BOTON' => 'Cerrar visita',
- 'FUNCION' => 'closePreventiveVisit',
- 'PARAMETROS' => json_encode([
- $this->encryptionController->encrypt($idVisit),
- $this->encryptionController->encrypt($form['linea']),
- $this->encryptionController->encrypt($regulatorId)
- ])
- ], [
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $regulatorAudience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- }
- // Confirmar transacción
- DB::commit();
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró comentario de finalización para la visita no programada #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.', [
- 'comments_registered' => $commentsRegistered,
- 'total_operators' => $totalOperators,
- 'is_complete' => $isComplete
- ]);
- } catch (\Exception $e) {
- // Revertir transacción en caso de error
- DB::rollBack();
- $actions = DB::getQueryLog();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $name = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Error',
- "Error al registrar comentario de finalización para la visita no programada #$idVisit: " . $e->getMessage(),
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(
- true,
- 'Ocurrió un error al registrar el comentario de finalización.',
- ['error' => $e->getMessage()],
- 500
- );
- }
- }
- // Visitas técnicas no programadas (Preventivas)
- public function startPreventiveVisit(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_visit' => '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);
- }
- $idVisit = $this->encryptionController->decrypt($form['id_visit']);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
- }
- $visitStates = [
- 'PE' => 'Pendiente',
- 'CA' => 'Cancelado',
- 'RE' => 'Rechazado',
- 'EL' => 'Eliminado',
- 'VA' => 'Validado',
- 'EP' => 'En Proceso',
- 'CP' => 'Cerrado Pendiente',
- 'CE' => 'Cerrado'
- ];
- if ($visit->RVTN_ESTA !== 'VA') {
- $statusKey = $visit->RVTN_ESTA;
- $statusName = array_key_exists($statusKey, $visitStates) ? $visitStates[$statusKey] : $statusKey;
- return $this->responseController->makeResponse(true, "La visita está $statusName.", [], 401);
- }
- if ($visit->RVTN_USRE != $idUser) {
- return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
- }
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- if (!is_array($statusHistoryArr)) {
- $statusHistoryArr = [];
- }
- // Buscar objeto VA en el historial
- // Si no existe pero RVTN_ESTA == 'VA', la visita está validada pero aún no tiene operarios asignados
- $validatedHistoryFilt = array_filter($statusHistoryArr, function ($item) {
- return array_key_exists('ESTADO', $item) && $item['ESTADO'] == 'VA';
- });
- $audience = [];
- // Si existe el objeto VA en el historial, obtener los operarios aceptados
- if (!empty($validatedHistoryFilt)) {
- $validatedStatus = end($validatedHistoryFilt);
- if (array_key_exists('ATENCION', $validatedStatus) && is_array($validatedStatus['ATENCION'])) {
- foreach ($validatedStatus['ATENCION'] as $item) {
- if (($item['RESPUESTA'] ?? '') === 'A') {
- $audience[] = $item['ID'];
- }
- }
- }
- }
- // Si no existe el objeto VA en el historial pero RVTN_ESTA == 'VA',
- // la audiencia quedará vacía (no hay operarios asignados aún)
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryArr[] = [
- 'USUARIO' => $idUser,
- 'ESTADO' => 'EP',
- 'FECHA' => $nowStr
- ];
- $statusHistoryStr = json_encode($statusHistoryArr);
- /*
- $commentsArr = json_decode($visit->RVTN_COME, true);
- if (!is_array($commentsArr)) {
- $commentsArr = [];
- }
- $commentsArr['COMENTARIO_INICIO'] = $form['comments'];
- $commentsStr = json_encode($commentsArr);
- */
- DB::table('S002V01TRVTN')->where([
- ['RVTN_IDVI', '=', $idVisit],
- ['RVTN_NULI', '=', $form['linea']]
- ])->update([
- 'RVTN_ESTA' => 'EP',
- 'RVTN_HIES' => $statusHistoryStr,
- 'RVTN_USMO' => $idUser,
- 'RVTN_FEMO' => $nowStr,
- ]);
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- "Visita Técnica No Programada #$idVisit",
- "Inicio de la ejecución de la visita técnica no programada #$idVisit.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") inició la visita técnica no programada #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function updateOrderStatus(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'status' => 'required|string|in:B,R,A,E'
- ]);
- 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 del usuario que realizó la solicitud no está 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 consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if (!$idOrder) {
- return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- }
- if ($form['status'] == 'A' && $order->OTPR_SEAN == null) {
- return $this->responseController->makeResponse(true, 'La orden no puede ser aprobada sin la asignación del análisis presupuestario.', [], 401);
- }
- $statusStr = '';
- switch ($form['status']) {
- case 'B':
- $statusStr = 'Borrador';
- break;
- case 'R':
- $statusStr = 'Revisión';
- break;
- case 'A':
- $statusStr = 'Aprobado';
- break;
- case 'E':
- $statusStr = 'Eliminado';
- break;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->update([
- 'OTPR_ESTA' => $form['status'],
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P01HOTP',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden #$idOrder a $statusStr.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function setBudgetAnalysis(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'analysis' => '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 del usuario que realizó la solicitud no está 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 consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if (!$idOrder) {
- return $this->responseController->makeResponse(true, 'El ID de la orden no está encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
- }
- $analysisArr = json_decode($form['analysis'], true);
- if (empty($analysisArr)) {
- return $this->responseController->makeResponse(true, 'El JSON de análisis no contiene información.', [], 400);
- } else if (!array_key_exists('teamsConf', $analysisArr)) {
- return $this->responseController->makeResponse(true, 'La información de la configuración de los equipos no se envió en el JSON.', [], 400);
- } else if (!is_array($analysisArr['teamsConf'])) {
- return $this->responseController->makeResponse(true, 'La configuración de los equipos tiene un formato inválido.', [], 400);
- }
- $teamsConf = $analysisArr['teamsConf'];
- foreach ($teamsConf as $key => $conf) {
- $idDec = $this->encryptionController->decrypt($conf['ID']);
- if (!$idDec) {
- return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
- }
- $conf['ID'] = $idDec;
- $teamsConf[$key] = $conf;
- }
- $analysisArr['teamsConf'] = $teamsConf;
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $sean = json_encode($analysisArr);
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->update([
- 'OTPR_SEAN' => $sean,
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P01HOTP',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") asignó el análisis presupuestario de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function getMaintenanceSimulation($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('S002V01TOTPR')->select([
- 'OTPR_IDOT AS IDORDER',
- 'OTPR_DEIN AS DESCRIPCION',
- 'OTPR_ININ AS INSTRUCCIONES',
- 'OTPR_EQIN AS EQUIPAMIENTO',
- 'OTPR_FIAP AS FECHAINICIO',
- 'OTPR_FTAP AS FECHAFINAL',
- 'OTPR_SEAN AS ANALISIS',
- 'OTPR_TIIN AS TIEINMEST',
- 'OTPR_OPPR AS OPERARIOS',
- 'OTPR_DTIN AS TIETOTEST',
- 'OTPR_RHRE AS RECURSOS',
- 'OTPR_ACAS AS ACTIVADOR',
- 'OTPR_ESTA AS ESTADO',
- 'ACTI_PRIO AS PRIORIDAD',
- 'ACTI_TIAC AS TIPOACTIVADOR',
- 'ACTI_COAC AS CONFIGACTI'
- ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
- } else if ($order->ESTADO == 'B') {
- return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en borradores.', [], 401);
- } else if ($order->ESTADO == 'R') {
- return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en revisión.', [], 401);
- } else if ($order->ESTADO == 'E') {
- return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque ha sido eliminado.', [], 401);
- }
- $analisisArr = json_decode($order->ANALISIS, true);
- $teamsConf = $analisisArr['teamsConf'];
- foreach ($teamsConf as $key => $val) {
- $val['ID'] = $this->encryptionController->encrypt($val['ID']);
- $teamsConf[$key] = $val;
- }
- $analisisArr['teamsConf'] = $teamsConf;
- $order->ANALISIS = json_encode($analisisArr);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M10GMPR',
- 'S002V01F06SPMA',
- 'S002V01P02VSPM',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la simulación de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $order);
- }
- public function getOrderWithActivator($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('S002V01TOTPR')->select([
- 'OTPR_IDOT AS IDORDEN',
- 'OTPR_DEIN AS DESCRIPCION',
- 'OTPR_ININ AS INSTRUCCIONES',
- 'OTPR_EQIN AS EQUIPAMIENTO',
- 'OTPR_FIAP AS FECHAINICIO',
- 'OTPR_FTAP AS FECHAFINAL',
- 'OTPR_TIIN AS TIEINMEST',
- 'OTPR_DTIN AS TIETOTEST',
- 'OTPR_ACAS AS ACTIVADOR',
- 'OTPR_CLAS AS CLASIFICACION',
- 'OTPR_ESTA AS ESTADO',
- 'ACTI_PRIO AS PRIORIDAD',
- 'ACTI_TIAC AS TIPOACTIVADOR',
- 'ACTI_COAC AS CONFIGACTIVADOR',
- ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder],
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F02AFDT',
- 'S002V01P01OTAT',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la información de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $order);
- }
- public function updateOrderWithActivator(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'id_activator' => 'required|string',
- 'start_date' => 'required|date',
- 'end_date' => 'required|date',
- 'activator_type' => 'required|string|in:Calendario,Sintoma,Medida,Valor',
- 'priority' => 'required|string|in:1,2,3,4',
- 'config_activator' => '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 del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $idUser],
- ['USUA_NULI', '=', $form['linea']],
- ])->first();
- if (is_null($usr)) {
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if (!$idOrder) {
- return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404);
- }
- $idActivator = $this->encryptionController->decrypt($form['id_activator']);
- if (!$idActivator) {
- return $this->responseController->makeResponse(true, 'El ID del activador solicitado no está encriptado correctamente.', [], 400);
- }
- $activator = DB::table('S002V01TACTI')->where([
- ['ACTI_IDAC', '=', $idActivator],
- ['ACTI_NULI', '=', $form['linea']]
- ])->first();
- if (is_null($activator)) {
- return $this->responseController->makeResponse(true, 'El activador solicitado no existe.', [], 404);
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->update([
- 'OTPR_ACAS' => $idActivator,
- 'OTPR_FIAP' => $form['start_date'],
- 'OTPR_FTAP' => $form['end_date'],
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr,
- ]);
- DB::table('S002V01TACTI')->where([
- ['ACTI_IDAC', '=', $idActivator],
- ['ACTI_NULI', '=', $form['linea']]
- ])->update([
- 'ACTI_PRIO' => $form['priority'],
- 'ACTI_TIAC' => $form['activator_type'],
- 'ACTI_COAC' => $form['config_activator'],
- 'ACTI_USMO' => $idUser,
- 'ACTI_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F02AFDT',
- 'S002V01P02ACAC',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden #$idOrder y el activador #$idActivator.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function printOrderSimulation($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('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
- }
- $simulation = DB::table('S002V01TRESI')->where([
- ['RESI_NULI', '=', $line],
- ['RESI_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($simulation)) {
- return $this->responseController->makeResponse(true, "La orden #$idOrder aún no ha sido simulada.", [], 401);
- }
- $content = json_decode($simulation->RESI_CUSI, true);
- $html = "
- <html>
- <head>
- <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">
- <style>
- .main-icon-cell{
- width: 50px;
- height: 50px;
- }
- .main-icon-container{
- width: 50px;
- height: 50px;
- border-radius: 64px;
- border-style: solid;
- padding-left: 8px;
- padding-top: 8px;
- border-color: rgba(0, 0, 0, 0.8);
- }
- .icon-container{
- padding-left: 8px;
- width: 42px;
- height: 42px;
- }
- .instruction-font{
- color: rgba(0, 0, 0, 0.8);
- font-size: 24px;
- padding-left: 8px;
- font-weight: 600;
- }
- .space-cell{
- width: 50px;
- }
- </style>
- </head>
- <body>
- <table width=\"100%\">
- ";
- foreach ($content as $item) {
- $imgContent = file_get_contents($this->functionsController->getBasePath() . "\storage\app\\files\\$item[icon].png");
- $imgB64 = "data:image/png;base64, " . base64_encode($imgContent);
- $html .= "
- <tr>
- ";
- if (!$item['isMain']) {
- $html .= '<td class="space-cell"></td>';
- }
- $html .= "
- <td class=\"main-icon-cell\">
- <div class=\"
- ";
- if ($item['isMain']) {
- $html .= 'main-icon-container">';
- } else {
- $html .= 'icon-container ">';
- }
- $html .= "
- <img src=\"$imgB64\" width=\"42\" height=\"42\">
- </div>
- </td>
- <td class=\"instruction-font\" colspan=\"
- ";
- if ($item['isMain']) {
- $html .= '2';
- }
- $html .= "
- \">$item[label]</td>
- </tr>
- ";
- }
- $html .= "
- </table>
- </body>
- </html>";
- $filePath = $this->functionsController->getBasePath() . '\public_files\\';
- $noar = "simulacion_orden_$idOrder";
- $exte = "pdf";
- $line = intval($line);
- $line = $line < 10 ? "0$line" : "$line";
- $como = "GMPR";
- $cldo = "OR";
- $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";
- }
- $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() . "\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,
- ]);
- $filesArr = json_decode($order->OTPR_DONE, true);
- $filesArr[] = $fileName;
- $filesStr = json_encode($filesArr);
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->update([
- 'OTPR_DONE' => $filesStr,
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M10GMPR',
- 'S002V01F06SPMA',
- 'S002V01P02VSPM',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
- }
- public function saveOrderSimulation(Request $request)
- {
- DB::enableQueryLog();
- $validator = Validator::make($request->all(), [
- 'id_user' => 'required|string',
- 'linea' => 'required|integer',
- 'id_order' => 'required|string',
- 'content' => '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 del usuario que realizó la solicitud no está 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 consulta no está registrado.', [], 404);
- }
- $idOrder = $this->encryptionController->decrypt($form['id_order']);
- if (!$idOrder) {
- return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
- }
- $order = DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $form['linea']],
- ['OTPR_IDOT', '=', $idOrder],
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
- }
- $simulation = DB::table('S002V01TRESI')->where([
- ['RESI_NULI', '=', $form['linea']],
- ['RESI_IDOT', '=', $idOrder],
- ])->first();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- if (is_null($simulation)) {
- DB::table('S002V01TRESI')->insert([
- 'RESI_NULI' => $form['linea'],
- 'RESI_IDOT' => $idOrder,
- 'RESI_CUSI' => $form['content'],
- 'RESI_FUSI' => $nowStr,
- 'RESI_UUSI' => $idUser,
- ]);
- } else {
- $timestamp = $now->timestamp;
- $history = $simulation->RESI_HISI == null ? [] : json_decode($simulation->RESI_HISI, true);
- $history[$timestamp] = [
- 'USUARIO' => $simulation->RESI_UUSI,
- 'FECHA' => $simulation->RESI_FUSI,
- 'CONTENIDO' => $simulation->RESI_CUSI,
- ];
- $historyStr = json_encode($history);
- DB::table('S002V01TRESI')->where([
- ['RESI_NULI', '=', $form['linea']],
- ['RESI_IDOT', '=', $idOrder],
- ])->update([
- 'RESI_CUSI' => $form['content'],
- 'RESI_FUSI' => $nowStr,
- 'RESI_UUSI' => $idUser,
- 'RESI_HISI' => $historyStr,
- ]);
- }
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F06SPMA',
- 'S002V01P02VSPM',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") registró una simulación para la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(false, 'EXITO.');
- }
- public function printOrderDetails($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('S002V01TOTPR')->join(
- 'S002V01TACTI',
- 'OTPR_ACAS',
- '=',
- 'ACTI_IDAC',
- )->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
- }
- $html = "
- <html>
- <head>
- <style>
- table{
- border-collapse: separate;
- border-spacing: 0;
- width: 100%;
- }
- .cell-title{
- font-size: 12px;
- font-weight: bold;
- padding: 8px 8px 4px 8px;
- }
- .top-corners-radius{
- border-radius: 4px 4px 0 0;
- }
- .left-bottom-corner-radius{
- border-radius: 0 0 0 4px;
- }
- .right-bottom-corner-radius{
- border-radius: 0 0 4px 0;
- }
- .cell-content{
- padding: 4px 8px 8px 8px;
- font-size: 16px;
- color: rgba(0, 0, 0, 0.7);
- }
- .border-top{ border-top: 1px solid #dddddd; }
- .border-left{ border-left: 1px solid #dddddd; }
- .border-right{ border-right: 1px solid #dddddd; }
- .border-bottom{ border-bottom: 1px solid #dddddd; }
- </style>
- </head>
- <body>
- <table>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title top-corners-radius border-top border-left border-right\">Descripción</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">" . $order->OTPR_DEIN . "</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Instrucciones</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">
- ";
- $instructions = json_decode($order->OTPR_ININ, true);
- $cont = 1;
- foreach ($instructions as $instruction) {
- $html .= $cont . ".- " . $instruction['INSTRUCCION'] . "<br>";
- $cont++;
- }
- $startDate = $this->functionsController->formatDateTime($order->OTPR_FIAP);
- $endDate = $this->functionsController->formatDateTime($order->OTPR_FTAP);
- $html .= "
- </td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Equipamiento relacionado</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">" . $order->OTPR_EQIN . "</td></tr>
- <tr>
- <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Fecha y hora de inicio</td>
- <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha y hora final</td>
- </tr>
- <tr>
- <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right\">$startDate</td>
- <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right\">$endDate</td>
- </tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Análisis presupuestario</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">
- ";
- $analisis = $order->OTPR_SEAN == null ? 'Sin configuración' : json_decode($order->OTPR_SEAN, true);
- if (gettype($analisis) == 'array') {
- //PENDIENTE
- $teamsConf = $analisis['teamsConf'];
- foreach ($teamsConf as $key => $team) {
- /*var_dump($key);
- echo "<br>";*/
- }
- $html .= "
- PENDIENTE
- </td></tr>
- ";
- } else {
- $html .= "
- $analisis
- </td></tr>
- ";
- }
- $html .= "
- <tr>
- <td width=\"33%\" colspan=\"2\" class=\"cell-title border-top border-left border-right\">Clasificación</td>
- <td width=\"34%\" colspan=\"2\" class=\"cell-title border-top border-right\">Duración total estimada</td>
- <td width=\"33%\" colspan=\"2\" class=\"cell-title border-top border-right\">Tiempo de inmovilización estimado</td>
- </tr>
- <tr>
- <td width=\"33%\" colspan=\"2\" class=\"cell-content border-left border-right\">" . $order->OTPR_CLAS . "</td>
- <td width=\"34%\" colspan=\"2\" class=\"cell-content border-right\">" . $order->OTPR_DTIN . " hora(s)</td>
- <td width=\"33%\" colspan=\"2\" class=\"cell-content border-right\">" . $order->OTPR_TIIN . " hora(s)</td>
- </tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Personal involucrado</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Recursos requerido</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Documentos requeridos</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Contratos requeridos</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Información del activador</td></tr>
- <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
- <tr>
- <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Usuario que registró</td>
- <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha de registro</td>
- </tr>
- <tr>
- <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right\">PENDIENTE</td>
- <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right\">PENDIENTE</td>
- </tr>
- <tr>
- <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Usuario de la última modificación</td>
- <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha de la última modificación</td>
- </tr>
- <tr>
- <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right border-bottom left-bottom-corner-radius\">PENDIENTE</td>
- <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right border-bottom right-bottom-corner-radius\">PENDIENTE</td>
- </tr>
- </table>
- </body>
- </html>
- ";
- $filePath = $this->functionsController->getBasePath() . '\public_files\\';
- $noar = "detalles_orden_$idOrder";
- $exte = "pdf";
- $line = intval($line);
- $line = $line < 10 ? "0$line" : "$line";
- $como = "GMPR";
- $cldo = "OR";
- $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";
- }
- $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() . "\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,
- ]);
- $filesArr = json_decode($order->OTPR_DONE, true);
- $filesArr[] = $fileName;
- $filesStr = json_encode($filesArr);
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->update([
- 'OTPR_DONE' => $filesStr,
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M10GMPR',
- 'S002V01F06SPMA',
- 'S002V01P02VSPM',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
- }
- public function extractMaintenancePlan($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('S002V01TOTPR')->join(
- 'S002V01TACTI',
- 'OTPR_ACAS',
- '=',
- 'ACTI_IDAC',
- )->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
- }
- $html = file_get_contents($this->templatesUbic . "01-GMPR-PL-010101-000003=01=PDF_PLAN_MANTENIMIENTO.html");
- $logo = file_get_contents($this->functionsController->getBasePath() . "\storage\app\public\global_resources\sam-short-logo.png");
- $logoStr = "data:image/svg+xml;base64," . base64_encode($logo);
- $html = str_replace("%stcImage%", $logoStr, $html);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $currentDate = $this->functionsController->buildHumanCurrentDate($nowStr);
- $html = str_replace("%currentDate%", $currentDate, $html);
- $html = str_replace("%idOrder%", $order->OTPR_IDOT, $html);
- $startDateTimeArr = explode(" ", $order->OTPR_FIAP);
- $startTimeArr = explode(":", $startDateTimeArr[1]);
- $startHour = intval($startTimeArr[0]);
- $startPeriod = $startHour < 12 ? 'AM' : 'PM';
- $startHour = $startHour > 12 ? $startHour - 12 : $startHour;
- $startTimeStr = "$startHour:$startTimeArr[1] $startPeriod";
- $html = str_replace("%startTime%", $startTimeStr, $html);
- $startDateTimeObj = new Carbon($order->OTPR_FIAP);
- $totalDuration = floatval($order->OTPR_DTIN);
- $totalDurationHours = intval($totalDuration);
- $startDateTimeObj->addHours($totalDuration);
- $totalDurationFloatMinutes = $this->functionsController->floatSub($totalDuration, $totalDurationHours);
- $totalDurationFloatMinutes = $this->functionsController->floatMul($totalDurationFloatMinutes, 60);
- $totalDurationMinutes = ceil($totalDurationFloatMinutes);
- $startDateTimeObj->addMinutes($totalDurationMinutes);
- $endDateTimeArr = explode(" ", $startDateTimeObj->toDateTimeString());
- $endTimeArr = explode(":", $endDateTimeArr[1]);
- $endHour = intval($endTimeArr[0]);
- $endPeriod = $startHour < 12 ? 'AM' : 'PM';
- $endHour = $endHour > 12 ? $endHour - 12 : $endHour;
- $endTimeStr = "$endHour:$endTimeArr[1] $endPeriod";
- $html = str_replace("%endTime%", $endTimeStr, $html);
- $html = str_replace("%inmTime%", $order->OTPR_TIIN . " h", $html);
- $html = str_replace("%totalTime%", $order->OTPR_DTIN . " h", $html);
- $html = str_replace("%equipment%", $order->OTPR_EQIN, $html);
- $html = str_replace("%description%", $order->OTPR_DEIN, $html);
- $instructions = json_decode($order->OTPR_ININ, true);
- $activitiesTableBody = "";
- foreach ($instructions as $k => $v) {
- $key = $k + 1;
- $activitiesTableBody .= "<tr>";
- $activitiesTableBody .= "<td>$key</td>";
- $activitiesTableBody .= "<td>$v[INSTRUCCION]</td>";
- $activitiesTableBody .= "<td>";
- /*foreach($v['ESPECIALIDADES'] as $v0){
- /*$team = array_filter($teams, function($v1) use ($v0) {
- return ($v1['ID'] == $v0);
- });
- $activitiesTableBody .= /*end($team)['ESP'] '--' . "<br>";
- }*/
- $activitiesTableBody .= "</td>";
- $activitiesTableBody .= "</tr>";
- }
- $html = str_replace("%activitiesTableBody%", $activitiesTableBody, $html);
- $personalArr = json_decode($order->OTPR_OPPR, true);
- $constConf = json_decode($order->OTPR_SEAN, true);
- $cont = 1;
- $specialtiesTableBody = "";
- foreach ($personalArr as $k => $v) {
- /*$team = array_filter($teams, function($v1) use ($k) {
- return ($v1['ID'] == $k);
- });*/
- $specialtiesTableBody .= "<tr>";
- $specialtiesTableBody .= "<td>$cont</td>";
- $specialtiesTableBody .= "<td>" . /*end($team)['ESP']*/ '--' . "</td>";
- $specialtiesTableBody .= "<td>";
- foreach ($constConf['teamsConf'][$k] as $v0) {
- $usrID = '-'; //$v0['USER'];
- $usrInv = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $usrID],
- ])->first();
- $invName = /*$this->functionsController->joinName($usrInv->USUA_NOMB, $usrInv->USUA_APPA, $usrInv->USUA_APMA) . " ($usrID)"*/ '-';
- $specialtiesTableBody .= $invName . "<br>";
- }
- $specialtiesTableBody .= "</td>";
- $specialtiesTableBody .= "</tr>";
- $cont++;
- }
- $html = str_replace("%specialtiesTableBody%", $specialtiesTableBody, $html);
- $como = 'GMPR';
- $cldo = 'OR';
- $noar = "plan_de_mantenimiento_preventivo_orden_$idOrder";
- $exte = "pdf";
- $line = $line < 10 ? "0$line" : "$line";
- $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() . "\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,
- ]);
- $filesArr = json_decode($order->OTPR_DONE, true);
- $filesArr[] = $fileName;
- $filesStr = json_encode($filesArr);
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->update([
- 'OTPR_DONE' => $filesStr,
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M10GMPR',
- 'S002V01F07EPMA',
- 'S002V01P02DPMA',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
- }
- public function getMaintenancePlanAnalysis($idFile, $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_IDUS', '=', $idUser],
- ['USUA_NULI', '=', $line]
- ])->first();
- if (is_null($usr)) {
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idFile = $this->encryptionController->decrypt($idFile);
- if (!$idFile) {
- return $this->responseController->makeResponse(true, 'El ID del archivo solicitado no está encriptado correctamente.', [], 400);
- }
- $tempFile = DB::table('S002V01TARTE')->where([
- ['ARTE_NULI', '=', $line],
- ['ARTE_IDAR', '=', $idFile]
- ])->first();
- if (is_null($tempFile)) {
- return $this->responseController->makeResponse(true, 'El archivo solicitado no está registrado.', [], 404);
- }
- $fileColumnsEsp = [
- 'Id',
- 'Activo',
- 'Modo de tarea',
- 'Nombre',
- 'Duración',
- 'Comienzo',
- 'Fin',
- 'Trabajo_Programado',
- 'Costo',
- 'Duración de línea base estimada',
- 'Comienzo previsto',
- 'Fin de línea base',
- 'Trabajo previsto',
- 'Costo de línea base',
- 'Variación de duración',
- 'Variación de trabajo',
- 'Variación de costo'
- ];
- $fileColumnsIng = ['ID', 'Active', 'Task Mode', 'Name', 'Duration', 'Start', 'Finish', 'Predecessors', 'Outline Level', 'Notes'];
- $MONTHS_ESP = [
- 'enero' => '01',
- 'febrero' => '02',
- 'marzo' => '03',
- 'abril' => '04',
- 'mayo' => '05',
- 'junio' => '06',
- 'julio' => '07',
- 'agosto' => '08',
- 'septiembre' => '09',
- 'octubre' => '10',
- 'noviembre' => '11',
- 'diciembre' => '12'
- ];
- $MONTHS_ING = [
- '1' => '01',
- '2' => '02',
- '3' => '03',
- '4' => '04',
- '5' => '05',
- '6' => '06',
- '7' => '07',
- '8' => '08',
- '9' => '09',
- '10' => '10',
- '11' => '11',
- '12' => '12'
- ];
- $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE);
- $workSheet = $spreadsheet->getActiveSheet();
- $maxColStr = $workSheet->getHighestColumn();
- $maxCol = Coordinate::columnIndexFromString($maxColStr);
- for ($i = 1; $i <= $maxCol; $i++) {
- $colStr = Coordinate::stringFromColumnIndex($i);
- $cell = $workSheet->getCell($colStr . "1");
- $val = $cell->getValue();
- if (!in_array($val, $fileColumnsEsp) && !in_array($val, $fileColumnsIng)) {
- return $this->responseController->makeResponse(true, 'El archivo tiene un formato inválido.', [], 400);
- }
- }
- $instructions = [];
- $maxRow = $workSheet->getHighestRow();
- for ($row = 2; $row <= $maxRow; $row++) {
- $activo = $workSheet->getCell("B$row")->getValue();
- $language = $activo == 'Yes' ? 'I' : 'E';
- if ($activo == 'Sí' || $activo == 'Si' || $activo == 'Yes') {
- $durationStr = $workSheet->getCell("E$row")->getValue();
- $durationArr = explode(" ", $durationStr);
- $duration = 0;
- if ($durationArr[1] == 'días' || $durationArr[1] == 'dias' || $durationArr[1] == 'día' || $durationArr[1] == 'dia' || $durationArr[1] == 'days' || $durationArr[1] == 'day') {
- $daysFloat = floatval($durationArr[0]);
- $daysInt = intval($daysFloat);
- $duration += $daysInt * 24;
- $hoursDec = $this->functionsController->floatSub($daysFloat, $daysInt);
- $hoursFloat = $this->functionsController->floatMul($hoursDec, 24);
- $duration = $this->functionsController->floatAdd($duration, $hoursFloat);
- }
- if ($durationArr[1] == 'mins' || $durationArr[1] == 'min') {
- $minsFloat = floatval($durationArr[0]);
- $hoursFloat = $this->functionsController->floatDiv($minsFloat, 60);
- $duration = $this->functionsController->floatAdd($duration, $hoursFloat);
- }
- $duration = round($duration, 5);
- $startDateStr = $workSheet->getCell("F$row")->getValue();
- $startDateArr = explode(" ", $startDateStr);
- if ($language == 'I') {
- $americanDateArr = explode('/', $startDateArr[1]);
- $startMonth = $MONTHS_ING[$americanDateArr[0]];
- } else {
- $startMonth = $MONTHS_ESP[$startDateArr[1]];
- $startPeriod = $startDateArr[4] . $startDateArr[5];
- $startPeriod = str_replace('.', '', $startPeriod);
- $startHourArr = explode(":", $startDateArr[3]);
- $startHour = intval($startHourArr[0]);
- $startHour = $startPeriod == 'pm' && $startHour < 12 ? $startHour + 12 : $startHour;
- $startHourStr = $startHour < 10 ? "0$startHour" : "$startHour";
- $startDateTime = "$startDateArr[2]-$startMonth-$startDateArr[0] $startHourStr:$startHourArr[1]:00";
- $startDateTimeObj = new Carbon($startDateTime);
- $startTimestamp = $startDateTimeObj->timestamp;
- $endDateStr = $workSheet->getCell("G$row")->getValue();
- $endDateArr = explode(" ", $endDateStr);
- $endMonth = $MONTHS_ESP[$endDateArr[1]];
- $endPeriod = $endDateArr[4] . $endDateArr[5];
- $endPeriod = str_replace('.', '', $endPeriod);
- $endHourArr = explode(":", $endDateArr[3]);
- $endHour = intval($endHourArr[0]);
- $endHour = $endPeriod == 'pm' && $endHour < 12 ? $endHour + 12 : $endHour;
- $endHourStr = $endHour < 10 ? "0$endHour" : "$endHour";
- $endDateTime = "$endDateArr[2]-$endMonth-$endDateArr[0] $endHourStr:$endHourArr[1]:00";
- $endDateTimeObj = new Carbon($endDateTime);
- $endTimestamp = $endDateTimeObj->timestamp;
- }
- $difference = $endTimestamp - $startTimestamp;
- $minutes = $this->functionsController->floatDiv($difference, 60);
- $hours = $this->functionsController->floatDiv($minutes, 60);
- $duration = round($hours, 5);
- $instructions[] = [
- "INSTRUCTION" => $workSheet->getCell("D$row")->getValue(),
- "DURATION" => $duration,
- "START" => $startDateTime,
- "END" => $endDateTime,
- "COST" => $workSheet->getCell("I$row")->getValue(),
- ];
- }
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F10DIBI',
- '-',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó el plan de mantenimiento para una nueva orden desde MS Project.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $instructions);
- }
- public function getFileToMSProject($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('S002V01TOTPR')->where([
- ['OTPR_IDOT', '=', $idOrder],
- ['OTPR_NULI', '=', $line]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
- }
- $cols = [
- 'Id',
- 'Activo',
- 'Modo de tarea',
- 'Nombre',
- 'Duración',
- 'Comienzo',
- 'Fin',
- 'Trabajo_Programado',
- 'Costo',
- 'Duración de línea base estimada',
- 'Comienzo previsto',
- 'Fin de línea base',
- 'Trabajo previsto',
- 'Costo de línea base',
- 'Variación de duración',
- 'Variación de trabajo',
- 'Variación de costo'
- ];
- $analysis = json_decode($order->OTPR_SEAN, true);
- $instructionsConf = /*$analysis['instructionsConf']*/ '{}';
- $instructions = json_decode($order->OTPR_ININ, true);
- $arrCols = [];
- $cont = 1;
- foreach ($instructions as $instruction) {
- $projectDuration = "";
- if ($instruction['DURACION'] < 24) {
- $duration = $instruction['DURACION'] * 60;
- $projectDuration = "$duration min";
- if ($duration > 1) {
- $projectDuration .= "s";
- }
- } else {
- $duration = $this->functionsController->floatDiv($instruction['DURACION'], 24);
- $duration = round($duration, 2);
- $projectDuration = "$duration día";
- if ($duration > 1) {
- $projectDuration .= "s";
- }
- }
- $instructionStartDateTimeArr = explode(' ', $instruction['INICIO']);
- $instructionStartTimeArr = explode(':', $instructionStartDateTimeArr[1]);
- $instructionStartHour = intval($instructionStartTimeArr[0]);
- if ($instructionStartDateTimeArr[2] == 'PM' && $instructionStartHour < 12) {
- $instructionStartHour = $instructionStartHour + 12;
- }
- $instructionStartHourStr = $instructionStartHour < 10 ? "0$instructionStartHour" : "$instructionStartHour";
- $instructionStartTimeStr = "$instructionStartHourStr:$instructionStartTimeArr[1]:00";
- $instructionStartDateTimeStr = "$instructionStartDateTimeArr[0] $instructionStartTimeStr";
- $instructionEndDateTimeArr = explode(' ', $instruction['FIN']);
- $instructionEndTimeArr = explode(':', $instructionEndDateTimeArr[1]);
- $instructionEndHour = intval($instructionEndTimeArr[0]);
- if ($instructionEndDateTimeArr[2] == 'PM' && $instructionEndHour < 12) {
- $instructionEndHour = $instructionEndHour + 12;
- }
- $instructionEndHourStr = $instructionEndHour < 10 ? "0$instructionEndHour" : "$instructionEndHour";
- $instructionEndTimeStr = "$instructionEndHourStr:$instructionEndTimeArr[1]:00";
- $instructionEndDateTimeStr = "$instructionEndDateTimeArr[0] $instructionEndTimeStr";
- $projectStartDate = $this->functionsController->buildProjectDate($instructionStartDateTimeStr);
- $projectEndDate = $this->functionsController->buildProjectDate($instructionEndDateTimeStr);
- $cost = /*$instruction['ISFROMFILE'] ? $instruction['COSTO'] : $instructionsConf[$instruction['ID']]*/ '0';
- $arrCol = [
- "A" => $cont,
- "B" => 'Sí',
- "C" => 'Programada manualmente',
- "D" => $instruction['INSTRUCCION'],
- "E" => $projectDuration,
- "F" => $projectStartDate,
- "G" => $projectEndDate,
- "H" => "0h",
- "I" => $cost,
- "J" => "0d",
- "K" => "NOD",
- "L" => "NOD",
- "M" => "0h",
- "N" => "0",
- "O" => $projectDuration,
- "P" => "0h",
- "Q" => "0",
- ];
- $arrCols[] = $arrCol;
- $cont++;
- }
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $dateTimeArr = explode(" ", $nowStr);
- $dateArr = explode("-", $dateTimeArr[0]);
- $year = substr($dateArr[0], 2);
- $como = 'GMPR';
- $cldo = 'OR';
- $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 = "";
- 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;
- }
- $noar = "plan_de_mantenimiento_preventivo_ms_project_orden_$idOrder";
- $exte = "xlsx";
- $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 = "";
- if (is_null($ver)) {
- $nuve = "01";
- } else {
- $vers = intval($ver->AFAL_NUVE) + 1;
- $nuve = $vers < 10 ? "0$vers" : "$vers";
- }
- $line = $line < 10 ? "0$line" : "$line";
- $filePath = $this->functionsController->getBasePath() . '\public_files\\';
- $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
- $tempFile = $filePath . $fileName;
- if (file_exists($tempFile)) {
- unlink($tempFile);
- }
- $spreadsheet = new Spreadsheet();
- $workSheet = $spreadsheet->getActiveSheet();
- $colInd = 1;
- foreach ($cols as $colName) {
- $colStr = Coordinate::stringFromColumnIndex($colInd);
- $workSheet->setCellValue($colStr . "1", $colName);
- $workSheet->getColumnDimension($colStr)->setAutoSize(true);
- $colInd++;
- }
- $row = 2;
- foreach ($arrCols as $col) {
- foreach ($col as $k => $v) {
- $workSheet->setCellValue($k . $row, $v);
- }
- $row++;
- }
- $writer = new Xlsx($spreadsheet);
- $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,
- ]);
- $filesArr = json_decode($order->OTPR_DONE, true);
- $filesArr[] = $fileName;
- $filesStr = json_encode($filesArr);
- DB::table('S002V01TOTPR')->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_IDOT', '=', $idOrder]
- ])->update([
- 'OTPR_DONE' => $filesStr,
- 'OTPR_USMO' => $idUser,
- 'OTPR_FEMO' => $nowStr
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $line,
- 'S002V01M10GMPR',
- 'S002V01F10DIBI',
- '-',
- 'Registro',
- "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento para MS Project de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
- }
- public function getOrderStaff($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('S002V01TOTPR')->where([
- ['OTPR_IDOT', '=', $idOrder],
- ['OTPR_NULI', '=', $line]
- ])->first();
- if (is_null($order)) {
- return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
- }
- $staffArr = json_decode($order->OTPR_OPPR, true);
- $staffTmp = [];
- foreach ($staffArr as $val) {
- if ($val['TYPE'] == 'EQ') {
- $employees = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_EQTR', '=', $val['ID']],
- ])->get()->all();
- foreach ($employees as $employee) {
- if (!in_array($employee->PERS_IDPE, $staffTmp)) {
- $staffTmp[] = $employee->PERS_IDPE;
- }
- }
- } else if ($val['TYPE'] == 'SU') {
- $employees = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPS', '=', $val['ID']],
- ])->get()->all();
- foreach ($employees as $employee) {
- if (!in_array($employee->PERS_IDPE, $staffTmp)) {
- $staffTmp[] = $employee->PERS_IDPE;
- }
- }
- } else {
- $id = intval($val['ID']);
- if (!in_array($id, $staffTmp)) {
- $staffTmp[] = $id;
- }
- }
- }
- $staffFn = [];
- foreach ($staffTmp as $empID) {
- $employee = DB::table('S002V01TPERS')->select([
- 'PERS_IDPE AS IDEMPLEADO',
- 'PERS_IDUS AS IDUSUARIO',
- DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'),
- 'PERS_TICO AS TIPOCONTRATO',
- 'PERS_IDPS AS IDSUBCONTRATISTA',
- 'PESU_RASO AS RAZONSOCIAL',
- 'PESU_REFI AS REGIMENFISCAL',
- 'PERS_EQTR AS IDEQUIPO',
- 'EQMA_NOMB AS NOMBREEQUIPO'
- ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
- ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
- ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([
- ['PERS_NULI', '=', $line],
- ['PERS_IDPE', '=', $empID],
- ])->first();
- if (!is_null($employee)) {
- $staffFn[] = $employee;
- }
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P03COTP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados de la orden #$idOrder.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $staffFn);
- }
- public function getOrderExecutionDetails($idExecution, $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);
- }
- $idExecution = $this->encryptionController->decrypt($idExecution);
- if (!$idExecution) {
- return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada no está encriptado correctamente.', [], 400);
- }
- $idExecArr = explode('|', $idExecution);
- if (count($idExecArr) < 4) {
- return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada tiene un formato inválido.', [], 400);
- }
- $execution = DB::table('S002V01TBEOT')->select([
- 'BEOT_IDRE AS IDREGISTRO',
- 'BEOT_IDOT AS IDORDEN',
- 'BEOT_FEPR AS FECHAPROGRAMACION',
- 'BEOT_TIAC AS TIPOACCION',
- 'BEOT_TIOR AS TIPOORDEN',
- 'BEOT_DTEJ AS TIEMPOEJECUCION',
- 'BEOT_OBSE AS OBSERVACIONES',
- 'BEOT_FEEJ AS FECHAEJECUCION',
- 'BEOT_USEJ AS USUARIOEJECUCION',
- 'BEOT_FEFI AS FECHAFINALIZACION',
- 'BEOT_USFI AS USUARIOFINALIZO'
- ])->where([
- ['BEOT_IDRE', '=', $idExecArr[0]],
- ['BEOT_NULI', '=', $line],
- ['BEOT_IDOT', '=', $idExecArr[2]],
- ['BEOT_FEPR', '=', $idExecArr[3]],
- ])->first();
- if (is_null($execution)) {
- return $this->responseController->makeResponse(true, 'El registro de la ejecución solicitada no existe.', [], 404);
- }
- $execution->IDREGISTRO = $this->encryptionController->encrypt($execution->IDREGISTRO);
- $execution->IDORDEN = $this->encryptionController->encrypt($execution->IDORDEN);
- $execUsr = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $execution->USUARIOEJECUCION],
- ['USUA_NULI', '=', $line]
- ])->first();
- $execName = $this->functionsController->joinName($execUsr->USUA_NOMB, $execUsr->USUA_APPA, $execUsr->USUA_APMA);
- $execution->USUARIOEJECUCION = $execName . " (" . $execution->USUARIOEJECUCION . ")";
- if (!is_null($execution->USUARIOFINALIZO)) {
- $finUsr = DB::table('S002V01TUSUA')->where([
- ['USUA_IDUS', '=', $execution->USUARIOFINALIZO],
- ['USUA_NULI', '=', $line]
- ])->first();
- $finName = $this->functionsController->joinName($finUsr->USUA_NOMB, $finUsr->USUA_APPA, $finUsr->USUA_APMA);
- $execution->USUARIOFINALIZO = $finName . " (" . $execution->USUARIOFINALIZO . ")";
- }
- $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,
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P03COTP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó los detalles de la ejecución del a orden de trabajo preventivo #$idExecArr[2] para la fecha $idExecArr[3].",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $execution);
- }
- public function getWorkOrdersByEquipment($equipmentCode, $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);
- }
- $equipmentCode = $this->encryptionController->decrypt($equipmentCode);
- if (!$equipmentCode) {
- return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400);
- }
- $equipment = DB::table('S002V01TEQUI')->where([
- ['EQUI_NULI', '=', $line],
- ['EQUI_COEQ', '=', $equipmentCode]
- ])->first();
- if (is_null($equipment)) {
- return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404);
- }
- $workOrders = DB::table('S002V01TOTPR')->select([
- 'OTPR_IDOT AS IDORDEN',
- 'OTPR_EQIN AS EQUIPO',
- 'OTPR_FIAP AS FECHAINICIO',
- 'OTPR_FTAP AS FECHAFINAL',
- 'OTPR_ACAS AS ACTIVADOR',
- 'ACTI_TIAC AS TIPOACTIVADOR',
- 'ACTI_PRIO AS PRIORIDAD',
- 'OTPR_ESTA AS ESTATUS'
- ])->where([
- ['OTPR_NULI', '=', $line],
- ['OTPR_EQIN', '=', $equipmentCode],
- ['OTPR_ESTA', '!=', 'E'],
- ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')
- ->orderBy('OTPR_IDOT', 'desc')->get()->all();
- foreach ($workOrders as $key => $order) {
- $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
- $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO);
- $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR);
- if (!is_null($order->PRIORIDAD)) {
- $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
- }
- if ($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null;
- if ($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null;
- $workOrders[$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,
- 'S002V01M10GMPR',
- 'S002V01F01COTP',
- 'S002V01P01HOTP',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo relacionadas al equipamient $equipmentCode.",
- $idUser,
- $nowStr,
- 'S002V01S01ORTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $workOrders);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getVisit($idVisit, $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);
- }
- $idVisit = $this->encryptionController->decrypt($idVisit);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita no está encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->select([
- 'RVTN_IDVI AS ID_ORDEN',
- 'RVTN_DEIN AS DESCRIPCION',
- 'RVTN_EQRE AS CODIGO_EQUIPAMIENTO',
- 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
- 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
- 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
- 'RVTN_TESO AS TIEMPO_ESTIMADO',
- 'RVTN_CORE AS CONTADOR',
- 'RVTN_DRCO AS MEDIDAS',
- 'RVTN_PRIO AS PRIORIDAD',
- 'RVTN_MAUT AS RECURSOS',
- 'RVTN_TIAC AS TIPO_ACTIVACION',
- 'RVTN_DORE AS DOCUMENTOS_RELACIONADOS',
- 'RVTN_CLAS AS CLASIFICACION',
- 'RVTN_COME AS COMENTARIOS',
- 'RVTN_ESTA AS ESTADO',
- 'RVTN_USRE AS USUREG',
- 'RVTN_FERE AS FECREG',
- 'RVTN_HIES AS HISTORIAL',
- 'RVTN_PEIN AS PERSONAL'
- ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')
- ->where([
- ['RVTN_IDVI', '=', $idVisit],
- ['RVTN_NULI', '=', $line],
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita consultada no existe.', [], 404);
- }
- $visit->ID_ORDEN = $this->encryptionController->encrypt($visit->ID_ORDEN);
- $visit->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->CODIGO_EQUIPAMIENTO);
- if (!is_null($visit->ID_EQUIPAMIENTO)) {
- $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO);
- }
- $visit->CONTADOR = $this->encryptionController->encrypt($visit->CONTADOR);
- $visit->PRIORIDAD = $this->encryptionController->encrypt($visit->PRIORIDAD);
- // Procesar PERSONAL
- $staffArr = json_decode($visit->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;
- }
- $visit->PERSONAL = json_encode($staffArr);
- // Procesar MEDIDAS_OBJ
- $measureArr = json_decode($visit->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']);
- }
- $visit->MEDIDAS_OBJ = $measureArr;
- unset($visit->MEDIDAS);
- // Procesar RECURSOS_ARR
- $resources = json_decode($visit->RECURSOS, true);
- $resourcesFn = [];
- foreach ($resources as $resource) {
- if ($resource['ID'] != 'SH') {
- $resourceObj = DB::table('S002V01TINST')->where([
- ['INST_NULI', '=', $line],
- ['INST_IDIS', '=', $resource['ID']],
- ])->first();
- if (!is_null($resourceObj)) {
- $resourcesFn[] = $resourceObj->INST_MODE;
- }
- }
- }
- $visit->RECURSOS_ARR = $resourcesFn;
- // Procesar DOCUMENTOS_RELACIONADOS_ARR
- $documentsArr = json_decode($visit->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[] = [
- 'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE,
- 'size' => $file->AFAL_TAMA
- ];
- }
- $visit->DOCUMENTOS_RELACIONADOS_ARR = $documentsFn;
- // Mapear TIPO_ACTIVACION
- $activationTypes = ['M' => 'Manual', 'A' => 'Automática'];
- $visit->TIPO_ACTIVACION = $activationTypes[$visit->TIPO_ACTIVACION];
- // Mapear ESTADO (RVTN_ESTA enum: 'VA','EP','CP','CE','P','C','R','A','F')
- // VA, EP, CP, CE: Solo para RVTN_TIAC='A' (Automática)
- // P, C, R, A, F: Solo para RVTN_TIAC='M' (Manual)
- $orderStates = [
- 'VA' => 'Validado', // Automática
- 'EP' => 'En progreso', // Automática
- 'CP' => 'Cerrado pendiente', // Automática
- 'CE' => 'Cerrado', // Automática
- 'PE' => 'Pendiente', // Manual
- 'CA' => 'Cancelado', // Manual
- 'RE' => 'Rechazado', // Manual
- 'EL' => 'Eliminado', // Manual
- ];
- $visit->ESTADO = $orderStates[$visit->ESTADO];
- // Procesar usuarios
- $usrReg = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $visit->USUREG],
- ])->first();
- $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
- $visit->USUREG = $nameReg . " (" . $visit->USUREG . ")";
- $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,
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P02COVI',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó la visita técnica #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $visit);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function assignOperariosToPreventiveVisit(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);
- }
- $idVisit = $this->encryptionController->decrypt($form['id_order']);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
- } else if ($visit->RVTN_ESTA != 'PE' && $visit->RVTN_ESTA != 'VA') {
- return $this->responseController->makeResponse(true, 'La visita no está en un estado válido para asignar operarios.', [], 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 operarios 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 operario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios no existe.", [], 404);
- }
- $audience[] = $employee->PERS_IDUS;
- }
- }
- // Validación de cupo global (basado en RVTN_PEIN)
- $planilla = json_decode($visit->RVTN_PEIN, true);
- $cupoRequerido = 0;
- if (!empty($planilla) && is_array($planilla)) {
- foreach ($planilla as $pe) {
- $cupoRequerido += intval($pe['CANT'] ?? 0);
- }
- }
- // Obtener último VA
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- $vaObj = null;
- if (!empty($statusHistoryArr)) {
- for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
- if ($statusHistoryArr[$i]['ESTADO'] == 'VA') {
- $vaObj = $statusHistoryArr[$i];
- break;
- }
- }
- }
- $atencionActual = $vaObj && array_key_exists('ATENCION', $vaObj) ? $vaObj['ATENCION'] : [];
- $aceptadosActual = 0;
- foreach ($atencionActual as $itm) {
- if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosActual++;
- }
- if ($cupoRequerido > 0 && $aceptadosActual >= $cupoRequerido) {
- return $this->responseController->makeResponse(true, 'La planilla ya está completa. No se pueden asignar más operarios.', [], 401);
- }
- // Evitar invitación duplicada al mismo operario (ya invitado o ya respondió)
- $yaInvitados = [];
- foreach ($atencionActual as $itm) {
- $yaInvitados[$itm['ID']] = $itm['RESPUESTA'] ?? '';
- }
- foreach ($audience as $opId) {
- if (array_key_exists($opId, $yaInvitados)) {
- return $this->responseController->makeResponse(true, "El operario $opId ya fue invitado o respondió anteriormente.", [], 401);
- }
- }
- // Iniciar transacción
- DB::beginTransaction();
- try {
- // Emitir notificación
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- "Visita de mantenimiento preventivo #$idVisit",
- "Se ha asignado la visita de mantenimiento preventivo #$idVisit y requiere su atención.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Atender visita',
- 'FUNCION' => 'attendPreventiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- // Buscar si ya existe un objeto con estado VA
- $vaStatusIndex = null;
- foreach ($statusHistoryArr as $index => $status) {
- if ($status['ESTADO'] == 'VA') {
- $vaStatusIndex = $index;
- break;
- }
- }
- // Revalidar cupo justo antes de insertar (concurrencia)
- $vaObjRef = null;
- if (!empty($statusHistoryArr)) {
- for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
- if ($statusHistoryArr[$i]['ESTADO'] == 'VA') {
- $vaObjRef = $statusHistoryArr[$i];
- break;
- }
- }
- }
- $atencionRef = $vaObjRef && array_key_exists('ATENCION', $vaObjRef) ? $vaObjRef['ATENCION'] : [];
- $aceptadosRef = 0;
- foreach ($atencionRef as $itm) {
- if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosRef++;
- }
- if ($cupoRequerido > 0 && $aceptadosRef >= $cupoRequerido) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'La planilla ya está completa. No se pueden asignar más operarios.', [], 401);
- }
- // Crear nuevas invitaciones
- $newInvitations = [];
- foreach ($audience as $operarioId) {
- $newInvitations[] = [
- 'ID' => $operarioId,
- 'FIRMA' => null,
- 'RESPUESTA' => '',
- 'COMENTARIOS' => ''
- ];
- }
- if ($vaStatusIndex !== null) {
- // Extender objeto VA existente
- $statusHistoryArr[$vaStatusIndex]['ATENCION'] = array_merge(
- $statusHistoryArr[$vaStatusIndex]['ATENCION'],
- $newInvitations
- );
- // Agregar nuevos operarios a PERSONAL (sin duplicar)
- $currentPersonal = $statusHistoryArr[$vaStatusIndex]['PERSONAL'] ?? [];
- foreach ($audience as $operarioId) {
- if (!in_array($operarioId, $currentPersonal)) {
- $currentPersonal[] = $operarioId;
- }
- }
- $statusHistoryArr[$vaStatusIndex]['PERSONAL'] = $currentPersonal;
- } else {
- // Crear nuevo objeto VA con todos los invitados en PERSONAL
- $statusHistoryArr[] = [
- 'USUARIO' => $idUser,
- 'ESTADO' => 'VA',
- 'FECHA' => $nowStr,
- 'ATENCION' => $newInvitations,
- 'PERSONAL' => $audience
- ];
- }
- $statusHistoryStr = json_encode($statusHistoryArr);
- // Actualizar la visita
- DB::table('S002V01TRVTN')->where([
- ['RVTN_IDVI', '=', $idVisit],
- ['RVTN_NULI', '=', $form['linea']]
- ])->update([
- 'RVTN_ESTA' => 'VA',
- 'RVTN_HIES' => $statusHistoryStr,
- 'RVTN_USMO' => $idUser,
- 'RVTN_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") asignó operarios a la visita preventiva #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- // Confirmar transacción
- DB::commit();
- return $this->responseController->makeResponse(false, 'EXITO.');
- } catch (\Exception $e) {
- // Revertir transacción en caso de error
- DB::rollBack();
- $actions = DB::getQueryLog();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $name = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Error',
- "Error al asignar operarios a la visita preventiva #$idVisit: " . $e->getMessage(),
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(
- true,
- 'Ocurrió un error al asignar operarios a la visita preventiva.',
- ['error' => $e->getMessage()],
- 500
- );
- }
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getVisitAttendance($idVisit, $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);
- }
- $idVisit = $this->encryptionController->decrypt($idVisit);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita relacionada no está encriptado correctamente', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $line],
- ['RVTN_IDVI', '=', $idVisit]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita relacionada no está registrada.', [], 404);
- }
- // Validar que la visita esté en estado VA (validado)
- // Puede estar en estado VA en RVTN_ESTA sin tener aún el objeto VA en RVTN_HIES
- // (cuando se crea automáticamente pero aún no se han asignado operarios)
- $visitStates = [
- 'PE' => 'Pendiente',
- 'CA' => 'Cancelado',
- 'RE' => 'Rechazado',
- 'EL' => 'Eliminado',
- 'VA' => 'Validado',
- 'EP' => 'En Proceso',
- 'CP' => 'Cerrado Pendiente',
- 'CE' => 'Cerrado'
- ];
- if ($visit->RVTN_ESTA !== 'VA') {
- $statusKey = $visit->RVTN_ESTA;
- $statusName = array_key_exists($statusKey, $visitStates) ? $visitStates[$statusKey] : $statusKey;
- return $this->responseController->makeResponse(true, "La visita relacionada no está en el estado de validación (estado actual: $statusName)", [], 404);
- }
- $statusHistory = json_decode($visit->RVTN_HIES, true);
- if (!is_array($statusHistory)) {
- $statusHistory = [];
- }
- $validatedHistoryFilt = array_filter($statusHistory, function ($v, $k) {
- return isset($v['ESTADO']) && $v['ESTADO'] == 'VA';
- }, ARRAY_FILTER_USE_BOTH);
- // Si no hay objeto VA en el historial pero el estado es VA, significa que aún no se han asignado operarios
- if (empty($validatedHistoryFilt)) {
- $statusKey = $visit->RVTN_ESTA;
- $statusName = array_key_exists($statusKey, $visitStates) ? $visitStates[$statusKey] : $statusKey;
- return $this->responseController->makeResponse(true, "La visita tiene estado $statusName pero aún no ha asignado operarios.", [], 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);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getVisitStaff($idVisit, $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);
- }
- $idVisit = $this->encryptionController->decrypt($idVisit);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita relacionada no está encriptado correctamente', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $line],
- ['RVTN_IDVI', '=', $idVisit]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita relacionada no está registrada.', [], 404);
- }
- $staffArr = json_decode($visit->RVTN_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,
- ];
- }
- }
- }
- }
- }
- return $this->responseController->makeResponse(false, 'EXITO', $staffArr);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getVisitStatusHistory($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 visita solicitada no está encriptado correctamente', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->select([
- 'RVTN_HIES AS HISTORIAL',
- ])->where([
- ['RVTN_IDVI', '=', $idOrder],
- ['RVTN_NULI', '=', $line]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita solicitada no está registrada.', [], 404);
- }
- $visitStates = [
- 'PE' => 'Pendiente',
- 'CA' => 'Cancelado',
- 'RE' => 'Rechazado',
- 'EL' => 'Eliminado',
- 'VA' => 'Validado',
- 'EP' => 'En Proceso',
- 'CP' => 'Cerrado Pendiente',
- 'CE' => 'Cerrado'
- ];
- $statusHistoryArr = json_decode($visit->HISTORIAL, true);
- foreach ($statusHistoryArr as $key => $item) {
- $item['ESTADO'] = $visitStates[$item['ESTADO']];
- $usrSta = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $item['USUARIO']]
- ])->first();
- if (!is_null($usrSta)) {
- $usrStaName = $this->functionsController->joinName($usrSta->USUA_NOMB, $usrSta->USUA_APPA, $usrSta->USUA_APMA);
- $item['USUARIO'] = $usrStaName . " (" . $item['USUARIO'] . ")";
- } else {
- $item['USUARIO'] = "Usuario no encontrado (" . $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,
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- '-',
- 'Consulta',
- "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de estados de la visita #$idOrder de mantenimiento preventivo.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
- return $this->responseController->makeResponse(false, 'EXITO.', $statusHistoryArr);
- }
- // Visitas técnicas no programadas (Preventivas)
- public function attendPreventiveVisit(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);
- }
- $idVisit = $this->encryptionController->decrypt($form['id_order']);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
- } else if ($visit->RVTN_ESTA != 'VA') {
- return $this->responseController->makeResponse(true, 'La visita no está validada para atender.', [], 401);
- }
- // Validar datos según tipo de respuesta
- 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);
- }
- // Cupo global requerido (RVTN_PEIN)
- $planilla = json_decode($visit->RVTN_PEIN, true);
- $cupoRequerido = 0;
- if (!empty($planilla) && is_array($planilla)) {
- foreach ($planilla as $pe) {
- $cupoRequerido += intval($pe['CANT'] ?? 0);
- }
- }
- // Obtener historial de estados
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- // Buscar el último objeto con estado VA
- $vaStatusIndex = null;
- foreach ($statusHistoryArr as $index => $status) {
- if ($status['ESTADO'] == 'VA') {
- $vaStatusIndex = $index;
- }
- }
- if ($vaStatusIndex === null) {
- return $this->responseController->makeResponse(true, 'No se encontró un estado validado en el historial.', [], 404);
- }
- // Buscar el operario en el array ATENCION
- $operatorIndex = null;
- $atencionArr = $statusHistoryArr[$vaStatusIndex]['ATENCION'] ?? [];
- foreach ($atencionArr as $index => $invitacion) {
- if ($invitacion['ID'] == $idUser) {
- $operatorIndex = $index;
- break;
- }
- }
- if ($operatorIndex === null) {
- return $this->responseController->makeResponse(true, 'El usuario no está invitado a esta visita.', [], 401);
- }
- // Verificar si ya respondió
- if (!empty($atencionArr[$operatorIndex]['RESPUESTA'])) {
- $respuestaAnterior = $atencionArr[$operatorIndex]['RESPUESTA'] == 'A' ? 'aceptado' : 'rechazado';
- return $this->responseController->makeResponse(true, "Ya ha $respuestaAnterior esta invitación.", [], 401);
- }
- // Bloquear aceptación si la planilla ya está completa (con base en aceptados actuales)
- $aceptadosActual = 0;
- foreach ($atencionArr as $itm) {
- if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosActual++;
- }
- if ($form['attendance'] == 'A' && $cupoRequerido > 0 && $aceptadosActual >= $cupoRequerido) {
- return $this->responseController->makeResponse(true, 'La planilla ya está completa. No es posible aceptar esta invitación.', [], 401);
- }
- // Iniciar transacción
- DB::beginTransaction();
- try {
- $signature = null;
- $comments = null;
- if ($form['attendance'] == 'A') {
- // Procesar firma
- $filesPath = str_replace("app\\Http\\Controllers", "storage\\app\\files", __DIR__);
- if (!file_exists($filesPath)) {
- throw new \Exception('No se encontró la ubicación de almacenamiento de archivos.');
- }
- 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}" : "{$now->month}";
- $day = $now->day < 10 ? "0{$now->day}" : "{$now->day}";
- $fecr = substr("$year", -2) . $month . $day;
- $sec = DB::table('S002V01TAFAL')->where([
- ['AFAL_COMO', '=', "GMPR"],
- ['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', '=', "GMPR"],
- ['AFAL_CLDO', '=', "FO"],
- ['AFAL_NOAR', '=', $noar],
- ['AFAL_EXTE', '=', $exte],
- ])->orderBy('AFAL_NUVE', 'desc')->first();
- $nuve = 1;
- if (!is_null($ver)) {
- $nuve = intval($ver->AFAL_NUVE) + 1;
- }
- $tama = filesize($signatureFileDir);
- $code = intval($form['linea']) < 10 ? "0{$form['linea']}" : "{$form['linea']}";
- $code .= "-GMPR-FO-$fecr-";
- for ($i = strlen((string)$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' => "GMPR",
- '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'];
- }
- // Última verificación de cupo (concurrencia) antes de confirmar respuesta
- $statusHistoryCheck = json_decode(DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit]
- ])->value('RVTN_HIES'), true);
- $vaObjChk = null;
- if (!empty($statusHistoryCheck)) {
- for ($i = count($statusHistoryCheck) - 1; $i >= 0; $i--) {
- if ($statusHistoryCheck[$i]['ESTADO'] == 'VA') {
- $vaObjChk = $statusHistoryCheck[$i];
- break;
- }
- }
- }
- $aceptadosChk = 0;
- $atencionChk = $vaObjChk && array_key_exists('ATENCION', $vaObjChk) ? $vaObjChk['ATENCION'] : [];
- foreach ($atencionChk as $itm) {
- if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosChk++;
- }
- if ($form['attendance'] == 'A' && $cupoRequerido > 0 && $aceptadosChk >= $cupoRequerido) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'La planilla ya está completa. No es posible aceptar esta invitación.', [], 401);
- }
- // Actualizar el objeto en ATENCION
- $statusHistoryArr[$vaStatusIndex]['ATENCION'][$operatorIndex]['RESPUESTA'] = $form['attendance'];
- $statusHistoryArr[$vaStatusIndex]['ATENCION'][$operatorIndex]['FIRMA'] = $signature;
- $statusHistoryArr[$vaStatusIndex]['ATENCION'][$operatorIndex]['COMENTARIOS'] = $comments;
- $statusHistoryStr = json_encode($statusHistoryArr);
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- // Actualizar la visita
- DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $form['linea']],
- ['RVTN_IDVI', '=', $idVisit]
- ])->update([
- "RVTN_HIES" => $statusHistoryStr,
- "RVTN_USMO" => $idUser,
- "RVTN_FEMO" => $nowStr,
- ]);
- $userName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $action = $form['attendance'] == 'A' ? 'aceptó' : 'rechazó';
- // Preparar notificaciones
- $notificationActions = [];
- if ($form['attendance'] == 'A') {
- $notificationActions[] = [
- 'BOTON' => 'Revisar firma',
- 'FUNCION' => 'reviewSignatureInPreventiveVisit',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit), $this->encryptionController->encrypt($idUser)])
- ];
- } else if ($form['attendance'] == 'R') {
- $notificationActions[] = [
- 'BOTON' => 'Revisar comentarios',
- 'FUNCION' => 'reviewCommentsInPreventiveVisit',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit), $this->encryptionController->encrypt($idUser)])
- ];
- $notificationActions[] = [
- 'BOTON' => 'Reasignar visita',
- 'FUNCION' => 'revalidatePreventiveVisit',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ];
- }
- $notificationActions[] = [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ];
- // Notificar al regulador (usuario 0000000001)
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- "Visita de mantenimiento preventivo #$idVisit",
- "El usuario $userName ($idUser) $action atender la visita de mantenimiento preventivo #$idVisit.",
- $notificationActions,
- ['0000000001'],
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- $actions = DB::getQueryLog();
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Actualización',
- "El usuario $userName (" . $usr->USUA_IDUS . ") $action atender la visita preventiva #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- // Confirmar transacción
- DB::commit();
- return $this->responseController->makeResponse(false, 'EXITO');
- } catch (\Exception $e) {
- // Revertir transacción en caso de error
- DB::rollBack();
- $actions = DB::getQueryLog();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $userName = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Error',
- "Error al procesar la respuesta de la visita preventiva #$idVisit: " . $e->getMessage(),
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(
- true,
- 'Ocurrió un error al procesar la respuesta de la visita.',
- ['error' => $e->getMessage()],
- 500
- );
- }
- }
- 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';
- }
- }
|