PreventiveMaintenanceController.php 271 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Support\Carbon;
  7. use Illuminate\Support\Facades\Log;
  8. use Dompdf\Dompdf;
  9. use Illuminate\Support\Facades\Storage;
  10. use Illuminate\Http\File;
  11. use PhpOffice\PhpSpreadsheet\IOFactory;
  12. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  13. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  14. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  15. use ElephantIO\Client;
  16. class PreventiveMaintenanceController extends Controller{
  17. private $responseController;
  18. private $encryptionController;
  19. private $functionsController;
  20. private $templatesUbic;
  21. private $documentManagementController;
  22. private $notificationsController;
  23. public function __construct(){
  24. $this->responseController = new ResponseController();
  25. $this->encryptionController = new EncryptionController();
  26. $this->functionsController = new FunctionsController();
  27. $this->templatesUbic = $this->functionsController->getBasePath() . "\storage\app\public\pdf_templates\\01_03_GMPR\\";
  28. $this->documentManagementController = new DocumentManagementController();
  29. $this->notificationsController = new NotificationsController();
  30. }
  31. private function getSocketClient(){
  32. $url = 'http://localhost:3200';
  33. $socketClient = new Client(Client::engine(Client::CLIENT_4X, $url));
  34. $socketClient->initialize();
  35. $socketClient->of('/');
  36. return $socketClient;
  37. }
  38. public function registerWorkOrder(Request $request){
  39. DB::enableQueryLog();
  40. $validator = Validator::make($request->all(), [
  41. 'id_user' => 'required|string',
  42. 'linea' => 'required|integer',
  43. 'description' => 'required|string',
  44. 'instructions' => 'required|json',
  45. 'start_date' => 'required|date',
  46. 'start_hour' => 'required|string',
  47. 'end_date' => 'date',
  48. 'end_hour' => 'string',
  49. 'equipment' => 'required|string',
  50. 'inm_time' => 'required|numeric',
  51. 'total_time' => 'required|numeric',
  52. 'resources' => 'required|json',
  53. 'activator' => 'required|string',
  54. 'attached' => 'json',
  55. 'exists' => 'required|string|in:S,N',
  56. 'id_order' => 'required_if:exists,=,S|string',
  57. 'clasification' => 'required|string|max:100',
  58. 'staff' => 'required|json',
  59. ]);
  60. if($validator->fails()){
  61. return $this->responseController->makeResponse(
  62. true,
  63. "Se encontraron uno o más errores.",
  64. $this->responseController->makeErrors(
  65. $validator->errors()->messages()
  66. ),
  67. 401
  68. );
  69. }
  70. $form = $request->all();
  71. $idUser = $this->encryptionController->decrypt($form['id_user']);
  72. if(!$idUser){
  73. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  74. }
  75. $usr = DB::table('S002V01TUSUA')->where([
  76. ['USUA_NULI', '=', $form['linea']],
  77. ['USUA_IDUS', '=', $idUser]
  78. ])->first();
  79. if(is_null($usr)){
  80. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  81. }
  82. $resources = json_decode($form['resources'], true);
  83. if(empty($resources)){
  84. return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
  85. }
  86. foreach($resources as $key=>$item){
  87. if(!array_key_exists('ID', $item)){
  88. return $this->responseController->makeResponse(true, "No se pudo encontrar el ID del elemento en la posición $key del arreglo de recursos.", [], 400);
  89. }
  90. if($item['ID'] != 'SH'){
  91. $idItemDec = $this->encryptionController->decrypt($item['ID']);
  92. $resource = DB::table('S002V01TINST')->where([
  93. ['INST_NULI', '=', $form['linea']],
  94. ['INST_IDIS', '=', $idItemDec],
  95. ])->first();
  96. if(is_null($resource)){
  97. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de recursos no existe.", [], 404);
  98. }
  99. $item['ID'] = $idItemDec;
  100. }
  101. $resources[$key] = $item;
  102. }
  103. $rhre = json_encode($resources);
  104. $idActivator = $this->encryptionController->decrypt($form['activator']);
  105. if(!$idActivator){
  106. return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400);
  107. }
  108. $activator = DB::table('S002V01TACTI')->where([
  109. ['ACTI_NULI', '=', $form['linea']],
  110. ['ACTI_IDAC', '=', $idActivator]
  111. ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first();
  112. if(is_null($activator)){
  113. return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
  114. }
  115. $startDateTime = "$form[start_date] $form[start_hour]";
  116. $validStartDateTime = $this->functionsController->validateDate($startDateTime);
  117. if(!$validStartDateTime){
  118. return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400);
  119. }
  120. $dateTimeStart = new Carbon($startDateTime);
  121. if($activator->ACTI_TIAC == 'Calendario' || $activator->ACTI_TIAC == 'Sintoma'){
  122. $activatorConfig = json_decode($activator->ACTI_COAC, true);
  123. $activatorStartDate = explode('T', $activatorConfig['startDate'])[0];
  124. $activatorStartDateTime = "$activatorStartDate $activatorConfig[startHour]";
  125. $activatorStartDateTimeObj = new Carbon($activatorStartDateTime);
  126. if($dateTimeStart->lt($activatorStartDateTimeObj)){
  127. 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);
  128. }
  129. }
  130. $ftap = '0001-01-01 00:00:00';
  131. if(isset($form['end_hour'])){
  132. $endDateTime = "$form[end_date] $form[end_hour]";
  133. $validEndDateTime = $this->functionsController->validateDate($endDateTime);
  134. if(!$validEndDateTime){
  135. return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400);
  136. }
  137. $dateTimeEnd = new Carbon("$endDateTime");
  138. if($dateTimeStart->gt($dateTimeEnd)){
  139. return $this->responseController->makeResponse(true, 'La hora de término es menor a la hora de inicio.', [], 400);
  140. }
  141. $ftap = $dateTimeEnd->toDateTimeString();
  142. }
  143. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  144. if(!$equipmentCode){
  145. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
  146. }
  147. $equipment = DB::table('S002V01TEQUI')->where([
  148. ['EQUI_NULI', '=', $form['linea']],
  149. ['EQUI_COEQ', '=', $equipmentCode]
  150. ])->first();
  151. if(is_null($equipment)){
  152. return $this->responseController->makeResponse(true, 'El equipaiento seleccionado no existe.', [], 404);
  153. }else if($activator->CONA_COEQ != $equipmentCode){
  154. return $this->responseController->makeResponse(true, 'El activador seleccionado no puede ser asignado al equipamiento relacionado, ya que el contador pertenece a otro equipo.', [], 401);
  155. }else if(floatval($form['inm_time']) > floatval($form['total_time'])){
  156. return $this->responseController->makeResponse(true, 'El tiempo de inmovilización aproximado no puede ser mayor al tiempo de duración aproximada.', [], 400);
  157. }
  158. $staffArr = json_decode($form['staff'], true);
  159. if(empty($staffArr)){
  160. return $this->responseController->makeResponse(true, 'El JSON de personal está vacío.', [], 400);
  161. }
  162. $staff = [];
  163. foreach($staffArr as $key=>$specialty){
  164. $specialtyDec = $this->encryptionController->decrypt($specialty['SPECIALTY']);
  165. if(!$specialtyDec){
  166. return $this->responseController->makeResponse(true, "El código en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  167. }
  168. $specialtyObj = DB::table('S002V01TGEES')->where([
  169. ['GEES_NULI', '=', $form['linea']],
  170. ['GEES_COES', '=', $specialtyDec]
  171. ])->first();
  172. if(is_null($specialtyObj)){
  173. return $this->responseController->makeResponse(true, "El item en la posición $key del arreglo de especialidades no existe.", [], 404);
  174. }
  175. $staff[] = [
  176. 'ID' => $specialtyDec,
  177. 'CANT' => $specialty['CANT']
  178. ];
  179. }
  180. $instructionsArr = json_decode($form['instructions'], true);
  181. foreach($instructionsArr as $key=>$instruction){
  182. $instructionInd = $key + 1;
  183. $instructionStartArr = explode(' ', $instruction['INICIO']);
  184. if(count($instructionStartArr) != 3){
  185. return $this->responseController->makeResponse(true, "La fecha de inicio de la instrucción $instructionInd tiene un formato inválido.", [], 400);
  186. }
  187. $startHourArr = explode(':', $instructionStartArr[1]);
  188. $startHourInt = intval($startHourArr[0]);
  189. if($instructionStartArr[2] == 'PM' && $startHourInt < 12){
  190. $startHourInt = $startHourInt + 12;
  191. }
  192. $startOrigin = $instruction['INICIO'];
  193. $startHourStr = $startHourInt < 10 ? "0$startHourInt" : "$startHourInt";
  194. $instructionStartStr = "$startHourStr:$startHourArr[1]:00";
  195. $instruction['INICIO'] = "$instructionStartArr[0] $instructionStartStr";
  196. $instructionStartDateTime = new Carbon($instruction['INICIO']);
  197. if($instructionStartDateTime->lt($dateTimeStart)){
  198. 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);
  199. }
  200. $instructionEndArr = explode(' ', $instruction['FIN']);
  201. if(count($instructionEndArr) != 3){
  202. return $this->responseController->makeResponse(true, "La fecha de término de la instrucción $instructionInd tiene un formato inválido.", [], 400);
  203. }
  204. $endHourArr = explode(':', $instructionEndArr[1]);
  205. $endHourInt = intval($endHourArr[0]);
  206. if($instructionEndArr[2] == 'PM' && $endHourInt < 12){
  207. $endHourInt = $endHourInt + 12;
  208. }
  209. $endOrigin = $instruction['FIN'];
  210. $endHourStr = $endHourInt < 10 ? "0$endHourInt" : "$endHourInt";
  211. $instructionEndStr = "$endHourStr:$endHourArr[1]:00";
  212. $instruction['FIN'] = "$instructionEndArr[0] $instructionEndStr";
  213. if(isset($form['end_hour'])){
  214. $dateTimeEnd = new Carbon($ftap);
  215. $instructionEndDateTime = new Carbon($instruction['FIN']);
  216. if($instructionEndDateTime->gt($dateTimeEnd)){
  217. 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);
  218. }
  219. }
  220. $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']);
  221. $instruction['INICIO'] = $startOrigin;
  222. $instruction['FIN'] = $endOrigin;
  223. $instructionsArr[$key] = $instruction;
  224. }
  225. $inin = json_encode($instructionsArr);
  226. $oppr = json_encode($staff);
  227. $now = $this->functionsController->now();
  228. $nowStr = $now->toDateTimeString();
  229. $fiap = $dateTimeStart->toDateTimeString();
  230. $attachedArrFn = [];
  231. if(isset($form['attached'])){
  232. $attachedArr = json_decode($form['attached'], true);
  233. foreach($attachedArr as $key=>$attached){
  234. $idDec = $this->encryptionController->decrypt($attached['id']);
  235. if(!$idDec){
  236. return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
  237. }
  238. if($attached['type'] == 'Existente'){
  239. $codeArr = explode('=', $idDec);
  240. $codeArr0 = explode('-', $codeArr[0]);
  241. $file = DB::table('S002V01TAFAL')->where([
  242. ['AFAL_NULI', '=', $form['linea']],
  243. ['AFAL_COMO', '=', $codeArr0[1]],
  244. ['AFAL_CLDO', '=', $codeArr0[2]],
  245. ['AFAL_FECR', '=', $codeArr0[3]],
  246. ['AFAL_NUSE', '=', $codeArr0[4]],
  247. ['AFAL_NUVE', '=', $codeArr[1]],
  248. ])->first();
  249. if(is_null($file)){
  250. return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
  251. }else if($file->AFAL_ESTA == 'Eliminado'){
  252. return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
  253. }
  254. $attachedArrFn[] = $idDec;
  255. }else if($attached['type'] == 'Nuevo'){
  256. $tempFile = DB::table('S002V01TARTE')->where([
  257. ['ARTE_IDAR', '=', $idDec],
  258. ['ARTE_NULI', '=', $form['linea']]
  259. ])->first();
  260. if(is_null($tempFile)){
  261. return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
  262. }else if($tempFile->ARTE_ESTA == 'Eliminado'){
  263. return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
  264. }
  265. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMPR', 'OR', $tempFile, $idUser);
  266. if(!$finalFile){
  267. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  268. }else{
  269. $attachedArrFn[] = $finalFile[1];
  270. }
  271. }
  272. }
  273. }
  274. $done = json_encode($attachedArrFn);
  275. if($form['exists'] == 'S'){
  276. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  277. if(!$idOrder){
  278. return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
  279. }
  280. $order = DB::table('S002V01TOTPR')->where([
  281. ['OTPR_IDOT', '=', $idOrder],
  282. ['OTPR_NULI', '=', $form['linea']]
  283. ])->first();
  284. if(is_null($order)){
  285. return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404);
  286. }
  287. DB::table('S002V01TOTPR')->where([
  288. ['OTPR_IDOT', '=', $idOrder],
  289. ['OTPR_NULI', '=', $form['linea']]
  290. ])->update([
  291. 'OTPR_DEIN' => $form['description'],
  292. 'OTPR_ININ' => $inin,
  293. 'OTPR_EQIN' => $equipmentCode,
  294. 'OTPR_FIAP' => $fiap,
  295. 'OTPR_FTAP' => $ftap,
  296. 'OTPR_TIIN' => $form['inm_time'],
  297. 'OTPR_OPPR' => $oppr,
  298. 'OTPR_DTIN' => $form['total_time'],
  299. 'OTPR_RHRE' => $rhre,
  300. 'OTPR_DONE' => $done,
  301. 'OTPR_ACAS' => $idActivator,
  302. 'OTPR_CLAS' => $form['clasification'],
  303. 'OTPR_ESTA' => 'R',
  304. 'OTPR_USMO' => $idUser,
  305. 'OTPR_FEMO' => $nowStr,
  306. ]);
  307. }else{
  308. $idOrder = DB::table('S002V01TOTPR')->insertGetId([
  309. 'OTPR_NULI' => $form['linea'],
  310. 'OTPR_DEIN' => $form['description'],
  311. 'OTPR_ININ' => $inin,
  312. 'OTPR_EQIN' => $equipmentCode,
  313. 'OTPR_FIAP' => $fiap,
  314. 'OTPR_FTAP' => $ftap,
  315. 'OTPR_TIIN' => $form['inm_time'],
  316. 'OTPR_OPPR' => $oppr,
  317. 'OTPR_DTIN' => $form['total_time'],
  318. 'OTPR_RHRE' => $rhre,
  319. 'OTPR_DONE' => $done,
  320. 'OTPR_ACAS' => $idActivator,
  321. 'OTPR_CLAS' => $form['clasification'],
  322. 'OTPR_ESTA' => 'R',
  323. 'OTPR_USRE' => $idUser,
  324. 'OTPR_FERE' => $nowStr,
  325. ]);
  326. }
  327. $actions = DB::getQueryLog();
  328. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  329. $idac = $this->functionsController->registerActivity(
  330. $form['linea'],
  331. 'S002V01M10GMPR',
  332. 'S002V01F01COTP',
  333. 'S002V01P01ROTR',
  334. 'Registro',
  335. "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo #$idOrder.",
  336. $idUser,
  337. $nowStr,
  338. 'S002V01S01ORTR'
  339. );
  340. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  341. return $this->responseController->makeResponse(false, 'EXITO.');
  342. }
  343. public function getWorkOrders($idUser, $line){
  344. DB::enableQueryLog();
  345. $idUser = $this->encryptionController->decrypt($idUser);
  346. if(!$idUser){
  347. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  348. }
  349. $usr = DB::table('S002V01TUSUA')->where([
  350. ['USUA_NULI', '=', $line],
  351. ['USUA_IDUS', '=', $idUser],
  352. ])->first();
  353. if(is_null($usr)){
  354. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  355. }
  356. $workOrders = DB::table('S002V01TOTPR')->select([
  357. 'OTPR_IDOT AS IDORDEN',
  358. 'OTPR_EQIN AS EQUIPO',
  359. 'OTPR_FIAP AS FECHAINICIO',
  360. 'OTPR_FTAP AS FECHAFINAL',
  361. 'OTPR_ACAS AS ACTIVADOR',
  362. 'ACTI_TIAC AS TIPOACTIVADOR',
  363. 'ACTI_PRIO AS PRIORIDAD',
  364. 'OTPR_ESTA AS ESTATUS'
  365. ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')
  366. ->where('OTPR_NULI', '=', $line)
  367. ->orderBy('OTPR_IDOT', 'desc')->get()->all();
  368. foreach($workOrders as $key=>$order){
  369. $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
  370. $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO);
  371. $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR);
  372. if(!is_null($order->PRIORIDAD)){
  373. $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
  374. }
  375. if($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null;
  376. if($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null;
  377. $workOrders[$key] = $order;
  378. }
  379. $now = $this->functionsController->now();
  380. $nowStr = $now->toDateTimeString();
  381. $actions = DB::getQueryLog();
  382. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  383. $idac = $this->functionsController->registerActivity(
  384. $line,
  385. 'S002V01M10GMPR',
  386. 'S002V01F01COTP',
  387. 'S002V01P01HOTP',
  388. 'Consulta',
  389. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo registradas.",
  390. $idUser,
  391. $nowStr,
  392. 'S002V01S01ORTR'
  393. );
  394. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  395. return $this->responseController->makeResponse(false, 'EXITO.', $workOrders);
  396. }
  397. public function getWorkOrder($idOrder, $idUser, $line){
  398. DB::enableQueryLog();
  399. $idUser = $this->encryptionController->decrypt($idUser);
  400. if(!$idUser){
  401. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  402. }
  403. $usr = DB::table('S002V01TUSUA')->where([
  404. ['USUA_NULI', '=', $line],
  405. ['USUA_IDUS', '=', $idUser],
  406. ])->first();
  407. if(is_null($usr)){
  408. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  409. }
  410. $idOrder = $this->encryptionController->decrypt($idOrder);
  411. if(!$idOrder){
  412. return $this->responseController->makeResponse(true, 'El ID de la orden no está encriptado correctamente.', [], 400);
  413. }
  414. $workOrder = DB::table('S002V01TOTPR')->select([
  415. 'OTPR_IDOT AS IDORDEN',
  416. 'OTPR_DEIN AS DESCRIPCION',
  417. 'OTPR_ININ AS INSTRUCCIONES',
  418. 'OTPR_EQIN AS EQUIPAMIENTO',
  419. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  420. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  421. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  422. 'OTPR_FIAP AS FECHAINICIO',
  423. 'OTPR_FTAP AS FECHAFINAL',
  424. 'OTPR_SEAN AS ANALISIS',
  425. 'OTPR_TIIN AS TIEMPOINMOESTI',
  426. 'OTPR_CLAS AS CLASIFICACION',
  427. 'OTPR_OPPR AS OPERARIOS',
  428. 'OTPR_DTIN AS DURACIONTOTAL',
  429. 'OTPR_RHRE AS RECURSOS',
  430. 'OTPR_DONE AS DOCUMENTOS',
  431. 'OTPR_RECO AS CONTRATOS',
  432. 'OTPR_ACAS AS ACTIVADOR',
  433. 'ACTI_TIAC AS TIPOACTIVADOR',
  434. 'ACTI_PRIO AS PRIORIDAD',
  435. 'OTPR_ESTA AS ESTADO',
  436. 'OTPR_USRE AS USUARIOREGISTRA',
  437. 'OTPR_FERE AS FECHAREGISTRO',
  438. 'OTPR_USMO AS USUARIOMODIFICA',
  439. 'OTPR_FEMO AS FECHAMODIFICACION',
  440. ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')
  441. ->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  442. ['OTPR_IDOT', '=', $idOrder],
  443. ['OTPR_NULI', '=', $line],
  444. ])->first();
  445. if(is_null($workOrder)){
  446. return $this->responseController->makeResponse(true, 'La orden de trabajo consultada no existe.', [], 404);
  447. }
  448. $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN);
  449. $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO);
  450. $workOrder->ACTIVADOR = $this->encryptionController->encrypt($workOrder->ACTIVADOR);
  451. if(!is_null($workOrder->ID_EQUIPAMIENTO)){
  452. $workOrder->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->ID_EQUIPAMIENTO);
  453. }
  454. if(!is_null($workOrder->PRIORIDAD)){
  455. $workOrder->PRIORIDAD = $this->encryptionController->encrypt($workOrder->PRIORIDAD);
  456. }
  457. $workOrder->FECHAFINAL = $workOrder->FECHAFINAL == '0001-01-01 00:00:00' ? null : $workOrder->FECHAFINAL;
  458. $workOrder->FECHAINICIO = $workOrder->FECHAINICIO == '0001-01-01 00:00:00' ? null : $workOrder->FECHAINICIO;
  459. $instructionsArr = json_decode($workOrder->INSTRUCCIONES, true);
  460. foreach($instructionsArr as $key=>$instruction){
  461. $instruction['ID'] = $this->encryptionController->encrypt($instruction['ID']);
  462. $instructionsArr[$key] = $instruction;
  463. }
  464. $workOrder->INSTRUCCIONES = json_encode($instructionsArr);
  465. $staffArr = json_decode($workOrder->OPERARIOS, true);
  466. foreach($staffArr as $key=>$val){
  467. $specialty = DB::table('S002V01TGEES')->where([
  468. ['GEES_NULI', '=', $line],
  469. ['GEES_COES', '=', $val['ID']]
  470. ])->first();
  471. $val['ID'] = $this->encryptionController->encrypt($val['ID']);
  472. $val['NAME'] = $specialty->GEES_NOES;
  473. $staffArr[$key] = $val;
  474. }
  475. $workOrder->OPERARIOS = json_encode($staffArr);
  476. $resources = json_decode($workOrder->RECURSOS, true);
  477. foreach($resources as $key=>$resource){
  478. if($resource['ID'] != 'SH'){
  479. $resourceObj = DB::table('S002V01TINST')->where([
  480. ['INST_NULI', '=', $line],
  481. ['INST_IDIS', '=', $resource['ID']],
  482. ])->join('S002V01TSTAR', 'STAR_IDIS', '=', 'INST_IDIS')
  483. ->join('S002V01TUNID', 'UNID_IDUN', '=', 'STAR_IDUN')->first();
  484. if(!is_null($resourceObj)){
  485. $resource['NAME'] = $resourceObj->INST_MODE;
  486. $resource['UNIT'] = $resourceObj->UNID_NOMB;
  487. }
  488. $resource['ID'] = $this->encryptionController->encrypt($resource['ID']);
  489. }
  490. $resources[$key] = $resource;
  491. }
  492. $workOrder->RECURSOS = json_encode($resources);
  493. $documentsArr = json_decode($workOrder->DOCUMENTOS, true);
  494. $documentsFn = [];
  495. foreach($documentsArr as $document){
  496. $documentArr = explode('=', $document);
  497. $codeArr = explode('-', $documentArr[0]);
  498. $file = DB::table('S002V01TAFAL')->where([
  499. ['AFAL_NULI', '=', $line],
  500. ['AFAL_COMO', '=', $codeArr[1]],
  501. ['AFAL_CLDO', '=', $codeArr[2]],
  502. ['AFAL_FECR', '=', $codeArr[3]],
  503. ['AFAL_NUSE', '=', $codeArr[4]],
  504. ['AFAL_NUVE', '=', $documentArr[1]]
  505. ])->first();
  506. $documentsFn[] = [
  507. 'id' => $this->encryptionController->encrypt($document),
  508. 'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE,
  509. 'size' => $file->AFAL_TAMA,
  510. 'type' => 'Existente'
  511. ];
  512. }
  513. $workOrder->DOCUMENTOS = json_encode($documentsFn);
  514. if(!is_null($workOrder->ANALISIS)){
  515. $analysisArr = json_decode($workOrder->ANALISIS, true);
  516. $teamsConf = $analysisArr['teamsConf'];
  517. foreach($teamsConf as $key=>$val){
  518. $idEnc = $this->encryptionController->encrypt($val['ID']);
  519. $val['ID'] = $idEnc;
  520. $teamsConf[$key] = $val;
  521. }
  522. $analysisArr['teamsConf'] = $teamsConf;
  523. $workOrder->ANALISIS = json_encode($analysisArr);
  524. }
  525. $usrReg = DB::table('S002V01TUSUA')->where([
  526. ['USUA_NULI', '=', $line],
  527. ['USUA_IDUS', '=', $workOrder->USUARIOREGISTRA],
  528. ])->first();
  529. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  530. $workOrder->USUARIOREGISTRA = $nameReg . " (" . $workOrder->USUARIOREGISTRA . ")";
  531. if(!is_null($workOrder->USUARIOMODIFICA)){
  532. $usrMod = DB::table('S002V01TUSUA')->where([
  533. ['USUA_NULI', '=', $line],
  534. ['USUA_IDUS', '=', $workOrder->USUARIOMODIFICA],
  535. ])->first();
  536. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  537. $workOrder->USUARIOMODIFICA = $nameMod . " (" . $workOrder->USUARIOMODIFICA . ")";
  538. }
  539. $now = $this->functionsController->now();
  540. $nowStr = $now->toDateTimeString();
  541. $actions = DB::getQueryLog();
  542. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  543. $idac = $this->functionsController->registerActivity(
  544. $line,
  545. 'S002V01M10GMPR',
  546. 'S002V01F01COTP',
  547. 'S002V01P04COIN',
  548. 'Consulta',
  549. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la orden de trabajo #$idOrder.",
  550. $idUser,
  551. $nowStr,
  552. 'S002V01S01ORTR'
  553. );
  554. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  555. return $this->responseController->makeResponse(false, 'EXITO.', $workOrder);
  556. }
  557. public function executePreventiveWorkOrder(Request $request){
  558. DB::enableQueryLog();
  559. $validator = Validator::make($request->all(), [
  560. 'id_user' => 'required|string',
  561. 'linea' => 'required|integer',
  562. 'id_order' => 'required|string',
  563. 'configuration' => 'required|string',
  564. 'execution_date' => 'required|date'
  565. ]);
  566. if($validator->fails()){
  567. return $this->responseController->makeResponse(
  568. true,
  569. "Se encontraron uno o más errores.",
  570. $this->responseController->makeErrors(
  571. $validator->errors()->messages()
  572. ),
  573. 401
  574. );
  575. }
  576. $form = $request->all();
  577. $idUser = $this->encryptionController->decrypt($form['id_user']);
  578. if(!$idUser){
  579. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  580. }
  581. $usr = DB::table('S002V01TUSUA')->where([
  582. ['USUA_NULI', '=', $form['linea']],
  583. ['USUA_IDUS', '=', $idUser]
  584. ])->first();
  585. if(is_null($usr)){
  586. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  587. }
  588. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  589. if(!$idOrder){
  590. return $this->responseController->makeResponse(true, 'El ID de la orden seleccionada no fue encriptado correctamente.', [], 400);
  591. }
  592. $workOrder = DB::table('S002V01TOTPR')->where([
  593. ['OTPR_NULI', '=', $form['linea']],
  594. ['OTPR_IDOT', '=', $idOrder]
  595. ])->first();
  596. if(is_null($workOrder)){
  597. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  598. }else if($workOrder->OTPR_ESTA == 'Eliminado'){
  599. return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada.', [], 404);
  600. }
  601. $configurationStr = $this->encryptionController->decrypt($form['configuration']);
  602. if(!$configurationStr){
  603. return $this->responseController->makeResponse(true, 'La cadena de configuración no fue encriptada correctamente.', [], 400);
  604. }
  605. $configurationArr = json_decode($configurationStr, true);
  606. $staffArr = [];
  607. foreach($configurationArr as $key=>$value){
  608. $specialty = DB::table('S002V01TGEES')->where([
  609. ['GEES_NULI', '=', $form['linea']],
  610. ['GEES_COES', '=', $key]
  611. ])->first();
  612. if(!is_null($specialty)){
  613. $specialtyEmployees = [];
  614. foreach($value as $key0=>$value0){
  615. $idEmployeeDec = $this->encryptionController->decrypt($value0);
  616. if(!$idEmployeeDec){
  617. return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key no fue encriptado correctamente.", [], 400);
  618. }
  619. $employee = DB::table('S002V01TPERS')->where([
  620. ['PERS_NULI', '=', $form['linea']],
  621. ['PERS_IDPE', '=', $idEmployeeDec]
  622. ])->first();
  623. if(is_null($employee)){
  624. return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key no existe.", [], 404);
  625. }else if($employee->PERS_ESTA == 'Eliminado'){
  626. return $this->responseController->makeResponse(true, "El epmleado en la posición $key0 del arreglo de la especialidad $key está eliminado.", [], 404);
  627. }
  628. $specialtyEmployees[] = $idEmployeeDec;
  629. }
  630. $staffArr[$key] = $specialtyEmployees;
  631. }
  632. }
  633. $now = $this->functionsController->now();
  634. $nowStr = $now->toDateTimeString();
  635. $staffStr = json_encode($staffArr);
  636. $validExecutionDate = $this->functionsController->validateDate($form['execution_date']);
  637. if(!$validExecutionDate){
  638. return $this->responseController->makeResponse(true, 'La fecha de ejecución tiene un formato inválido.', [], 400);
  639. }
  640. $execDate = new Carbon($form['execution_date']);
  641. $fecIni = new Carbon($workOrder->OTPR_FIAP);
  642. if($fecIni->gt($execDate)){
  643. $tmp = $fecIni->toDateTimeString() . '|' . $execDate->toDateTimeString();
  644. return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.' . $tmp, [], 400);
  645. }
  646. $execDateStr = $execDate->toDateString();
  647. $execution = DB::table('S002V01TBEOT')->where([
  648. ['BEOT_NULI', '=', $form['linea']],
  649. ['BEOT_IDOT', '=', $form['id_order']],
  650. ['BEOT_FEPR', '=', $execDateStr]
  651. ])->first();
  652. if(!is_null($execution)){
  653. $estatus = $execution->BEOT_TIAC;
  654. if($estatus == 'Ejecucion'){
  655. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya fue realizada.", [], 401);
  656. }else if($estatus == 'Cancelacion'){
  657. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr fue cancelada.", [], 401);
  658. }else if($estatus == 'Finalizado'){
  659. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha finalizado.", [], 401);
  660. }
  661. }
  662. DB::table('S002V01TBEOT')->insert([
  663. 'BEOT_NULI' => $form['linea'],
  664. 'BEOT_IDOT' => $idOrder,
  665. 'BEOT_FEPR' => $execDateStr,
  666. 'BEOT_TIAC' => 'Ejecucion',
  667. 'BEOT_OPER' => $staffStr,
  668. 'BEOT_FEEJ' => $nowStr,
  669. 'BEOT_USEJ' => $idUser,
  670. ]);
  671. $actions = DB::getQueryLog();
  672. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  673. $idac = $this->functionsController->registerActivity(
  674. $form['linea'],
  675. 'S002V01M10GMPR',
  676. 'S002V01F02EMOT',
  677. '-',
  678. 'Registro',
  679. "El usuario $name (" . $usr->USUA_IDUS . ") ejecutó la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.",
  680. $idUser,
  681. $nowStr,
  682. 'S002V01S01ORTR'
  683. );
  684. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  685. return $this->responseController->makeResponse(false, 'EXITO.');
  686. }
  687. public function cancelWorkOrder(Request $request){
  688. //PENDIENTE REVISAR
  689. DB::enableQueryLog();
  690. $validator = Validator::make($request->all(), [
  691. 'id_user' => 'required|string',
  692. 'linea' => 'required|integer',
  693. 'id_order' => 'required|integer',
  694. 'execution_date' => 'required|date',
  695. 'observations' => 'required|string',
  696. ]);
  697. if($validator->fails()){
  698. return $this->responseController->makeResponse(
  699. true,
  700. "Se encontraron uno o más errores.",
  701. $this->responseController->makeErrors(
  702. $validator->errors()->messages()
  703. ),
  704. 401
  705. );
  706. }
  707. $form = $request->all();
  708. $idUser = $this->encryptionController->decrypt($form['id_user']);
  709. if(!$idUser){
  710. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  711. }
  712. $usr = DB::table('S002V01TUSUA')->where([
  713. ['USUA_NULI', '=', $form['linea']],
  714. ['USUA_IDUS', '=', $idUser]
  715. ])->first();
  716. if(is_null($usr)){
  717. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  718. }
  719. $workOrder = DB::table('S002V01TOTPR')->where([
  720. ['OTPR_NULI', '=', $form['linea']],
  721. ['OTPR_IDOT', '=', $form['id_order']]
  722. ])->first();
  723. if(is_null($workOrder)){
  724. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  725. }
  726. $execDate = new Carbon($form['execution_date']);
  727. $fecIni = new Carbon($workOrder->OTPR_FIAP);
  728. if($fecIni->gt($execDate)){
  729. return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.', [], 400);
  730. }
  731. $execDateStr = $execDate->toDateString();
  732. $execution = DB::table('S002V01TBEOT')->where([
  733. ['BEOT_NULI', '=', $form['linea']],
  734. ['BEOT_IDOT', '=', $form['id_order']],
  735. ['BEOT_FEPR', '=', $execDateStr]
  736. ])->first();
  737. if(!is_null($execution)){
  738. $estatus = $execution->BEOT_TIAC;
  739. if($estatus == 'Ejecucion'){
  740. 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);
  741. }else if($estatus == 'Finalizado'){
  742. 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);
  743. }else if($estatus == 'Cancelacion'){
  744. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha sido cancelada.", [], 401);
  745. }
  746. }
  747. $now = $this->functionsController->now();
  748. $nowStr = $now->toDateTimeString();
  749. DB::table('S002V01TBEOT')->insert([
  750. 'BEOT_NULI' => $form['linea'],
  751. 'BEOT_IDOT' => $form['id_order'],
  752. 'BEOT_FEPR' => $execDateStr,
  753. 'BEOT_TIAC' => 'Cancelacion',
  754. 'BEOT_OBSE' => $form['observations'],
  755. 'BEOT_FEEJ' => $nowStr,
  756. 'BEOT_USEJ' => $idUser,
  757. ]);
  758. $actions = DB::getQueryLog();
  759. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  760. $idac = $this->functionsController->registerActivity(
  761. $form['linea'],
  762. 'S002V01M10GMPR',
  763. 'S002V01F02EMOT',
  764. '-',
  765. 'Registro',
  766. "El usuario $name (" . $usr->USUA_IDUS . ") canceló la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.",
  767. $idUser,
  768. $nowStr,
  769. 'S002V01S01ORTR'
  770. );
  771. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  772. return $this->responseController->makeResponse(false, 'EXITO.');
  773. }
  774. public function deleteWorkOrder(Request $request){
  775. DB::enableQueryLog();
  776. $validator = Validator::make($request->all(), [
  777. 'id_user' => 'required|string',
  778. 'linea' => 'required|integer',
  779. 'id_order' => 'required|string',
  780. ]);
  781. if($validator->fails()){
  782. return $this->responseController->makeResponse(
  783. true,
  784. "Se encontraron uno o más errores.",
  785. $this->responseController->makeErrors(
  786. $validator->errors()->messages()
  787. ),
  788. 401
  789. );
  790. }
  791. $form = $request->all();
  792. $idUser = $this->encryptionController->decrypt($form['id_user']);
  793. if(!$idUser){
  794. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  795. }
  796. $usr = DB::table('S002V01TUSUA')->where([
  797. ['USUA_NULI', '=', $form['linea']],
  798. ['USUA_IDUS', '=', $idUser]
  799. ])->first();
  800. if(is_null($usr)){
  801. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  802. }
  803. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  804. if(!$idOrder){
  805. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no fue encriptado correctamente.', [], 400);
  806. }
  807. $workOrder = DB::table('S002V01TOTPR')->where([
  808. ['OTPR_NULI', '=', $form['linea']],
  809. ['OTPR_IDOT', '=', $idOrder]
  810. ])->first();
  811. if (is_null($workOrder)) {
  812. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  813. } else if ($workOrder->OTPR_ESTA == 'E') {
  814. return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada', [], 401);
  815. }
  816. $now = $this->functionsController->now();
  817. $nowStr = $now->toDateTimeString();
  818. DB::table('S002V01TOTPR')->where([
  819. ['OTPR_IDOT', '=', $idOrder],
  820. ['OTPR_NULI', '=', $form['linea']]
  821. ])->update([
  822. 'OTPR_ESTA' => 'E',
  823. 'OTPR_USMO' => $idUser,
  824. 'OTPR_FEMO' => $nowStr,
  825. ]);
  826. $actions = DB::getQueryLog();
  827. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  828. $idac = $this->functionsController->registerActivity(
  829. $form['linea'],
  830. 'S002V01M10GMPR',
  831. 'S002V01F04EOTP',
  832. '-',
  833. 'Eliminación',
  834. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo #$form[id_order].",
  835. $idUser,
  836. $nowStr,
  837. 'S002V01S01ORTR'
  838. );
  839. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  840. return $this->responseController->makeResponse(false, 'EXITO.');
  841. }
  842. public function updateWorkOrder(Request $request){
  843. //PENDIENTE ELIMINAR
  844. DB::enableQueryLog();
  845. $validator = Validator::make($request->all(), [
  846. 'id_user' => 'required|string',
  847. 'linea' => 'required|integer',
  848. 'id_order' => 'required|integer',
  849. 'title' => 'required|string',
  850. 'repeat' => 'required|json',
  851. 'start_date' => 'required|date',
  852. 'start_hour' => 'required|string',
  853. 'inm_time' => 'required|numeric',
  854. 'description' => 'required|string|max:100',
  855. 'clasification' => 'required|string|max:50',
  856. 'priority' => 'required|string|in:1,2,3',
  857. 'equipment' => 'required|string',
  858. 'analisis' => 'required|string',
  859. 'specialties' => 'required|json',
  860. 'attached' => 'json',
  861. ]);
  862. if($validator->fails()){
  863. return $this->responseController->makeResponse(
  864. true,
  865. "Se encontraron uno o más errores.",
  866. $this->responseController->makeErrors(
  867. $validator->errors()->messages()
  868. ),
  869. 401
  870. );
  871. }
  872. $form = $request->all();
  873. $idUser = $this->encryptionController->decrypt($form['id_user']);
  874. if(!$idUser){
  875. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  876. }
  877. $usr = DB::table('S002V01TUSUA')->where([
  878. ['USUA_NULI', '=', $form['linea']],
  879. ['USUA_IDUS', '=', $idUser]
  880. ])->first();
  881. if(is_null($usr)){
  882. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  883. }
  884. $workOrder = DB::table('S002V01TOTPR')->where([
  885. ['OTPR_NULI', '=', $form['linea']],
  886. ['OTPR_IDOT', '=', $form['id_order']]
  887. ])->first();
  888. if(is_null($workOrder)){
  889. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  890. }
  891. $repeArr = json_decode($form['repeat'], true);
  892. if(empty($repeArr)){
  893. return $this->responseController->makeResponse(true, 'El JSON de repetición tiene un formato inválido.', [], 400);
  894. }else if(!array_key_exists('type', $repeArr)){
  895. return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de repetición.', [], 400);
  896. }else if(!array_key_exists('config', $repeArr)){
  897. return $this->responseController->makeResponse(true, 'El campo config no fue enviado en el JSON de repetición.', [], 400);
  898. }
  899. $hourArr = explode(' ', $form['start_hour']);
  900. $timeArr = '';
  901. if(count($hourArr) < 2){
  902. return $this->responseController->makeResponse(true, 'La hora de inicio tiene un formato inválido.', [], 400);
  903. }else if($hourArr[1] == 'PM'){
  904. $hour = explode(':', $hourArr[0]);
  905. $h = intval($hour[0]);
  906. if($h != 12){
  907. $h = $h + 12;
  908. }
  909. $hourStr = "$h:$hour[1]:00";
  910. $timeArr .= " $hourStr";
  911. }else if($hourArr[1] == 'AM'){
  912. $hour = explode(':', $hourArr[0]);
  913. $h = intval($hour[0]);
  914. $hStr = $h < 10 ? "0$h" : "$h";
  915. $hStr .= ":$hour[1]:00";
  916. $timeArr .= " $hStr";
  917. }else{
  918. return $this->responseController->makeResponse(true, 'No se pudo determinar el periodo del horario.', [], 400);
  919. }
  920. $specialtiesArr = json_decode($form['specialties'], true);
  921. if(empty($specialtiesArr)){
  922. return $this->responseController->makeResponse(true, 'El JSON de especialidades tiene un formato inválido.', [], 400);
  923. }
  924. foreach($specialtiesArr as $specialty){
  925. if(!array_key_exists('specialty', $specialty)){
  926. return $this->responseController->makeResponse(true, 'El campo specialty no fue enviado en el JSON de especialidad.', [], 400);
  927. }else if(!array_key_exists('type', $specialty)){
  928. return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de especialidad.', [], 400);
  929. }else if(!array_key_exists('staff', $specialty)){
  930. return $this->responseController->makeResponse(true, 'El campo staff no fue enviado en el JSON de especialidad.', [], 400);
  931. }
  932. }
  933. $now = $this->functionsController->now();
  934. $nowStr = $now->toDateTimeString();
  935. $documents = isset($form['attached']) ? $form['attached'] : null;
  936. DB::table('S002V01TOTPR')->where([
  937. ['OTPR_IDOT', '=', $form['id_order']],
  938. ['OTPR_NULI', '=', $form['linea']],
  939. ])->update([
  940. 'OTPR_TIOR' => $form['title'],
  941. 'OTPR_REPE' => $form['repeat'],
  942. 'OTPR_FIIN' => $form['start_date'],
  943. 'OTPR_HIIN' => $timeArr,
  944. 'OTPR_TIES' => $form['inm_time'],
  945. 'OTPR_DEIN' => $form['description'],
  946. 'OTPR_ANIN' => $form['analisis'],
  947. 'OTPR_CEIN' => $form['equipment'],
  948. 'OTPR_PERE' => $form['specialties'],
  949. 'OTPR_CLAS' => $form['clasification'],
  950. 'OTPR_PRIO' => $form['priority'],
  951. 'OTPR_DONE' => $documents,
  952. 'OTPR_USRE' => $idUser,
  953. 'OTPR_FERE' => $nowStr,
  954. ]);
  955. $actions = DB::getQueryLog();
  956. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  957. $idac = $this->functionsController->registerActivity(
  958. $form['linea'],
  959. 'S002V01M10GMPR',
  960. 'S002V01F01COTP',
  961. 'S002V01P01ROTR',
  962. 'Actualización',
  963. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo $form[title] ($form[id_order]).",
  964. $idUser,
  965. $nowStr,
  966. 'S002V01S01ORTR'
  967. );
  968. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  969. return $this->responseController->makeResponse(false, 'EXITO.');
  970. }
  971. public function geStartedtWorkOrders($idUser, $line){
  972. //PENDIENTE REVISAR
  973. DB::enableQueryLog();
  974. $idUser = $this->encryptionController->decrypt($idUser);
  975. if(!$idUser){
  976. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  977. }
  978. $usr = DB::table('S002V01TUSUA')->where([
  979. ['USUA_NULI', '=', $line],
  980. ['USUA_IDUS', '=', $idUser]
  981. ])->first();
  982. if(is_null($usr)){
  983. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  984. }
  985. $startedWorkOrders = DB::table('S002V01TBEOT')->select([
  986. 'BEOT_IDRE AS IDREGISTRO',
  987. 'BEOT_IDOT AS IDORDEN',
  988. 'BEOT_FEPR AS FECHAPROGRAMA',
  989. 'BEOT_FEEJ AS FECHAEJECUCION',
  990. 'BEOT_USEJ AS USUARIOEJECUCION',
  991. 'BEOT_TIAC AS ESTADO',
  992. 'OTPR_TIOR AS TITULOORDEN',
  993. 'OTPR_HIIN AS HORAPROGRAMA',
  994. 'OTPR_TIES AS TIEMPOESTIMADO',
  995. 'OTPR_PRIO AS PRIORIDAD',
  996. ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')->where([
  997. ['BEOT_NULI', '=', $line],
  998. ])->get()->all();
  999. foreach($startedWorkOrders as $workOrder){
  1000. $usrEje = DB::table('S002V01TUSUA')->where([
  1001. ['USUA_NULI', '=', $line],
  1002. ['USUA_IDUS', '=', $workOrder->USUARIOEJECUCION]
  1003. ])->first();
  1004. $nameEje = $this->functionsController->joinName($usrEje->USUA_NOMB, $usrEje->USUA_APPA, $usrEje->USUA_APMA);
  1005. $workOrder->USUARIOEJECUCION = $nameEje . " (" . $workOrder->USUARIOEJECUCION . ")";
  1006. }
  1007. $now = $this->functionsController->now();
  1008. $nowStr = $now->toDateTimeString();
  1009. $actions = DB::getQueryLog();
  1010. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1011. $idac = $this->functionsController->registerActivity(
  1012. $line,
  1013. 'S002V01M10GMPR',
  1014. 'S002V01F05BEOT',
  1015. 'S002V01P01HOEJ',
  1016. 'Consulta',
  1017. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo en ejecución.",
  1018. $idUser,
  1019. $nowStr,
  1020. 'S002V01S01ORTR'
  1021. );
  1022. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1023. return $this->responseController->makeResponse(false, 'EXITO.', $startedWorkOrders);
  1024. }
  1025. public function endOrderExecution(Request $request){
  1026. DB::enableQueryLog();
  1027. $validator = Validator::make($request->all(), [
  1028. 'id_user' => 'required|string',
  1029. 'linea' => 'required|integer',
  1030. 'id_order' => 'required|integer',
  1031. 'id_reg' => 'required|integer',
  1032. 'observations' => 'required|string|min:15',
  1033. ]);
  1034. if($validator->fails()){
  1035. return $this->responseController->makeResponse(
  1036. true,
  1037. "Se encontraron uno o más errores.",
  1038. $this->responseController->makeErrors(
  1039. $validator->errors()->messages()
  1040. ),
  1041. 401
  1042. );
  1043. }
  1044. $form = $request->all();
  1045. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1046. if(!$idUser){
  1047. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1048. }
  1049. $usr = DB::table('S002V01TUSUA')->where([
  1050. ['USUA_NULI', '=', $form['linea']],
  1051. ['USUA_IDUS', '=', $idUser]
  1052. ])->first();
  1053. if(is_null($usr)){
  1054. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1055. }
  1056. $workOrder = DB::table('S002V01TOTPR')->where([
  1057. ['OTPR_NULI', '=', $form['linea']],
  1058. ['OTPR_IDOT', '=', $form['id_order']]
  1059. ])->first();
  1060. if(is_null($workOrder)){
  1061. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  1062. }
  1063. $register = DB::table('S002V01TBEOT')->where([
  1064. ['BEOT_NULI', '=', $form['linea']],
  1065. ['BEOT_IDRE', '=', $form['id_reg']],
  1066. ['BEOT_IDOT', '=', $form['id_order']]
  1067. ])->first();
  1068. if(is_null($register)){
  1069. return $this->responseController->makeResponse(true, 'El registro solicitado no existe', [], 404);
  1070. }else if($register->BEOT_TIAC == 'Cancelacion'){
  1071. return $this->responseController->makeResponse(true, 'El registro solicitado fue cancelado', [], 401);
  1072. }else if($register->BEOT_TIAC == 'Finalizado'){
  1073. return $this->responseController->makeResponse(true, 'El registro solicitado ya fue finalizado', [], 401);
  1074. }
  1075. $now = $this->functionsController->now();
  1076. $executionDate = new Carbon($register->BEOT_FEEJ);
  1077. $diff = $now->diffInMilliseconds($executionDate); //Milisegundos
  1078. $diff = $diff / 1000; //Segundos
  1079. $diff = $diff / 60; //Minutos
  1080. $diff = $diff / 60; //Horas
  1081. $nowStr = $now->toDateTimeString();
  1082. DB::table('S002V01TBEOT')->where([
  1083. ['BEOT_NULI', '=', $form['linea']],
  1084. ['BEOT_IDRE', '=', $form['id_reg']],
  1085. ['BEOT_IDOT', '=', $form['id_order']]
  1086. ])->update([
  1087. "BEOT_TIAC" => 'Finalizado',
  1088. "BEOT_DTEJ" => $diff,
  1089. "BEOT_OBSE" => $form['observations'],
  1090. "BEOT_FEFI" => $nowStr,
  1091. "BEOT_USFI" => $idUser,
  1092. ]);
  1093. $actions = DB::getQueryLog();
  1094. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1095. $idac = $this->functionsController->registerActivity(
  1096. $form['linea'],
  1097. 'S002V01M10GMPR',
  1098. 'S002V01F05SEOR',
  1099. '-',
  1100. 'Actualización',
  1101. "El usuario $name (" . $usr->USUA_IDUS . ") finalizó la ejecución del día ". $register->BEOT_FEPR ." de la orden #$form[id_order].",
  1102. $idUser,
  1103. $nowStr,
  1104. 'S002V01S02AOTR'
  1105. );
  1106. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1107. return $this->responseController->makeResponse(false, 'EXITO.');
  1108. }
  1109. public function getExecRegister($date, $idRegister, $idUser, $line){
  1110. DB::enableQueryLog();
  1111. $idUser = $this->encryptionController->decrypt($idUser);
  1112. if(!$idUser){
  1113. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  1114. }
  1115. $usr = DB::table('S002V01TUSUA')->where([
  1116. ['USUA_NULI', '=', $line],
  1117. ['USUA_IDUS', '=', $idUser],
  1118. ])->first();
  1119. if(is_null($usr)){
  1120. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  1121. }
  1122. $idRegister = $this->encryptionController->decrypt($idRegister);
  1123. if(!$idRegister){
  1124. return $this->responseController->makeResponse(true, 'El ID de la orden relacionada no fue encriptado correctamente.', [], 400);
  1125. }
  1126. $dateArr = explode('|', $date);
  1127. $workOrder = null;
  1128. if(count($dateArr) == 2){
  1129. if($dateArr[1] == 'O'){
  1130. $workOrder = DB::table('S002V01TOTPR')->select(
  1131. 'OTPR_IDOT AS IDORDEN',
  1132. 'OTPR_DEIN AS DESCRIPCION',
  1133. DB::raw("CONCAT(
  1134. OTPR_EQIN, ' - ',
  1135. EQUI_TIPO, ' - ',
  1136. EQUI_MODE, ' (',
  1137. EQUI_IDEQ, ')'
  1138. ) AS EQUIPAMIENTO"),
  1139. 'OTPR_FIAP AS FECHAINICIO',
  1140. DB::raw("'Programada' AS ESTADODEEJECUCION"),
  1141. DB::raw("'-' AS IDREG"),
  1142. DB::raw("NULL AS OBSERVACIONES"),
  1143. DB::raw("NULL AS OPERARIOS"),
  1144. )->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([
  1145. ['OTPR_NULI', '=', $line],
  1146. ['OTPR_IDOT', '=', $idRegister],
  1147. ])->first();
  1148. }else{
  1149. $validDate = $this->functionsController->validDate($dateArr[0]);
  1150. if(!$validDate){
  1151. return $this->responseController->makeResponse(true, 'La fecha de ejecución enviada tiene un formato inválido.', [], 400);
  1152. }
  1153. $workOrder = DB::table('S002V01TBEOT')->select([
  1154. 'BEOT_IDOT AS IDORDEN',
  1155. 'OTPR_DEIN AS DESCRIPCION',
  1156. DB::raw("CONCAT(
  1157. OTPR_EQIN, ' - ',
  1158. EQUI_TIPO, ' - ',
  1159. EQUI_MODE, ' (',
  1160. EQUI_IDEQ, ')'
  1161. ) AS EQUIPAMIENTO"),
  1162. 'OTPR_FIAP AS FECHAINICIO',
  1163. 'BEOT_TIAC AS ESTADODEEJECUCION',
  1164. 'BEOT_IDRE AS IDREG',
  1165. 'BEOT_OBSE AS OBSERVACIONES',
  1166. 'BEOT_OPER AS OPERARIOS'
  1167. ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')
  1168. ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([
  1169. ['BEOT_NULI', '=', $line],
  1170. ['BEOT_IDOT', '=', $idRegister],
  1171. ['BEOT_FEPR', '=', $dateArr[0]],
  1172. ])->first();
  1173. }
  1174. }else{
  1175. $workOrder = DB::table('S002V01TBEOT')->select([
  1176. 'BEOT_IDOT AS IDORDEN',
  1177. 'OTPR_DEIN AS DESCRIPCION',
  1178. DB::raw("CONCAT(
  1179. OTPR_EQIN, ' - ',
  1180. EQUI_TIPO, ' - ',
  1181. EQUI_MODE, ' (',
  1182. EQUI_IDEQ, ')'
  1183. ) AS EQUIPAMIENTO"),
  1184. 'OTPR_FIAP AS FECHAINICIO',
  1185. 'BEOT_TIAC AS ESTADODEEJECUCION',
  1186. 'BEOT_IDRE AS IDREG',
  1187. 'BEOT_OBSE AS OBSERVACIONES',
  1188. 'BEOT_OPER AS OPERARIOS'
  1189. ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')
  1190. ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')->where([
  1191. ['BEOT_NULI', '=', $line],
  1192. ['BEOT_IDRE', '=', $idRegister],
  1193. ])->first();
  1194. }
  1195. if(is_null($workOrder)){
  1196. return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404);
  1197. }
  1198. $idOrder = $workOrder->IDORDEN;
  1199. $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN);
  1200. $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO);
  1201. $workOrder->IDREG = $this->encryptionController->encrypt($workOrder->IDREG);
  1202. if(!is_null($workOrder->OPERARIOS)){
  1203. $staffArr = json_decode($workOrder->OPERARIOS);
  1204. $staffArrFn = [];
  1205. foreach($staffArr as $key=>$val){
  1206. $specialtyObj = DB::table('S002V01TGEES')->where([
  1207. ['GEES_NULI', '=', $line],
  1208. ['GEES_COES', '=', $key]
  1209. ])->first();
  1210. $specialtyConf = [];
  1211. if(!is_null($specialtyObj)){
  1212. $specialtyConf['CODIGO_ESPECIALIDAD'] = $this->encryptionController->encrypt($specialtyObj->GEES_COES);
  1213. $specialtyConf['NOMBRE_ESPECIALIDAD'] = $specialtyObj->GEES_NOES;
  1214. $staff = [];
  1215. foreach($val as $val0){
  1216. $employee = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
  1217. ['PERS_NULI', '=', $line],
  1218. ['PERS_IDPE', '=', $val0]
  1219. ])->first();
  1220. $employeeObj = [
  1221. 'ID_EMPLEADO' => $this->encryptionController->encrypt($employee->PERS_IDPE),
  1222. 'ID_USUARIO' => $this->encryptionController->encrypt($employee->USUA_IDUS),
  1223. 'NOMBRE_EMPLEADO' => $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA),
  1224. 'TIPO_EMPLEADO' => $employee->PERS_TICO
  1225. ];
  1226. $staff[] = $employeeObj;
  1227. }
  1228. $specialtyConf['OPERARIOS'] = $staff;
  1229. }
  1230. $staffArrFn[] = $specialtyConf;
  1231. }
  1232. $workOrder->OPERARIOS = $staffArrFn;
  1233. }
  1234. $now = $this->functionsController->now();
  1235. $nowStr = $now->toDateTimeString();
  1236. $actions = DB::getQueryLog();
  1237. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1238. $idac = $this->functionsController->registerActivity(
  1239. $line,
  1240. 'S002V01M10GMPR',
  1241. 'S002V01F08VCPR',
  1242. '-',
  1243. 'Consulta',
  1244. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el estado de la ejecución de la orden #" . $idOrder . " para la fecha $date.",
  1245. $idUser,
  1246. $nowStr,
  1247. 'S002V01S02AOTR'
  1248. );
  1249. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1250. return $this->responseController->makeResponse(false, 'EXITO.', $workOrder);
  1251. }
  1252. public function copyWorkOrder(Request $request){
  1253. DB::enableQueryLog();
  1254. $validator = Validator::make($request->all(), [
  1255. 'id_user' => 'required|string',
  1256. 'linea' => 'required|integer',
  1257. 'id_order' => 'required|string',
  1258. 'equipment' => 'required|string',
  1259. ]);
  1260. if($validator->fails()){
  1261. return $this->responseController->makeResponse(
  1262. true,
  1263. "Se encontraron uno o más errores.",
  1264. $this->responseController->makeErrors(
  1265. $validator->errors()->messages()
  1266. ),
  1267. 401
  1268. );
  1269. }
  1270. $form = $request->all();
  1271. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1272. if(!$idUser){
  1273. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1274. }
  1275. $usr = DB::table('S002V01TUSUA')->where([
  1276. ['USUA_NULI', '=', $form['linea']],
  1277. ['USUA_IDUS', '=', $idUser],
  1278. ])->first();
  1279. if(is_null($usr)){
  1280. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1281. }
  1282. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  1283. if(!$idOrder){
  1284. return $this->responseController->makeResponse(true, 'El ID de la orden que desea copiar no fue encriptado correctamente.', [], 400);
  1285. }
  1286. $workOrder = DB::table('S002V01TOTPR')->where([
  1287. ['OTPR_NULI', '=', $form['linea']],
  1288. ['OTPR_IDOT', '=', $idOrder]
  1289. ])->first();
  1290. if(is_null($workOrder)){
  1291. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  1292. }
  1293. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  1294. if(!$equipmentCode){
  1295. return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400);
  1296. }
  1297. $equipment = DB::table('S002V01TEQUI')->where([
  1298. ['EQUI_NULI', '=', $form['linea']],
  1299. ['EQUI_COEQ', '=', $equipmentCode],
  1300. ])->first();
  1301. if(is_null($equipment)){
  1302. return $this->responseController->makeResponse(true, 'El equipamiento seleccionado no existe.', [], 404);
  1303. }else if($equipmentCode == $workOrder->OTPR_EQIN){
  1304. return $this->responseController->makeResponse(true, 'El equipo seleccionado es igual al de la orden copiada.', [], 400);
  1305. }
  1306. $now = $this->functionsController->now();
  1307. $nowStr = $now->toDateTimeString();
  1308. $idOrderNew = DB::table('S002V01TOTPR')->insertGetId([
  1309. "OTPR_NULI" => $form['linea'],
  1310. "OTPR_DEIN" => $workOrder->OTPR_DEIN,
  1311. "OTPR_ININ" => $workOrder->OTPR_ININ,
  1312. "OTPR_EQIN" => $equipmentCode,
  1313. "OTPR_FIAP" => $workOrder->OTPR_FIAP,
  1314. "OTPR_FTAP" => $workOrder->OTPR_FTAP,
  1315. "OTPR_SEAN" => $workOrder->OTPR_SEAN,
  1316. "OTPR_TIIN" => $workOrder->OTPR_TIIN,
  1317. "OTPR_OPPR" => $workOrder->OTPR_OPPR,
  1318. "OTPR_DTIN" => $workOrder->OTPR_DTIN,
  1319. "OTPR_RHRE" => $workOrder->OTPR_RHRE,
  1320. "OTPR_DONE" => '[]',
  1321. "OTPR_RECO" => $workOrder->OTPR_RECO,
  1322. "OTPR_ACAS" => $workOrder->OTPR_ACAS,
  1323. "OTPR_CLAS" => $workOrder->OTPR_CLAS,
  1324. "OTPR_ESTA" => 'R',
  1325. "OTPR_USRE" => $idUser,
  1326. "OTPR_FERE" => $nowStr,
  1327. ]);
  1328. $actions = DB::getQueryLog();
  1329. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1330. $idac = $this->functionsController->registerActivity(
  1331. $form['linea'],
  1332. 'S002V01M10GMPR',
  1333. 'S002V01F06COVE',
  1334. '-',
  1335. 'Registro',
  1336. "El usuario $name (" . $usr->USUA_IDUS . ") copió la orden #$idOrder para el equipamiento $equipmentCode dentro de la orden #$idOrderNew.",
  1337. $idUser,
  1338. $nowStr,
  1339. 'S002V01S01ORTR'
  1340. );
  1341. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1342. return $this->responseController->makeResponse(false, 'EXITO.');
  1343. }
  1344. public function savePresetWorkOrder(Request $request){
  1345. DB::enableQueryLog();
  1346. $validator = Validator::make($request->all(), [
  1347. 'id_user' => 'required|string',
  1348. 'linea' => 'required|integer',
  1349. 'exists' => 'required|string|in:S,N',
  1350. 'id_order' => 'required_if:exists,=,S|string',
  1351. 'description' => 'required|string',
  1352. 'instructions' => 'required|string',
  1353. 'start_date' => 'required|string',
  1354. 'start_hour' => 'required|string',
  1355. 'end_date' => 'required|string',
  1356. 'end_hour' => 'required|string',
  1357. 'equipment' => 'required|string',
  1358. 'inm_time' => 'required|string',
  1359. 'total_time' => 'required|string',
  1360. 'staff' => 'required|string',
  1361. 'attached' => 'required|string',
  1362. 'activator_type' => 'required|string',
  1363. 'activator' => 'required|string',
  1364. 'clasification' => 'required|string|max:100',
  1365. 'resources' => 'required|json',
  1366. ]);
  1367. if($validator->fails()){
  1368. return $this->responseController->makeResponse(
  1369. true,
  1370. "Se encontraron uno o más errores.",
  1371. $this->responseController->makeErrors(
  1372. $validator->errors()->messages()
  1373. ),
  1374. 401
  1375. );
  1376. }
  1377. $form = $request->all();
  1378. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1379. if(!$idUser){
  1380. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1381. }
  1382. $usr = DB::table('S002V01TUSUA')->where([
  1383. ['USUA_NULI', '=', $form['linea']],
  1384. ['USUA_IDUS', '=', $idUser],
  1385. ])->first();
  1386. if(is_null($usr)){
  1387. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1388. }
  1389. $acas = '0';
  1390. if($form['activator'] != '-'){
  1391. $idActivator = $this->encryptionController->decrypt($form['activator']);
  1392. if(!$idActivator){
  1393. return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400);
  1394. }
  1395. $activator = DB::table('S002V01TACTI')->where([
  1396. ['ACTI_NULI', '=', $form['linea']],
  1397. ['ACTI_IDAC', '=', $idActivator]
  1398. ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first();
  1399. if(is_null($activator)){
  1400. return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
  1401. }
  1402. $acas = $idActivator;
  1403. }
  1404. $rhre = '[]';
  1405. if($form['resources'] != '[]'){
  1406. $resources = json_decode($form['resources'], true);
  1407. if(empty($resources)){
  1408. return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
  1409. }
  1410. foreach($resources as $key=>$item){
  1411. if(!array_key_exists('ID', $item)){
  1412. return $this->responseController->makeResponse(true, "No se pudo encontrar el ID del elemento en la posición $key del arreglo de recursos.", [], 400);
  1413. }
  1414. if($item['ID'] != 'SH'){
  1415. $idItemDec = $this->encryptionController->decrypt($item['ID']);
  1416. $resource = DB::table('S002V01TINST')->where([
  1417. ['INST_NULI', '=', $form['linea']],
  1418. ['INST_IDIS', '=', $idItemDec],
  1419. ])->first();
  1420. if(is_null($resource)){
  1421. return $this->responseController->makeResponse(true, "El elemento en la posición $key del arreglo de recursos no existe.", [], 404);
  1422. }
  1423. $item['ID'] = $idItemDec;
  1424. }
  1425. $resources[$key] = $item;
  1426. }
  1427. $rhre = json_encode($resources);
  1428. }
  1429. $startDateTime = '0001-01-01 00:00:00';
  1430. if($form['start_date'] != '-' && $form['start_hour'] != '-'){
  1431. $startDateTime = "$form[start_date] $form[start_hour]";
  1432. $validStartDateTime = $this->functionsController->validateDate($startDateTime);
  1433. if(!$validStartDateTime){
  1434. return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400);
  1435. }
  1436. }
  1437. $endDateTime = '0001-01-01 00:00:00';
  1438. if($form['end_date'] != '-' && $form['end_hour'] != '-'){
  1439. $endDateTime = "$form[end_date] $form[end_hour]";
  1440. $validEndDateTime = $this->functionsController->validateDate($endDateTime);
  1441. if(!$validEndDateTime){
  1442. return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400);
  1443. }
  1444. }
  1445. $now = $this->functionsController->now();
  1446. $nowStr = $now->toDateTimeString();
  1447. $dein = $form['description'];
  1448. $eqin = '-';
  1449. if($form['equipment'] != '-'){
  1450. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  1451. if(!$equipmentCode){
  1452. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
  1453. }
  1454. $equipment = DB::table('S002V01TEQUI')->where([
  1455. ['EQUI_NULI', '=', $form['linea']],
  1456. ['EQUI_COEQ', '=', $equipmentCode]
  1457. ])->first();
  1458. if(is_null($equipment)){
  1459. return $this->responseController->makeResponse(true, 'El equipaiento seleccionado no existe.', [], 404);
  1460. }
  1461. $eqin = $equipmentCode;
  1462. }
  1463. $tiin = $form['inm_time'] == '-' ? 0 : floatval($form['inm_time']);
  1464. $dtin = $form['total_time'] == '-' ? 0 : floatval($form['total_time']);
  1465. $staffArr = json_decode($form['staff'], true);
  1466. $staff = [];
  1467. if($form['staff'] != '-' && !empty($staffArr)){
  1468. $staffArr = json_decode($form['staff'], true);
  1469. foreach($staffArr as $key=>$specialty){
  1470. $specialtyDec = $this->encryptionController->decrypt($specialty['SPECIALTY']);
  1471. if(!$specialtyDec){
  1472. return $this->responseController->makeResponse(true, "El código en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  1473. }
  1474. $specialtyObj = DB::table('S002V01TGEES')->where([
  1475. ['GEES_NULI', '=', $form['linea']],
  1476. ['GEES_COES', '=', $specialtyDec]
  1477. ])->first();
  1478. if(is_null($specialtyObj)){
  1479. return $this->responseController->makeResponse(true, "El item en la posición $key del arreglo de especialidades no existe.", [], 404);
  1480. }
  1481. $staff[] = [
  1482. 'ID' => $specialtyDec,
  1483. 'CANT' => $specialty['CANT']
  1484. ];
  1485. }
  1486. }
  1487. $oppr = json_encode($staff);
  1488. $clas = $form['clasification'];
  1489. $inin = '[]';
  1490. if ($form['instructions'] != '-') {
  1491. $instructions = json_decode($form['instructions'], true);
  1492. foreach ($instructions as $key => $instruction) {
  1493. $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']);
  1494. $instructions[$key] = $instruction;
  1495. }
  1496. $inin = json_encode($instructions);
  1497. }
  1498. $attachedArrFn = [];
  1499. if (isset($form['attached'])) {
  1500. $attachedArr = json_decode($form['attached'], true);
  1501. foreach ($attachedArr as $key => $attached) {
  1502. $idDec = $this->encryptionController->decrypt($attached['id']);
  1503. if (!$idDec) {
  1504. return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
  1505. }
  1506. if ($attached['type'] == 'Existente') {
  1507. $codeArr = explode('=', $idDec);
  1508. $codeArr0 = explode('-', $codeArr[0]);
  1509. $file = DB::table('S002V01TAFAL')->where([
  1510. ['AFAL_NULI', '=', $form['linea']],
  1511. ['AFAL_COMO', '=', $codeArr0[1]],
  1512. ['AFAL_CLDO', '=', $codeArr0[2]],
  1513. ['AFAL_FECR', '=', $codeArr0[3]],
  1514. ['AFAL_NUSE', '=', $codeArr0[4]],
  1515. ['AFAL_NUVE', '=', $codeArr[1]],
  1516. ])->first();
  1517. if(is_null($file)){
  1518. return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
  1519. }else if($file->AFAL_ESTA == 'Eliminado'){
  1520. return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
  1521. }
  1522. $attachedArrFn[] = $idDec;
  1523. }else if($attached['type'] == 'Nuevo'){
  1524. $tempFile = DB::table('S002V01TARTE')->where([
  1525. ['ARTE_IDAR', '=', $idDec],
  1526. ['ARTE_NULI', '=', $form['linea']]
  1527. ])->first();
  1528. if(is_null($tempFile)){
  1529. return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
  1530. }else if($tempFile->ARTE_ESTA == 'Eliminado'){
  1531. return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
  1532. }
  1533. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMPR', 'OR', $tempFile, $idUser);
  1534. if(!$finalFile){
  1535. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  1536. }else{
  1537. $attachedArrFn[] = $finalFile[1];
  1538. }
  1539. }
  1540. }
  1541. }
  1542. $done = json_encode($attachedArrFn);
  1543. if($form['exists'] == 'N'){
  1544. $idOrder = DB::table('S002V01TOTPR')->insertGetId([
  1545. 'OTPR_NULI' => $form['linea'],
  1546. 'OTPR_DEIN' => $dein,
  1547. 'OTPR_ININ' => $inin,
  1548. 'OTPR_EQIN' => $eqin,
  1549. 'OTPR_FIAP' => $startDateTime,
  1550. 'OTPR_FTAP' => $endDateTime,
  1551. 'OTPR_TIIN' => $tiin,
  1552. 'OTPR_OPPR' => $oppr,
  1553. 'OTPR_DTIN' => $dtin,
  1554. 'OTPR_RHRE' => $rhre,
  1555. 'OTPR_DONE' => $done,
  1556. 'OTPR_ACAS' => $acas,
  1557. 'OTPR_CLAS' => $clas,
  1558. 'OTPR_ESTA' => 'B',
  1559. 'OTPR_USRE' => $idUser,
  1560. 'OTPR_FERE' => $nowStr,
  1561. ]);
  1562. }else{
  1563. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  1564. if(!$idOrder){
  1565. return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
  1566. }
  1567. $order = DB::table('S002V01TOTPR')->where([
  1568. ['OTPR_NULI', '=', $form['linea']],
  1569. ['OTPR_IDOT', '=', $idOrder],
  1570. ])->first();
  1571. if(is_null($order)){
  1572. return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404);
  1573. }
  1574. DB::table('S002V01TOTPR')->where([
  1575. ['OTPR_NULI', '=', $form['linea']],
  1576. ['OTPR_IDOT', '=', $idOrder]
  1577. ])->update([
  1578. 'OTPR_DEIN' => $dein,
  1579. 'OTPR_ININ' => $inin,
  1580. 'OTPR_EQIN' => $eqin,
  1581. 'OTPR_FIAP' => $startDateTime,
  1582. 'OTPR_FTAP' => $endDateTime,
  1583. 'OTPR_TIIN' => $tiin,
  1584. 'OTPR_OPPR' => $oppr,
  1585. 'OTPR_DTIN' => $dtin,
  1586. 'OTPR_RHRE' => $rhre,
  1587. 'OTPR_DONE' => $done,
  1588. 'OTPR_ACAS' => $acas,
  1589. 'OTPR_CLAS' => $clas,
  1590. 'OTPR_USMO' => $idUser,
  1591. 'OTPR_FEMO' => $nowStr,
  1592. ]);
  1593. }
  1594. $actions = DB::getQueryLog();
  1595. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1596. $idac = $this->functionsController->registerActivity(
  1597. $form['linea'],
  1598. 'S002V01M10GMPR',
  1599. 'S002V01F01COTP',
  1600. 'S002V01P02ROTP',
  1601. 'Registro',
  1602. "El usuario $name (" . $usr->USUA_IDUS . ") registró un borrador para la orden de trabajo #$idOrder.",
  1603. $idUser,
  1604. $nowStr,
  1605. 'S002V01S01ORTR'
  1606. );
  1607. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1608. return $this->responseController->makeresponse(false, "EXITO");
  1609. }
  1610. public function getActiveOrders($idUser, $line){
  1611. DB::enableQueryLog();
  1612. $idUser = $this->encryptionController->decrypt($idUser);
  1613. if(!$idUser){
  1614. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  1615. }
  1616. $usr = DB::table('S002V01TUSUA')->where([
  1617. ['USUA_NULI', '=', $line],
  1618. ['USUA_IDUS', '=', $idUser]
  1619. ])->first();
  1620. if(is_null($usr)){
  1621. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  1622. }
  1623. $activeWorkOrders = DB::table('S002V01TOTPR')->select([
  1624. 'OTPR_IDOT AS IDORDEN',
  1625. 'OTPR_EQIN AS EQUIPAMIENTO',
  1626. 'OTPR_FIAP AS FECHAINICIO',
  1627. 'OTPR_FTAP AS FECHATERMINO',
  1628. 'OTPR_TIIN AS TIEMPOESTIMADO',
  1629. 'OTPR_DTIN AS TIEMPOTOTAL',
  1630. 'OTPR_CLAS AS CLASIFICACION',
  1631. 'OTPR_ACAS AS ACTIVADOR',
  1632. 'ACTI_PRIO AS PRIORIDAD',
  1633. 'ACTI_TIAC AS TIPOACTIVADOR'
  1634. ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  1635. ['OTPR_NULI', '=', $line],
  1636. ['OTPR_ESTA', '=', 'A']
  1637. ])->get()->all();
  1638. $now = $this->functionsController->now();
  1639. $nowStr = $now->toDateTimeString();
  1640. $actions = DB::getQueryLog();
  1641. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1642. $idac = $this->functionsController->registerActivity(
  1643. $line,
  1644. 'S002V01M10GMPR',
  1645. 'S002V01F01ACMA',
  1646. 'S002V01P01OTAC',
  1647. 'Consulta',
  1648. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento preventivo activas.",
  1649. $idUser,
  1650. $nowStr,
  1651. 'S002V01S02AOTR'
  1652. );
  1653. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1654. return $this->responseController->makeResponse(false, 'EXITO.', $activeWorkOrders);
  1655. }
  1656. public function getPreventiveCalendar($fecIni, $fecFin, $idUser, $line){
  1657. DB::enableQueryLog();
  1658. $idUser = $this->encryptionController->decrypt($idUser);
  1659. if(!$idUser){
  1660. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  1661. }
  1662. $usr = DB::table('S002V01TUSUA')->where([
  1663. ['USUA_NULI', '=', $line],
  1664. ['USUA_IDUS', '=', $idUser],
  1665. ])->first();
  1666. if(is_null($usr)){
  1667. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  1668. }
  1669. if(!$this->functionsController->validDate($fecIni)){
  1670. return $this->responseController->makeResponse(true, 'La fecha de inicio es inválida.', [], 400);
  1671. }
  1672. if(!$this->functionsController->validDate($fecFin)){
  1673. return $this->responseController->makeResponse(true, 'La fecha final es inválida.', [], 400);
  1674. }
  1675. $fecIniObj = new Carbon($fecIni . ' 00:00:00');
  1676. $fecFinObj = new Carbon($fecFin . ' 23:59:59');
  1677. $workOrders = DB::table('S002V01TOTPR')->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  1678. ['OTPR_NULI', '=', $line],
  1679. ['OTPR_ESTA', '=', 'A'],
  1680. ])->get()->all();
  1681. $programmedWorkOrders = [];
  1682. foreach($workOrders as $order){
  1683. $orderStart = new Carbon($order->OTPR_FIAP);
  1684. if($order->ACTI_TIAC == 'Calendario' || $order->ACTI_TIAC == 'Sintoma'){
  1685. $repeatConfig = json_decode($order->ACTI_COAC, true);
  1686. switch($repeatConfig['repeat']){
  1687. case 'AN':
  1688. while ($orderStart->lte($fecFinObj)) {
  1689. if($orderStart->gte($fecIniObj)){
  1690. $reg = DB::table('S002V01TBEOT')->where([
  1691. ['BEOT_NULI', '=', $line],
  1692. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1693. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1694. ])->first();
  1695. $programmedWorkOrders[] = [
  1696. "IDORDEN" => $order->OTPR_IDOT,
  1697. "EVENTCOLOR" => $repeatConfig['color'],
  1698. "DATE" => $orderStart->toDateString(),
  1699. "TYPE" => $order->ACTI_TIAC,
  1700. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1701. ];
  1702. }
  1703. $orderStart->addYear();
  1704. }
  1705. break;
  1706. case 'ME':
  1707. while ($orderStart->lte($fecFinObj)) {
  1708. if($orderStart->gte($fecIniObj)){
  1709. $reg = DB::table('S002V01TBEOT')->where([
  1710. ['BEOT_NULI', '=', $line],
  1711. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1712. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1713. ])->first();
  1714. $programmedWorkOrders[] = [
  1715. "IDORDEN" => $order->OTPR_IDOT,
  1716. "EVENTCOLOR" => $repeatConfig['color'],
  1717. "DATE" => $orderStart->toDateString(),
  1718. "TYPE" => $order->ACTI_TIAC,
  1719. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1720. ];
  1721. }
  1722. $orderStart->addMonth();
  1723. }
  1724. break;
  1725. case 'SE':
  1726. while ($orderStart->lte($fecFinObj)){
  1727. if($orderStart->gte($fecIniObj)){
  1728. $reg = DB::table('S002V01TBEOT')->where([
  1729. ['BEOT_NULI', '=', $line],
  1730. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1731. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1732. ])->first();
  1733. $programmedWorkOrders[] = [
  1734. "IDORDEN" => $order->OTPR_IDOT,
  1735. "EVENTCOLOR" => $repeatConfig['color'],
  1736. "DATE" => $orderStart->toDateString(),
  1737. "TYPE" => $order->ACTI_TIAC,
  1738. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1739. ];
  1740. }
  1741. $orderStart->addWeek();
  1742. }
  1743. break;
  1744. case 'TD':
  1745. while ($orderStart->lte($fecFinObj)){
  1746. if($orderStart->gte($fecIniObj)){
  1747. $reg = DB::table('S002V01TBEOT')->where([
  1748. ['BEOT_NULI', '=', $line],
  1749. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1750. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1751. ])->first();
  1752. $programmedWorkOrders[] = [
  1753. "IDORDEN" => $order->OTPR_IDOT,
  1754. "EVENTCOLOR" => $repeatConfig['color'],
  1755. "DATE" => $orderStart->toDateString(),
  1756. "TYPE" => $order->ACTI_TIAC,
  1757. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1758. ];
  1759. }
  1760. $orderStart->addDay();
  1761. }
  1762. break;
  1763. case 'NR':
  1764. if($orderStart->gte($fecIniObj) && $orderStart->lte($fecFinObj)){
  1765. $reg = DB::table('S002V01TBEOT')->where([
  1766. ['BEOT_NULI', '=', $line],
  1767. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1768. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1769. ])->first();
  1770. $programmedWorkOrders[] = [
  1771. "IDORDEN" => $order->OTPR_IDOT,
  1772. "EVENTCOLOR" => $repeatConfig['color'],
  1773. "DATE" => $orderStart->toDateString(),
  1774. "TYPE" => $order->ACTI_TIAC,
  1775. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1776. ];
  1777. }
  1778. break;
  1779. case 'PE':
  1780. $customRepeat = json_decode($repeatConfig['customRepeat'], true);
  1781. $repeatEvery = explode('|', $customRepeat['repeatEvery']);
  1782. switch($repeatEvery[1]){
  1783. case '0':
  1784. //Repeticiones por día
  1785. $days = intval($repeatEvery[0]);
  1786. while ($orderStart->lte($fecFinObj)) {
  1787. if($orderStart->gte($fecIniObj)){
  1788. $reg = DB::table('S002V01TBEOT')->where([
  1789. ['BEOT_NULI', '=', $line],
  1790. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1791. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1792. ])->first();
  1793. $programmedWorkOrders[] = [
  1794. "IDORDEN" => $order->OTPR_IDOT,
  1795. "EVENTCOLOR" => $repeatConfig['color'],
  1796. "DATE" => $orderStart->toDateString(),
  1797. "TYPE" => $order->ACTI_TIAC,
  1798. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1799. ];
  1800. }
  1801. $orderStart->addDays($days);
  1802. }
  1803. break;
  1804. case '1':
  1805. //Repeticiones por semana
  1806. $weeks = intval($repeatEvery[0]);
  1807. $orderStartAux = new Carbon($orderStart->toDateTimeString());
  1808. $repeatOn = $customRepeat['repeatOn'];
  1809. while ($orderStart->lte($fecFinObj)){
  1810. $dayInd = $orderStartAux->dayOfWeek;
  1811. for($i = $dayInd; $i < 7; $i++){
  1812. $dayName = strtolower($orderStartAux->dayName);
  1813. $dayKey = substr($dayName, 0, 3);
  1814. $shouldRepeat = $repeatOn[$dayKey];
  1815. if($shouldRepeat && $orderStartAux->lte($fecFinObj) && $orderStartAux->gte($fecIniObj)){
  1816. $reg = DB::table('S002V01TBEOT')->where([
  1817. ['BEOT_NULI', '=', $line],
  1818. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1819. ['BEOT_FEPR', '=', $orderStartAux->toDateString()]
  1820. ])->first();
  1821. $programmedWorkOrders[] = [
  1822. "IDORDEN" => $order->OTPR_IDOT,
  1823. "EVENTCOLOR" => $repeatConfig['color'],
  1824. "DATE" => $orderStartAux->toDateString(),
  1825. "TYPE" => $order->ACTI_TIAC,
  1826. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1827. ];
  1828. }
  1829. $orderStartAux->addDay();
  1830. }
  1831. $orderStart->addWeeks($weeks);
  1832. }
  1833. break;
  1834. case '2':
  1835. //Repeticiones por mes
  1836. $months = intval($repeatEvery[0]);
  1837. $orderStartStrAux = $orderStart->toDateTimeString();
  1838. $iterations = 1;
  1839. while ($orderStart->lte($fecFinObj)){
  1840. if($orderStart->gte($fecIniObj)){
  1841. $reg = DB::table('S002V01TBEOT')->where([
  1842. ['BEOT_NULI', '=', $line],
  1843. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1844. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1845. ])->first();
  1846. $programmedWorkOrders[] = [
  1847. "IDORDEN" => $order->OTPR_IDOT,
  1848. "EVENTCOLOR" => $repeatConfig['color'],
  1849. "DATE" => $orderStart->toDateString(),
  1850. "TYPE" => $order->ACTI_TIAC,
  1851. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1852. ];
  1853. }
  1854. $monthsToAdd = $months * $iterations;
  1855. $orderStartObjAux = new Carbon($orderStartStrAux);
  1856. $orderStartObjAux->addMonths($monthsToAdd);
  1857. $orderStart = new Carbon($orderStartObjAux->toDateTimeString());
  1858. $iterations++;
  1859. }
  1860. break;
  1861. case '3':
  1862. //Repeticiones por año
  1863. $years = intval($repeatEvery[0]);
  1864. while ($orderStart->lte($fecFinObj)){
  1865. if($orderStart->gte($fecIniObj)){
  1866. $reg = DB::table('S002V01TBEOT')->where([
  1867. ['BEOT_NULI', '=', $line],
  1868. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  1869. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  1870. ])->first();
  1871. $programmedWorkOrders[] = [
  1872. "IDORDEN" => $order->OTPR_IDOT,
  1873. "EVENTCOLOR" => $repeatConfig['color'],
  1874. "DATE" => $orderStart->toDateString(),
  1875. "TYPE" => $order->ACTI_TIAC,
  1876. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  1877. ];
  1878. }
  1879. $orderStart->addYears($years);
  1880. }
  1881. break;
  1882. }
  1883. break;
  1884. }
  1885. }
  1886. }
  1887. $now = $this->functionsController->now();
  1888. $nowStr = $now->toDateTimeString();
  1889. $actions = DB::getQueryLog();
  1890. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1891. $idac = $this->functionsController->registerActivity(
  1892. $line,
  1893. 'S002V01M10GMPR',
  1894. 'S002V01F08VCPR',
  1895. '-',
  1896. 'Consulta',
  1897. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los eventos programados entre las fechas $fecIni y $fecFin.",
  1898. $idUser,
  1899. $nowStr,
  1900. 'S002V01S02AOTR'
  1901. );
  1902. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1903. return $this->responseController->makeResponse(false, 'EXITO.', $programmedWorkOrders);
  1904. }
  1905. // Visitas técnicas no programadas (Preventivas)
  1906. public function newUnprogrammedOrder(Request $request){
  1907. Log::info($request->all());
  1908. DB::enableQueryLog();
  1909. $validator = Validator::make($request->all(), [
  1910. 'id_user' => 'required|string',
  1911. 'linea' => 'required|integer',
  1912. 'equipment' => 'required|string',
  1913. 'resources' => 'required|json',
  1914. 'comments' => 'required|string|min:35',
  1915. 'staff' => 'required|json',
  1916. 'priority' => 'required|integer',
  1917. 'description' => 'required|string',
  1918. 'estimated' => 'required|numeric',
  1919. 'clasification' => 'required|string'
  1920. ]);
  1921. if ($validator->fails()) {
  1922. return $this->responseController->makeResponse(
  1923. true,
  1924. "Se encontraron uno o más errores.",
  1925. $this->responseController->makeErrors(
  1926. $validator->errors()->messages()
  1927. ),
  1928. 401
  1929. );
  1930. }
  1931. $form = $request->all();
  1932. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1933. if (!$idUser) {
  1934. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1935. }
  1936. $usr = DB::table('S002V01TUSUA')->where([
  1937. ['USUA_NULI', '=', $form['linea']],
  1938. ['USUA_IDUS', '=', $idUser]
  1939. ])->first();
  1940. if (is_null($usr)) {
  1941. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1942. }
  1943. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  1944. if (!$equipmentCode) {
  1945. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
  1946. }
  1947. $equipment = DB::table('S002V01TEQUI')->where([
  1948. ['EQUI_NULI', '=', $form['linea']],
  1949. ['EQUI_COEQ', '=', $equipmentCode]
  1950. ])->first();
  1951. if(is_null($equipment)){
  1952. return $this->responseController->makeResponse(true, 'El equipamiento seleccionado no existe.', [], 404);
  1953. }
  1954. $staffArr = json_decode($form['staff'], true);
  1955. if(empty($staffArr)){
  1956. return $this->responseController->makeResponse(true, 'El JSON de personal está vacío.', [], 400);
  1957. }
  1958. $staff = [];
  1959. foreach($staffArr as $val){
  1960. if(!array_key_exists('TYPE', $val) && !array_key_exists('ID', $val)){
  1961. return $this->responseController->makeResponse(true, "El arreglo del personal no tiene un formato válido.", [], 400);
  1962. }
  1963. $typeStr = '';
  1964. if($val['TYPE'] == 'EQ'){
  1965. $typeStr = 'equipo de trabajo';
  1966. }else if($val['TYPE'] == 'SU'){
  1967. $typeStr = 'subcontratista';
  1968. }else if($val['TYPE'] == 'EM'){
  1969. $typeStr = 'empleado';
  1970. }
  1971. $key = $this->encryptionController->decrypt($val['ID']);
  1972. if(!$key){
  1973. return $this->responseController->makeResponse(true, "El ID del $typeStr no fue encriptado correctamente.", [], 400);
  1974. }
  1975. $res = null;
  1976. if($val['TYPE'] == 'EQ'){
  1977. $res = DB::table('S002V01TEQMA')->where([
  1978. ['EQMA_NULI', '=', $form['linea']],
  1979. ['EQMA_IDEQ', '=', $key],
  1980. ])->first();
  1981. }else if($val['TYPE'] == 'SU'){
  1982. $res = DB::table('S002V01TPESU')->where([
  1983. ['PESU_NULI', '=', $form['linea']],
  1984. ['PESU_IDPS', '=', $key],
  1985. ])->first();
  1986. }else if($val['TYPE'] == 'EM'){
  1987. $res = DB::table('S002V01TPERS')->where([
  1988. ['PERS_NULI', '=', $form['linea']],
  1989. ['PERS_IDPE', '=', $key],
  1990. ])->first();
  1991. }
  1992. if (is_null($res)) {
  1993. return $this->responseController->makeResponse(true, "El $typeStr no está registrado.", [], 400);
  1994. }
  1995. $staff[] = [
  1996. 'ID' => $key,
  1997. 'TYPE' => $val['TYPE']
  1998. ];
  1999. }
  2000. $resources = json_decode($form['resources'], true);
  2001. if (empty($resources)) {
  2002. return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
  2003. }
  2004. $commentsArr = [
  2005. 'COMENTARIO_REGISTRO' => $form['comments']
  2006. ];
  2007. $now = $this->functionsController->now();
  2008. $nowStr = $now->toDateTimeString();
  2009. $statusHistoryStr = json_encode([
  2010. [
  2011. 'FECHA' => $nowStr,
  2012. 'ESTADO' => 'PE',
  2013. 'USUARIO' => $idUser,
  2014. ]
  2015. ]);
  2016. $commentsStr = json_encode($commentsArr);
  2017. $staffStr = json_encode($staff);
  2018. $idVisit = DB::table('S002V01TRVTN')->insertGetId([
  2019. 'RVTN_NULI' => $form['linea'],
  2020. 'RVTN_EQRE' => $equipmentCode,
  2021. 'RVTN_DEIN' => $form['description'],
  2022. 'RVTN_TIAC' => 'M',
  2023. 'RVTN_PEIN' => $staffStr,
  2024. 'RVTN_MAUT' => $form['resources'],
  2025. 'RVTN_PRIO' => $form['priority'],
  2026. 'RVTN_TESO' => $form['estimated'],
  2027. 'RVTN_CLAS' => $form['clasification'],
  2028. 'RVTN_ESTA' => 'PE',
  2029. 'RVTN_HIES' => $statusHistoryStr,
  2030. 'RVTN_COME' => $commentsStr,
  2031. 'RVTN_USRE' => $idUser,
  2032. 'RVTN_FERE' => $nowStr,
  2033. ]);
  2034. $actions = DB::getQueryLog();
  2035. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2036. $idac = $this->functionsController->registerActivity(
  2037. $form['linea'],
  2038. 'S002V01M10GMPR',
  2039. 'S002V01F11RVTP',
  2040. 'S002V01P01REVI',
  2041. 'Registro',
  2042. "El usuario $name (" . $usr->USUA_IDUS . ") registró la visita no programada #$idVisit.",
  2043. $idUser,
  2044. $nowStr,
  2045. 'S002V01S02AOTR'
  2046. );
  2047. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2048. return $this->responseController->makeResponse(false, 'EXITO.');
  2049. }
  2050. // Visitas técnicas no programadas (Preventivas)
  2051. public function getUnprogrammedVisits($idUser, $line){
  2052. DB::enableQueryLog();
  2053. $idUser = $this->encryptionController->decrypt($idUser);
  2054. if (!$idUser) {
  2055. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2056. }
  2057. $usr = DB::table('S002V01TUSUA')->where([
  2058. ['USUA_NULI', '=', $line],
  2059. ['USUA_IDUS', '=', $idUser],
  2060. ])->first();
  2061. if (is_null($usr)) {
  2062. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2063. }
  2064. $visits = DB::table('S002V01TRVTN')->select([
  2065. 'RVTN_IDVI AS IDVISITA',
  2066. 'RVTN_EQRE AS EQUIPAMIENTO',
  2067. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  2068. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  2069. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  2070. 'RVTN_ESTA AS ESTADO',
  2071. 'RVTN_USRE AS USRREG',
  2072. 'RVTN_FERE AS FECREG',
  2073. 'RVTN_FEMO AS FECMOD',
  2074. 'RVTN_PRIO AS PRIORIDAD',
  2075. 'RVTN_DEIN AS DESCRIPCION',
  2076. 'RVTN_TIAC AS TIPO_ACTIVACION',
  2077. 'usrReg.USUA_NOMB AS USRREG_NOMB',
  2078. 'usrReg.USUA_APPA AS USRREG_APPA',
  2079. 'usrReg.USUA_APMA AS USRREG_APMA'
  2080. ])->where('RVTN_NULI', '=', $line)
  2081. ->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')
  2082. ->leftJoin('S002V01TUSUA as usrReg', function ($join) {
  2083. $join->on('usrReg.USUA_IDUS', '=', 'S002V01TRVTN.RVTN_USRE')
  2084. ->on('usrReg.USUA_NULI', '=', 'S002V01TRVTN.RVTN_NULI');
  2085. })
  2086. ->orderBy('RVTN_IDVI', 'desc')->get()->all();
  2087. foreach ($visits as $visit) {
  2088. $visit->IDVISITA = $this->encryptionController->encrypt($visit->IDVISITA);
  2089. $visit->EQUIPAMIENTO = $this->encryptionController->encrypt($visit->EQUIPAMIENTO);
  2090. $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO);
  2091. $nameReg = $this->functionsController->joinName($visit->USRREG_NOMB, $visit->USRREG_APPA, $visit->USRREG_APMA);
  2092. if (!empty($nameReg)) {
  2093. $visit->USRREG = trim((string) $nameReg) . " (" . $visit->USRREG . ")";
  2094. }
  2095. unset($visit->USRREG_NOMB, $visit->USRREG_APPA, $visit->USRREG_APMA);
  2096. }
  2097. $now = $this->functionsController->now();
  2098. $nowStr = $now->toDateTimeString();
  2099. $actions = DB::getQueryLog();
  2100. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2101. $idac = $this->functionsController->registerActivity(
  2102. $line,
  2103. 'S002V01M10GMPR',
  2104. 'S002V01F11RVTP',
  2105. 'S002V01P02COVI',
  2106. 'Consulta',
  2107. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la lista de visitas no programadas.",
  2108. $idUser,
  2109. $nowStr,
  2110. 'S002V01S02AOTR'
  2111. );
  2112. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2113. return $this->responseController->makeResponse(false, 'EXITO.', $visits);
  2114. }
  2115. // Visitas técnicas no programadas (Preventivas)
  2116. public function getUnprogrammedVisit($idVisit, $idUser, $line){
  2117. DB::enableQueryLog();
  2118. $idUser = $this->encryptionController->decrypt($idUser);
  2119. if (!$idUser) {
  2120. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2121. }
  2122. $usr = DB::table('S002V01TUSUA')->where([
  2123. ['USUA_IDUS', '=', $idUser],
  2124. ['USUA_NULI', '=', $line]
  2125. ])->first();
  2126. if (is_null($usr)) {
  2127. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2128. }
  2129. $idVisit = $this->encryptionController->decrypt($idVisit);
  2130. if (!$idVisit) {
  2131. return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
  2132. }
  2133. $visit = DB::table('S002V01TRVTN')->select([
  2134. 'RVTN_IDVI AS IDVISITA',
  2135. 'RVTN_EQRE AS EQUIPAMIENTO',
  2136. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  2137. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  2138. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  2139. 'RVTN_PEIN AS PERSONAL',
  2140. 'RVTN_MAUT AS MATERIAL',
  2141. 'RVTN_COME AS COMENTARIOS',
  2142. 'RVTN_ESTA AS ESTADO',
  2143. 'RVTN_USRE AS USRREG',
  2144. 'RVTN_FERE AS FECREG',
  2145. 'RVTN_UARE AS USAURE',
  2146. 'RVTN_FARE AS FEAURE',
  2147. 'RVTN_USCA AS USRCAN',
  2148. 'RVTN_FECA AS FECCAN',
  2149. 'RVTN_USFI AS USUFIN',
  2150. 'RVTN_FEFI AS FECFIN',
  2151. 'RVTN_USMO AS USRMOD',
  2152. 'RVTN_FEMO AS FECMOD',
  2153. ])->where([
  2154. ['RVTN_IDVI', '=', $idVisit],
  2155. ['RVTN_NULI', '=', $line]
  2156. ])->join('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')->first();
  2157. if (is_null($visit)) {
  2158. return $this->responseController->makeResponse(true, 'La visita consultada no existe.', [], 404);
  2159. }
  2160. $visit->IDVISITA = $this->encryptionController->encrypt($visit->IDVISITA);
  2161. $visit->EQUIPAMIENTO = $this->encryptionController->encrypt($visit->EQUIPAMIENTO);
  2162. $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO);
  2163. $staffFn = [];
  2164. $staffArr = json_decode($visit->PERSONAL, true);
  2165. foreach ($staffArr as $item) {
  2166. $name = '';
  2167. if ($item['TYPE'] == 'EQ') {
  2168. $workTeam = DB::table('S002V01TEQMA')->where([
  2169. ['EQMA_NULI', '=', $line],
  2170. ['EQMA_IDEQ', '=', $item['ID']]
  2171. ])->first();
  2172. $name = $workTeam->EQMA_NOMB;
  2173. } else if ($item['TYPE'] == 'SU') {
  2174. $subcontratist = DB::table('S002V01TPESU')->where([
  2175. ['PESU_NULI', '=', $line],
  2176. ['PESU_IDPS', '=', $item['ID']]
  2177. ])->first();
  2178. $name = $subcontratist->PESU_RASO;
  2179. } else if ($item['TYPE'] == 'EM') {
  2180. $employee = DB::table('S002V01TPERS')
  2181. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
  2182. ['PERS_NULI', '=', $line],
  2183. ['PERS_IDPE', '=', $item['ID']]
  2184. ])->first();
  2185. $name = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
  2186. }
  2187. $staffFn[] = [
  2188. 'ID' => $this->encryptionController->encrypt($item['ID']),
  2189. 'TYPE' => $item['TYPE'],
  2190. 'NAME' => $name,
  2191. ];
  2192. }
  2193. $visit->PERSONAL = json_encode($staffFn);
  2194. $usrReg = DB::table('S002V01TUSUA')->where([
  2195. ['USUA_NULI', '=', $line],
  2196. ['USUA_IDUS', '=', $visit->USRREG],
  2197. ])->first();
  2198. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $visit->USRREG . ")";
  2199. $visit->USRREG = $nameReg;
  2200. if (!is_null($visit->USAURE)) {
  2201. $usaure = DB::table('S002V01TUSUA')->where([
  2202. ['USUA_NULI', '=', $line],
  2203. ['USUA_IDUS', '=', $visit->USAURE],
  2204. ])->first();
  2205. $nameUre = $this->functionsController->joinName($usaure->USUA_NOMB, $usaure->USUA_APPA, $usaure->USUA_APMA) . " (" . $visit->USAURE . ")";
  2206. $visit->USAURE = $nameUre;
  2207. }
  2208. if (!is_null($visit->USRCAN)) {
  2209. $usrCan = DB::table('S002V01TUSUA')->where([
  2210. ['USUA_NULI', '=', $line],
  2211. ['USUA_IDUS', '=', $visit->USRCAN],
  2212. ])->first();
  2213. $nameCan = $this->functionsController->joinName($usrCan->USUA_NOMB, $usrCan->USUA_APPA, $usrCan->USUA_APMA) . " (" . $visit->USRCAN . ")";
  2214. $visit->USRCAN = $nameCan;
  2215. }
  2216. if (!is_null($visit->USUFIN)) {
  2217. $usrFin = DB::table('S002V01TUSUA')->where([
  2218. ['USUA_NULI', '=', $line],
  2219. ['USUA_IDUS', '=', $visit->USUFIN],
  2220. ])->first();
  2221. $nameFin = $this->functionsController->joinName($usrFin->USUA_NOMB, $usrFin->USUA_APPA, $usrFin->USUA_APMA) . " (" . $visit->USUFIN . ")";
  2222. $visit->USUFIN = $nameFin;
  2223. }
  2224. if (!is_null($visit->USRMOD)) {
  2225. $usrMod = DB::table('S002V01TUSUA')->where([
  2226. ['USUA_NULI', '=', $line],
  2227. ['USUA_IDUS', '=', $visit->USRMOD],
  2228. ])->first();
  2229. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA) . " (" . $visit->USRMOD . ")";
  2230. $visit->USRMOD = $nameMod;
  2231. }
  2232. $now = $this->functionsController->now();
  2233. $nowStr = $now->toDateTimeString();
  2234. $actions = DB::getQueryLog();
  2235. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2236. $idac = $this->functionsController->registerActivity(
  2237. $line,
  2238. 'S002V01M10GMPR',
  2239. 'S002V01F11RVTP',
  2240. 'S002V01P02COVI',
  2241. 'Consulta',
  2242. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la visita no programada #$idVisit.",
  2243. $idUser,
  2244. $nowStr,
  2245. 'S002V01S02AOTR'
  2246. );
  2247. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2248. return $this->responseController->makeResponse(false, 'EXITO.', $visit);
  2249. }
  2250. // Visitas técnicas no programadas (Preventivas)
  2251. public function updateVisitStatus(Request $request){
  2252. DB::enableQueryLog();
  2253. // RVTN_ESTA enum: 'PE','CA','RE','EL','VA','EP','CP','CE'
  2254. $validator = Validator::make($request->all(), [
  2255. 'id_user' => 'required|string',
  2256. 'linea' => 'required|integer',
  2257. 'id_visit' => 'required|string',
  2258. 'comments' => 'nullable|string|min:15',
  2259. 'status' => 'required|string|in:PE,CA,RE,EL,VA,EP,CP,CE'
  2260. ]);
  2261. if ($validator->fails()) {
  2262. return $this->responseController->makeResponse(
  2263. true,
  2264. "Se encontraron uno o más errores.",
  2265. $this->responseController->makeErrors(
  2266. $validator->errors()->messages()
  2267. ),
  2268. 401
  2269. );
  2270. }
  2271. $form = $request->all();
  2272. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2273. if (!$idUser) {
  2274. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2275. }
  2276. $usr = DB::table('S002V01TUSUA')->where([
  2277. ['USUA_NULI', '=', $form['linea']],
  2278. ['USUA_IDUS', '=', $idUser],
  2279. ])->first();
  2280. if (is_null($usr)) {
  2281. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2282. }
  2283. $idVisit = $this->encryptionController->decrypt($form['id_visit']);
  2284. if (!$idVisit) {
  2285. return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
  2286. }
  2287. $visit = DB::table('S002V01TRVTN')->where([
  2288. ['RVTN_NULI', '=', $form['linea']],
  2289. ['RVTN_IDVI', '=', $idVisit],
  2290. ])->first();
  2291. if (is_null($visit)) {
  2292. return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
  2293. }
  2294. $currentStatus = $visit->RVTN_ESTA;
  2295. $newStatus = $form['status'];
  2296. // Matriz de transiciones permitidas
  2297. $allowedTransitions = [
  2298. 'PE' => ['VA', 'RE', 'CA', 'EL'], // Pendiente
  2299. 'VA' => ['EP', 'CA', 'EL'], // Validado
  2300. 'EP' => ['CP', 'CA', 'EL'], // En proceso
  2301. 'CP' => ['CE'], // Cerrado pendiente
  2302. 'CE' => [], // Cerrado - Estado final
  2303. 'CA' => [], // Cancelado - Estado final
  2304. 'EL' => [], // Eliminado - Estado final
  2305. 'RE' => [] // Rechazado - Estado final
  2306. ];
  2307. // Validar transición permitida
  2308. $currentStatusTransitions = $allowedTransitions[$currentStatus] ?? [];
  2309. // Si el estado actual no está en la matriz, no permitir cambios
  2310. if (!array_key_exists($currentStatus, $allowedTransitions)) {
  2311. return $this->responseController->makeResponse(true, "El estado actual {$currentStatus} no permite cambios.", [], 400);
  2312. }
  2313. // Validar si la transición está permitida
  2314. if (!in_array($newStatus, $currentStatusTransitions)) {
  2315. $statusNames = [
  2316. 'PE' => 'Pendiente',
  2317. 'CA' => 'Cancelado',
  2318. 'RE' => 'Rechazado',
  2319. 'EL' => 'Eliminado',
  2320. 'VA' => 'Validado',
  2321. 'EP' => 'En Proceso',
  2322. 'CP' => 'Cerrado Pendiente',
  2323. 'CE' => 'Cerrado'
  2324. ];
  2325. $currentStatusName = $statusNames[$currentStatus] ?? $currentStatus;
  2326. $newStatusName = $statusNames[$newStatus] ?? $newStatus;
  2327. return $this->responseController->makeResponse(true, "No se puede cambiar de {$currentStatusName} a {$newStatusName}. Transición no permitida.", [], 400);
  2328. }
  2329. // Obtener y actualizar historial de estados
  2330. $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
  2331. if (!is_array($statusHistoryArr)) {
  2332. $statusHistoryArr = [];
  2333. }
  2334. $now = $this->functionsController->now();
  2335. $nowStr = $now->toDateTimeString();
  2336. // Agregar nuevo estado al historial
  2337. $statusHistoryArr[] = [
  2338. 'FECHA' => $nowStr,
  2339. 'ESTADO' => $newStatus,
  2340. 'USUARIO' => $idUser
  2341. ];
  2342. $statusHistoryStr = json_encode($statusHistoryArr);
  2343. // Preparar actualización
  2344. $updateArr = [
  2345. 'RVTN_ESTA' => $newStatus,
  2346. 'RVTN_HIES' => $statusHistoryStr,
  2347. 'RVTN_USMO' => $idUser,
  2348. 'RVTN_FEMO' => $nowStr,
  2349. ];
  2350. // Asignar campos específicos según el estado
  2351. if ($newStatus == 'PE') {
  2352. // Pendiente - Ya registrado en creación
  2353. } elseif ($newStatus == 'CA') {
  2354. $updateArr['RVTN_USCA'] = $idUser;
  2355. $updateArr['RVTN_FECA'] = $nowStr;
  2356. // Registrar comentario de cancelación
  2357. if (!empty($form['comments'])) {
  2358. $commentsArr = json_decode($visit->RVTN_COME, true);
  2359. if (!is_array($commentsArr)) {
  2360. $commentsArr = [];
  2361. }
  2362. $commentsArr['COMENTARIO_CANCELACION'] = [
  2363. 'ID' => $idUser,
  2364. 'COMENTARIO' => $form['comments'],
  2365. 'FECHA' => $nowStr
  2366. ];
  2367. $updateArr['RVTN_COME'] = json_encode($commentsArr);
  2368. }
  2369. } elseif ($newStatus == 'RE') {
  2370. $updateArr['RVTN_UARE'] = $idUser;
  2371. $updateArr['RVTN_FARE'] = $nowStr;
  2372. // Registrar comentario de rechazo
  2373. if (!empty($form['comments'])) {
  2374. $commentsArr = json_decode($visit->RVTN_COME, true);
  2375. if (!is_array($commentsArr)) {
  2376. $commentsArr = [];
  2377. }
  2378. $commentsArr['COMENTARIO_RECHAZO'] = [
  2379. 'ID' => $idUser,
  2380. 'COMENTARIO' => $form['comments'],
  2381. 'FECHA' => $nowStr
  2382. ];
  2383. $updateArr['RVTN_COME'] = json_encode($commentsArr);
  2384. }
  2385. } elseif ($newStatus == 'EL') {
  2386. // Eliminado - podría necesitar campos específicos
  2387. } elseif (in_array($newStatus, ['VA', 'EP', 'CP', 'CE'])) {
  2388. $updateArr['RVTN_UARE'] = $idUser;
  2389. $updateArr['RVTN_FARE'] = $nowStr;
  2390. if ($newStatus == 'CE') {
  2391. $updateArr['RVTN_USFI'] = $idUser;
  2392. $updateArr['RVTN_FEFI'] = $nowStr;
  2393. // Calcular tiempo de duración de la intervención
  2394. $epDate = null;
  2395. $ceDate = $nowStr;
  2396. foreach ($statusHistoryArr as $historyItem) {
  2397. if ($historyItem['ESTADO'] === 'EP') {
  2398. $epDate = $historyItem['FECHA'];
  2399. }
  2400. }
  2401. if ($epDate) {
  2402. $startTime = new \Carbon\Carbon($epDate);
  2403. $endTime = new \Carbon\Carbon($ceDate);
  2404. $durationHours = $endTime->diffInMinutes($startTime) / 60.0;
  2405. $updateArr['RVTN_DTIN'] = $durationHours;
  2406. }
  2407. }
  2408. }
  2409. DB::table('S002V01TRVTN')->where([
  2410. ['RVTN_NULI', '=', $form['linea']],
  2411. ['RVTN_IDVI', '=', $idVisit],
  2412. ])->update($updateArr);
  2413. // Obtener audiencia para notificaciones (operarios y regulador)
  2414. $audience = [];
  2415. // Obtener operarios que aceptaron la invitación (del último estado VA)
  2416. $statusHistoryForAudience = json_decode($visit->RVTN_HIES, true);
  2417. if (is_array($statusHistoryForAudience)) {
  2418. // Buscar el último estado VA
  2419. $lastVAStatus = null;
  2420. for ($i = count($statusHistoryForAudience) - 1; $i >= 0; $i--) {
  2421. if ($statusHistoryForAudience[$i]['ESTADO'] === 'VA') {
  2422. $lastVAStatus = $statusHistoryForAudience[$i];
  2423. break;
  2424. }
  2425. }
  2426. if ($lastVAStatus && isset($lastVAStatus['ATENCION']) && is_array($lastVAStatus['ATENCION'])) {
  2427. foreach ($lastVAStatus['ATENCION'] as $item) {
  2428. if (($item['RESPUESTA'] ?? '') === 'A') {
  2429. $audience[] = $item['ID'];
  2430. }
  2431. }
  2432. }
  2433. }
  2434. // Agregar regulador (quien registró la visita)
  2435. if (!empty($visit->RVTN_USRE) && !in_array($visit->RVTN_USRE, $audience)) {
  2436. $audience[] = $visit->RVTN_USRE;
  2437. }
  2438. // Preparar mensajes de notificación según el estado
  2439. $statusMessages = [
  2440. 'PE' => 'Pendiente',
  2441. 'CA' => 'Cancelación',
  2442. 'RE' => 'Rechazo',
  2443. 'EL' => 'Eliminación',
  2444. 'VA' => 'Validación',
  2445. 'EP' => 'Inicio',
  2446. 'CP' => 'Cerrado Pendiente',
  2447. 'CE' => 'Cierre'
  2448. ];
  2449. $statusAction = $statusMessages[$newStatus] ?? 'Cambio de estado';
  2450. $notificationTitle = "Visita Técnica No Programada #$idVisit";
  2451. $notificationMessage = "La visita técnica no programada #$idVisit ha sido actualizada a estado: {$statusAction}.";
  2452. // Notificación general para todos los cambios de estado
  2453. if (in_array($newStatus, ['VA', 'RE', 'CA', 'EL', 'EP', 'CE', 'CP']) && !empty($audience)) {
  2454. $this->notificationsController->emitNotification(
  2455. 'S002V01M10GMPR',
  2456. $notificationTitle,
  2457. $notificationMessage,
  2458. [[
  2459. 'BOTON' => 'Ver detalles',
  2460. 'FUNCION' => 'openPreventiveWorkOrderDetails',
  2461. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  2462. ], [
  2463. 'BOTON' => 'Ir al módulo',
  2464. 'FUNCION' => 'openModule',
  2465. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  2466. ]],
  2467. $audience,
  2468. $idUser,
  2469. $form['linea'],
  2470. $this->getSocketClient(),
  2471. $idVisit,
  2472. 'Preventivo'
  2473. );
  2474. }
  2475. $actions = DB::getQueryLog();
  2476. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2477. $idac = $this->functionsController->registerActivity(
  2478. $form['linea'],
  2479. 'S002V01M10GMPR',
  2480. 'S002V01F11RVTP',
  2481. 'S002V01P01REVI',
  2482. 'Actualización',
  2483. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la visita no programada #$idVisit a estado {$statusAction}.",
  2484. $idUser,
  2485. $nowStr,
  2486. 'S002V01S02AOTR'
  2487. );
  2488. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2489. return $this->responseController->makeResponse(false, 'EXITO.');
  2490. }
  2491. // Visitas técnicas no programadas (Preventivas)
  2492. // Registrar comentario de finalización de un operario en estado CP
  2493. public function registerOperatorClosingComment(Request $request){
  2494. DB::enableQueryLog();
  2495. $validator = Validator::make($request->all(), [
  2496. 'id_user' => 'required|string',
  2497. 'linea' => 'required|integer',
  2498. 'id_visit' => 'required|string',
  2499. 'comment' => 'required|string|min:15'
  2500. ]);
  2501. if ($validator->fails()) {
  2502. return $this->responseController->makeResponse(
  2503. true,
  2504. "Se encontraron uno o más errores.",
  2505. $this->responseController->makeErrors(
  2506. $validator->errors()->messages()
  2507. ),
  2508. 401
  2509. );
  2510. }
  2511. $form = $request->all();
  2512. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2513. if (!$idUser) {
  2514. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2515. }
  2516. $usr = DB::table('S002V01TUSUA')->where([
  2517. ['USUA_NULI', '=', $form['linea']],
  2518. ['USUA_IDUS', '=', $idUser],
  2519. ])->first();
  2520. if (is_null($usr)) {
  2521. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2522. }
  2523. $idVisit = $this->encryptionController->decrypt($form['id_visit']);
  2524. if (!$idVisit) {
  2525. return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
  2526. }
  2527. $visit = DB::table('S002V01TRVTN')->where([
  2528. ['RVTN_NULI', '=', $form['linea']],
  2529. ['RVTN_IDVI', '=', $idVisit],
  2530. ])->first();
  2531. if (is_null($visit)) {
  2532. return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
  2533. }
  2534. // Validar que la visita está en estado EP o CP
  2535. if (!in_array($visit->RVTN_ESTA, ['EP', 'CP'])) {
  2536. 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);
  2537. }
  2538. // Iniciar transacción
  2539. DB::beginTransaction();
  2540. try {
  2541. // Obtener historial de estados
  2542. $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
  2543. if (!is_array($statusHistoryArr)) {
  2544. DB::rollBack();
  2545. return $this->responseController->makeResponse(true, 'No se encontró un historial de estados válido para la visita.', [], 500);
  2546. }
  2547. // Buscar el último estado VA para obtener la lista de operarios que aceptaron
  2548. $lastVAStatus = null;
  2549. $acceptedOperators = [];
  2550. for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
  2551. if ($statusHistoryArr[$i]['ESTADO'] === 'VA') {
  2552. $lastVAStatus = $statusHistoryArr[$i];
  2553. break;
  2554. }
  2555. }
  2556. if (!$lastVAStatus || !isset($lastVAStatus['ATENCION']) || !is_array($lastVAStatus['ATENCION'])) {
  2557. DB::rollBack();
  2558. return $this->responseController->makeResponse(true, 'No se encontró información de operarios asignados a la visita.', [], 404);
  2559. }
  2560. // Obtener lista de operarios que aceptaron
  2561. foreach ($lastVAStatus['ATENCION'] as $item) {
  2562. if (($item['RESPUESTA'] ?? '') === 'A') {
  2563. $acceptedOperators[] = $item['ID'];
  2564. }
  2565. }
  2566. // Validar que el usuario es uno de los operarios que aceptó
  2567. if (!in_array($idUser, $acceptedOperators)) {
  2568. DB::rollBack();
  2569. 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);
  2570. }
  2571. // Buscar el objeto CP en el historial o crearlo si no existe
  2572. $cpStatusIndex = null;
  2573. $cpStatus = null;
  2574. $isFirstComment = false;
  2575. for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
  2576. if ($statusHistoryArr[$i]['ESTADO'] === 'CP') {
  2577. $cpStatusIndex = $i;
  2578. $cpStatus = $statusHistoryArr[$i];
  2579. break;
  2580. }
  2581. }
  2582. // Si no existe objeto CP, crear uno nuevo y cambiar estado de EP a CP
  2583. if ($cpStatusIndex === null) {
  2584. $now = $this->functionsController->now();
  2585. $nowStr = $now->toDateTimeString();
  2586. $isFirstComment = true;
  2587. $cpStatus = [
  2588. 'FECHA' => $nowStr,
  2589. 'ESTADO' => 'CP',
  2590. 'USUARIO' => $idUser,
  2591. 'COMENTARIOS_OPERARIOS' => []
  2592. ];
  2593. $cpStatusIndex = count($statusHistoryArr);
  2594. $statusHistoryArr[] = $cpStatus;
  2595. } else {
  2596. // Asegurar que existe el array de comentarios
  2597. if (!isset($cpStatus['COMENTARIOS_OPERARIOS']) || !is_array($cpStatus['COMENTARIOS_OPERARIOS'])) {
  2598. $cpStatus['COMENTARIOS_OPERARIOS'] = [];
  2599. }
  2600. }
  2601. // Obtener comentarios existentes para validación
  2602. $existingCommentsArr = json_decode($visit->RVTN_COME, true);
  2603. if (!is_array($existingCommentsArr)) {
  2604. $existingCommentsArr = [];
  2605. }
  2606. // Validar que el operario no haya registrado comentario ya
  2607. if (isset($existingCommentsArr['COMENTARIOS_OPERADORES']) && is_array($existingCommentsArr['COMENTARIOS_OPERADORES'])) {
  2608. foreach ($existingCommentsArr['COMENTARIOS_OPERADORES'] as $existingComment) {
  2609. if (isset($existingComment['ID']) && $existingComment['ID'] === $idUser) {
  2610. DB::rollBack();
  2611. return $this->responseController->makeResponse(true, 'Ya ha registrado su comentario de finalización para esta visita.', [], 400);
  2612. }
  2613. }
  2614. }
  2615. // Registrar el comentario del operario
  2616. $now = $this->functionsController->now();
  2617. $nowStr = $now->toDateTimeString();
  2618. $operatorName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2619. $cpStatus['COMENTARIOS_OPERARIOS'][] = [
  2620. 'ID' => $idUser,
  2621. 'COMENTARIO' => $form['comment'],
  2622. 'FECHA' => $nowStr
  2623. ];
  2624. // Actualizar el objeto en el historial
  2625. $statusHistoryArr[$cpStatusIndex] = $cpStatus;
  2626. $statusHistoryStr = json_encode($statusHistoryArr);
  2627. // Contar comentarios registrados vs total de operarios
  2628. $updatedCommentsArr = json_decode($visit->RVTN_COME, true);
  2629. $commentsRegistered = isset($updatedCommentsArr['COMENTARIOS_OPERADORES']) ? count($updatedCommentsArr['COMENTARIOS_OPERADORES']) : 0;
  2630. $totalOperators = count($acceptedOperators);
  2631. $isComplete = $commentsRegistered >= $totalOperators;
  2632. // Preparar actualización de la visita
  2633. $updateArr = [
  2634. 'RVTN_HIES' => $statusHistoryStr,
  2635. 'RVTN_USMO' => $idUser,
  2636. 'RVTN_FEMO' => $nowStr,
  2637. ];
  2638. // Si es el primer comentario, cambiar estado de EP a CP
  2639. if ($isFirstComment) {
  2640. $updateArr['RVTN_ESTA'] = 'CP';
  2641. $updateArr['RVTN_UARE'] = $idUser;
  2642. $updateArr['RVTN_FARE'] = $nowStr;
  2643. }
  2644. // Actualizar comentarios de operadores
  2645. $commentsArr = json_decode($visit->RVTN_COME, true);
  2646. if (!is_array($commentsArr)) {
  2647. $commentsArr = [];
  2648. }
  2649. // Inicializar array de comentarios de operadores si no existe
  2650. if (!isset($commentsArr['COMENTARIOS_OPERADORES']) || !is_array($commentsArr['COMENTARIOS_OPERADORES'])) {
  2651. $commentsArr['COMENTARIOS_OPERADORES'] = [];
  2652. }
  2653. // Agregar comentario del operario
  2654. $commentsArr['COMENTARIOS_OPERADORES'][] = [
  2655. 'ID' => $idUser,
  2656. 'COMENTARIO' => $form['comment'],
  2657. 'FECHA' => $nowStr
  2658. ];
  2659. $commentsStr = json_encode($commentsArr);
  2660. $updateArr['RVTN_COME'] = $commentsStr;
  2661. // Actualizar la visita
  2662. DB::table('S002V01TRVTN')->where([
  2663. ['RVTN_NULI', '=', $form['linea']],
  2664. ['RVTN_IDVI', '=', $idVisit],
  2665. ])->update($updateArr);
  2666. // Obtener regulador para notificaciones
  2667. $regulatorId = $visit->RVTN_USRE;
  2668. $regulatorAudience = !empty($regulatorId) ? [$regulatorId] : [];
  2669. // Obtener audiencia completa (operarios y regulador) para notificación de cambio de estado
  2670. $audience = [];
  2671. if (!empty($lastVAStatus['ATENCION']) && is_array($lastVAStatus['ATENCION'])) {
  2672. foreach ($lastVAStatus['ATENCION'] as $item) {
  2673. if (($item['RESPUESTA'] ?? '') === 'A') {
  2674. $audience[] = $item['ID'];
  2675. }
  2676. }
  2677. }
  2678. if (!empty($regulatorId) && !in_array($regulatorId, $audience)) {
  2679. $audience[] = $regulatorId;
  2680. }
  2681. // Si es el primer comentario (cambio EP -> CP), notificar a todos
  2682. if ($isFirstComment && !empty($audience)) {
  2683. $notificationTitle = "Visita Técnica No Programada #$idVisit";
  2684. $notificationMessage = "La visita técnica no programada #$idVisit ha pasado a estado Cerrado Pendiente.";
  2685. $this->notificationsController->emitNotification(
  2686. 'S002V01M10GMPR',
  2687. $notificationTitle,
  2688. $notificationMessage,
  2689. [[
  2690. 'BOTON' => 'Ver detalles',
  2691. 'FUNCION' => 'openPreventiveWorkOrderDetails',
  2692. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  2693. ], [
  2694. 'BOTON' => 'Ir al módulo',
  2695. 'FUNCION' => 'openModule',
  2696. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  2697. ]],
  2698. $audience,
  2699. $idUser,
  2700. $form['linea'],
  2701. $this->getSocketClient(),
  2702. $idVisit,
  2703. 'Preventivo'
  2704. );
  2705. }
  2706. // Notificar al regulador por cada comentario registrado
  2707. if (!empty($regulatorAudience)) {
  2708. $notificationTitle = "Visita Técnica No Programada #$idVisit";
  2709. $notificationMessage = "El usuario $operatorName ($idUser) registró comentario de finalización de la visita #$idVisit.";
  2710. $this->notificationsController->emitNotification(
  2711. 'S002V01M10GMPR',
  2712. $notificationTitle,
  2713. $notificationMessage,
  2714. [[
  2715. 'BOTON' => 'Ver detalles',
  2716. 'FUNCION' => 'openPreventiveWorkOrderDetails',
  2717. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  2718. ], [
  2719. 'BOTON' => 'Ir al módulo',
  2720. 'FUNCION' => 'openModule',
  2721. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  2722. ]],
  2723. $regulatorAudience,
  2724. $idUser,
  2725. $form['linea'],
  2726. $this->getSocketClient(),
  2727. $idVisit,
  2728. 'Preventivo'
  2729. );
  2730. }
  2731. // Si todos los comentarios están completos, enviar notificación final
  2732. if ($isComplete && !empty($regulatorAudience)) {
  2733. $finalNotificationTitle = "Visita Técnica No Programada #$idVisit";
  2734. $finalNotificationMessage = "La visita #$idVisit ya puede ser cerrada. Todos los operarios han registrado sus comentarios de finalización.";
  2735. $this->notificationsController->emitNotification(
  2736. 'S002V01M10GMPR',
  2737. $finalNotificationTitle,
  2738. $finalNotificationMessage,
  2739. [[
  2740. 'BOTON' => 'Cerrar visita',
  2741. 'FUNCION' => 'closePreventiveVisit',
  2742. 'PARAMETROS' => json_encode([
  2743. $this->encryptionController->encrypt($idVisit),
  2744. $this->encryptionController->encrypt($form['linea']),
  2745. $this->encryptionController->encrypt($regulatorId)
  2746. ])
  2747. ], [
  2748. 'BOTON' => 'Ver detalles',
  2749. 'FUNCION' => 'openPreventiveWorkOrderDetails',
  2750. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  2751. ], [
  2752. 'BOTON' => 'Ir al módulo',
  2753. 'FUNCION' => 'openModule',
  2754. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  2755. ]],
  2756. $regulatorAudience,
  2757. $idUser,
  2758. $form['linea'],
  2759. $this->getSocketClient(),
  2760. $idVisit,
  2761. 'Preventivo'
  2762. );
  2763. }
  2764. // Confirmar transacción
  2765. DB::commit();
  2766. $actions = DB::getQueryLog();
  2767. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2768. $idac = $this->functionsController->registerActivity(
  2769. $form['linea'],
  2770. 'S002V01M10GMPR',
  2771. 'S002V01F11RVTP',
  2772. 'S002V01P01REVI',
  2773. 'Actualización',
  2774. "El usuario $name (" . $usr->USUA_IDUS . ") registró comentario de finalización para la visita no programada #$idVisit.",
  2775. $idUser,
  2776. $nowStr,
  2777. 'S002V01S02AOTR'
  2778. );
  2779. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2780. return $this->responseController->makeResponse(false, 'EXITO.', [
  2781. 'comments_registered' => $commentsRegistered,
  2782. 'total_operators' => $totalOperators,
  2783. 'is_complete' => $isComplete
  2784. ]);
  2785. } catch (\Exception $e) {
  2786. // Revertir transacción en caso de error
  2787. DB::rollBack();
  2788. $actions = DB::getQueryLog();
  2789. $now = $this->functionsController->now();
  2790. $nowStr = $now->toDateTimeString();
  2791. $name = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
  2792. $idac = $this->functionsController->registerActivity(
  2793. $form['linea'],
  2794. 'S002V01M10GMPR',
  2795. 'S002V01F11RVTP',
  2796. 'S002V01P01REVI',
  2797. 'Error',
  2798. "Error al registrar comentario de finalización para la visita no programada #$idVisit: " . $e->getMessage(),
  2799. $idUser,
  2800. $nowStr,
  2801. 'S002V01S02AOTR'
  2802. );
  2803. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2804. return $this->responseController->makeResponse(
  2805. true,
  2806. 'Ocurrió un error al registrar el comentario de finalización.',
  2807. ['error' => $e->getMessage()],
  2808. 500
  2809. );
  2810. }
  2811. }
  2812. // Visitas técnicas no programadas (Preventivas)
  2813. public function startPreventiveVisit(Request $request){
  2814. DB::enableQueryLog();
  2815. $validator = Validator::make($request->all(), [
  2816. 'id_user' => 'required|string',
  2817. 'linea' => 'required|integer',
  2818. 'id_visit' => 'required|string'
  2819. ]);
  2820. if ($validator->fails()) {
  2821. return $this->responseController->makeResponse(
  2822. true,
  2823. "Se encontraron uno o más errores.",
  2824. $this->responseController->makeErrors(
  2825. $validator->errors()->messages()
  2826. ),
  2827. 401
  2828. );
  2829. }
  2830. $form = $request->all();
  2831. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2832. if (!$idUser) {
  2833. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2834. }
  2835. $usr = DB::table('S002V01TUSUA')->where([
  2836. ['USUA_NULI', '=', $form['linea']],
  2837. ['USUA_IDUS', '=', $idUser]
  2838. ])->first();
  2839. if (is_null($usr)) {
  2840. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  2841. }
  2842. $idVisit = $this->encryptionController->decrypt($form['id_visit']);
  2843. if (!$idVisit) {
  2844. return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
  2845. }
  2846. $visit = DB::table('S002V01TRVTN')->where([
  2847. ['RVTN_NULI', '=', $form['linea']],
  2848. ['RVTN_IDVI', '=', $idVisit]
  2849. ])->first();
  2850. if (is_null($visit)) {
  2851. return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
  2852. }
  2853. $visitStates = [
  2854. 'PE' => 'Pendiente',
  2855. 'CA' => 'Cancelado',
  2856. 'RE' => 'Rechazado',
  2857. 'EL' => 'Eliminado',
  2858. 'VA' => 'Validado',
  2859. 'EP' => 'En Proceso',
  2860. 'CP' => 'Cerrado Pendiente',
  2861. 'CE' => 'Cerrado'
  2862. ];
  2863. if ($visit->RVTN_ESTA !== 'VA') {
  2864. $statusKey = $visit->RVTN_ESTA;
  2865. $statusName = array_key_exists($statusKey, $visitStates) ? $visitStates[$statusKey] : $statusKey;
  2866. return $this->responseController->makeResponse(true, "La visita está $statusName.", [], 401);
  2867. }
  2868. if ($visit->RVTN_USRE != $idUser) {
  2869. return $this->responseController->makeResponse(true, 'El usuario que solicitó la acción no tiene los permisos necesarios.', [], 401);
  2870. }
  2871. $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
  2872. if (!is_array($statusHistoryArr)) {
  2873. $statusHistoryArr = [];
  2874. }
  2875. // Buscar objeto VA en el historial
  2876. // Si no existe pero RVTN_ESTA == 'VA', la visita está validada pero aún no tiene operarios asignados
  2877. $validatedHistoryFilt = array_filter($statusHistoryArr, function ($item) {
  2878. return array_key_exists('ESTADO', $item) && $item['ESTADO'] == 'VA';
  2879. });
  2880. $audience = [];
  2881. // Si existe el objeto VA en el historial, obtener los operarios aceptados
  2882. if (!empty($validatedHistoryFilt)) {
  2883. $validatedStatus = end($validatedHistoryFilt);
  2884. if (array_key_exists('ATENCION', $validatedStatus) && is_array($validatedStatus['ATENCION'])) {
  2885. foreach ($validatedStatus['ATENCION'] as $item) {
  2886. if (($item['RESPUESTA'] ?? '') === 'A') {
  2887. $audience[] = $item['ID'];
  2888. }
  2889. }
  2890. }
  2891. }
  2892. // Si no existe el objeto VA en el historial pero RVTN_ESTA == 'VA',
  2893. // la audiencia quedará vacía (no hay operarios asignados aún)
  2894. $now = $this->functionsController->now();
  2895. $nowStr = $now->toDateTimeString();
  2896. $statusHistoryArr[] = [
  2897. 'USUARIO' => $idUser,
  2898. 'ESTADO' => 'EP',
  2899. 'FECHA' => $nowStr
  2900. ];
  2901. $statusHistoryStr = json_encode($statusHistoryArr);
  2902. /*
  2903. $commentsArr = json_decode($visit->RVTN_COME, true);
  2904. if (!is_array($commentsArr)) {
  2905. $commentsArr = [];
  2906. }
  2907. $commentsArr['COMENTARIO_INICIO'] = $form['comments'];
  2908. $commentsStr = json_encode($commentsArr);
  2909. */
  2910. DB::table('S002V01TRVTN')->where([
  2911. ['RVTN_IDVI', '=', $idVisit],
  2912. ['RVTN_NULI', '=', $form['linea']]
  2913. ])->update([
  2914. 'RVTN_ESTA' => 'EP',
  2915. 'RVTN_HIES' => $statusHistoryStr,
  2916. 'RVTN_USMO' => $idUser,
  2917. 'RVTN_FEMO' => $nowStr,
  2918. ]);
  2919. $this->notificationsController->emitNotification(
  2920. 'S002V01M10GMPR',
  2921. "Visita Técnica No Programada #$idVisit",
  2922. "Inicio de la ejecución de la visita técnica no programada #$idVisit.",
  2923. [[
  2924. 'BOTON' => 'Ver detalles',
  2925. 'FUNCION' => 'openPreventiveWorkOrderDetails',
  2926. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  2927. ], [
  2928. 'BOTON' => 'Ir al módulo',
  2929. 'FUNCION' => 'openModule',
  2930. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  2931. ]],
  2932. $audience,
  2933. $idUser,
  2934. $form['linea'],
  2935. $this->getSocketClient(),
  2936. $idVisit,
  2937. 'Preventivo'
  2938. );
  2939. $actions = DB::getQueryLog();
  2940. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2941. $idac = $this->functionsController->registerActivity(
  2942. $form['linea'],
  2943. 'S002V01M10GMPR',
  2944. 'S002V01F11RVTP',
  2945. 'S002V01P01REVI',
  2946. 'Actualización',
  2947. "El usuario $name (" . $usr->USUA_IDUS . ") inició la visita técnica no programada #$idVisit.",
  2948. $idUser,
  2949. $nowStr,
  2950. 'S002V01S02AOTR'
  2951. );
  2952. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2953. return $this->responseController->makeResponse(false, 'EXITO.');
  2954. }
  2955. public function updateOrderStatus(Request $request){
  2956. DB::enableQueryLog();
  2957. $validator = Validator::make($request->all(), [
  2958. 'id_user' => 'required|string',
  2959. 'linea' => 'required|integer',
  2960. 'id_order' => 'required|string',
  2961. 'status' => 'required|string|in:B,R,A,E'
  2962. ]);
  2963. if($validator->fails()){
  2964. return $this->responseController->makeResponse(
  2965. true,
  2966. "Se encontraron uno o más errores.",
  2967. $this->responseController->makeErrors(
  2968. $validator->errors()->messages()
  2969. ),
  2970. 401
  2971. );
  2972. }
  2973. $form = $request->all();
  2974. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2975. if(!$idUser){
  2976. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2977. }
  2978. $usr = DB::table('S002V01TUSUA')->where([
  2979. ['USUA_NULI', '=', $form['linea']],
  2980. ['USUA_IDUS', '=', $idUser],
  2981. ])->first();
  2982. if(is_null($usr)){
  2983. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2984. }
  2985. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  2986. if(!$idOrder){
  2987. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  2988. }
  2989. $order = DB::table('S002V01TOTPR')->where([
  2990. ['OTPR_NULI', '=', $form['linea']],
  2991. ['OTPR_IDOT', '=', $idOrder],
  2992. ])->first();
  2993. if(is_null($order)){
  2994. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  2995. }
  2996. if($form['status'] == 'A' && $order->OTPR_SEAN == null){
  2997. return $this->responseController->makeResponse(true, 'La orden no puede ser aprobada sin la asignación del análisis presupuestario.', [], 401);
  2998. }
  2999. $statusStr = '';
  3000. switch($form['status']){
  3001. case 'B': $statusStr = 'Borrador'; break;
  3002. case 'R': $statusStr = 'Revisión'; break;
  3003. case 'A': $statusStr = 'Aprobado'; break;
  3004. case 'E': $statusStr = 'Eliminado'; break;
  3005. }
  3006. $now = $this->functionsController->now();
  3007. $nowStr = $now->toDateTimeString();
  3008. DB::table('S002V01TOTPR')->where([
  3009. ['OTPR_NULI', '=', $form['linea']],
  3010. ['OTPR_IDOT', '=', $idOrder],
  3011. ])->update([
  3012. 'OTPR_ESTA' => $form['status'],
  3013. 'OTPR_USMO' => $idUser,
  3014. 'OTPR_FEMO' => $nowStr
  3015. ]);
  3016. $actions = DB::getQueryLog();
  3017. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3018. $idac = $this->functionsController->registerActivity(
  3019. $form['linea'],
  3020. 'S002V01M10GMPR',
  3021. 'S002V01F01COTP',
  3022. 'S002V01P01HOTP',
  3023. 'Actualización',
  3024. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden #$idOrder a $statusStr.",
  3025. $idUser,
  3026. $nowStr,
  3027. 'S002V01S01ORTR'
  3028. );
  3029. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3030. return $this->responseController->makeResponse(false, 'EXITO.');
  3031. }
  3032. public function setBudgetAnalysis(Request $request){
  3033. DB::enableQueryLog();
  3034. $validator = Validator::make($request->all(), [
  3035. 'id_user' => 'required|string',
  3036. 'linea' => 'required|integer',
  3037. 'id_order' => 'required|string',
  3038. 'analysis' => 'required|json'
  3039. ]);
  3040. if($validator->fails()){
  3041. return $this->responseController->makeResponse(
  3042. true,
  3043. "Se encontraron uno o más errores.",
  3044. $this->responseController->makeErrors(
  3045. $validator->errors()->messages()
  3046. ),
  3047. 401
  3048. );
  3049. }
  3050. $form = $request->all();
  3051. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3052. if(!$idUser){
  3053. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3054. }
  3055. $usr = DB::table('S002V01TUSUA')->where([
  3056. ['USUA_NULI', '=', $form['linea']],
  3057. ['USUA_IDUS', '=', $idUser],
  3058. ])->first();
  3059. if(is_null($usr)){
  3060. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3061. }
  3062. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  3063. if(!$idOrder){
  3064. return $this->responseController->makeResponse(true, 'El ID de la orden no está encriptado correctamente.', [], 400);
  3065. }
  3066. $order = DB::table('S002V01TOTPR')->where([
  3067. ['OTPR_NULI', '=', $form['linea']],
  3068. ['OTPR_IDOT', '=', $idOrder]
  3069. ])->first();
  3070. if(is_null($order)){
  3071. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  3072. }
  3073. $analysisArr = json_decode($form['analysis'], true);
  3074. if(empty($analysisArr)){
  3075. return $this->responseController->makeResponse(true, 'El JSON de análisis no contiene información.', [], 400);
  3076. }else if(!array_key_exists('teamsConf', $analysisArr)){
  3077. return $this->responseController->makeResponse(true, 'La información de la configuración de los equipos no se envió en el JSON.', [], 400);
  3078. }else if(!is_array($analysisArr['teamsConf'])){
  3079. return $this->responseController->makeResponse(true, 'La configuración de los equipos tiene un formato inválido.', [], 400);
  3080. }
  3081. $teamsConf = $analysisArr['teamsConf'];
  3082. foreach($teamsConf as $key=>$conf){
  3083. $idDec = $this->encryptionController->decrypt($conf['ID']);
  3084. if(!$idDec){
  3085. return $this->responseController->makeResponse(true, "El ID del elemento en la posición $key del arreglo de especialidades no fue encriptado correctamente.", [], 400);
  3086. }
  3087. $conf['ID'] = $idDec;
  3088. $teamsConf[$key] = $conf;
  3089. }
  3090. $analysisArr['teamsConf'] = $teamsConf;
  3091. $now = $this->functionsController->now();
  3092. $nowStr = $now->toDateTimeString();
  3093. $sean = json_encode($analysisArr);
  3094. DB::table('S002V01TOTPR')->where([
  3095. ['OTPR_NULI', '=', $form['linea']],
  3096. ['OTPR_IDOT', '=', $idOrder],
  3097. ])->update([
  3098. 'OTPR_SEAN' => $sean,
  3099. 'OTPR_USMO' => $idUser,
  3100. 'OTPR_FEMO' => $nowStr
  3101. ]);
  3102. $actions = DB::getQueryLog();
  3103. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3104. $idac = $this->functionsController->registerActivity(
  3105. $form['linea'],
  3106. 'S002V01M10GMPR',
  3107. 'S002V01F01COTP',
  3108. 'S002V01P01HOTP',
  3109. 'Actualización',
  3110. "El usuario $name (" . $usr->USUA_IDUS . ") asignó el análisis presupuestario de la orden #$idOrder.",
  3111. $idUser,
  3112. $nowStr,
  3113. 'S002V01S01ORTR'
  3114. );
  3115. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3116. return $this->responseController->makeResponse(false, 'EXITO.');
  3117. }
  3118. public function getMaintenanceSimulation($idOrder, $idUser, $line){
  3119. DB::enableQueryLog();
  3120. $idUser = $this->encryptionController->decrypt($idUser);
  3121. if(!$idUser){
  3122. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3123. }
  3124. $usr = DB::table('S002V01TUSUA')->where([
  3125. ['USUA_NULI', '=', $line],
  3126. ['USUA_IDUS', '=', $idUser],
  3127. ])->first();
  3128. if(is_null($usr)){
  3129. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3130. }
  3131. $idOrder = $this->encryptionController->decrypt($idOrder);
  3132. if(!$idOrder){
  3133. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3134. }
  3135. $order = DB::table('S002V01TOTPR')->select([
  3136. 'OTPR_IDOT AS IDORDER',
  3137. 'OTPR_DEIN AS DESCRIPCION',
  3138. 'OTPR_ININ AS INSTRUCCIONES',
  3139. 'OTPR_EQIN AS EQUIPAMIENTO',
  3140. 'OTPR_FIAP AS FECHAINICIO',
  3141. 'OTPR_FTAP AS FECHAFINAL',
  3142. 'OTPR_SEAN AS ANALISIS',
  3143. 'OTPR_TIIN AS TIEINMEST',
  3144. 'OTPR_OPPR AS OPERARIOS',
  3145. 'OTPR_DTIN AS TIETOTEST',
  3146. 'OTPR_RHRE AS RECURSOS',
  3147. 'OTPR_ACAS AS ACTIVADOR',
  3148. 'OTPR_ESTA AS ESTADO',
  3149. 'ACTI_PRIO AS PRIORIDAD',
  3150. 'ACTI_TIAC AS TIPOACTIVADOR',
  3151. 'ACTI_COAC AS CONFIGACTI'
  3152. ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  3153. ['OTPR_NULI', '=', $line],
  3154. ['OTPR_IDOT', '=', $idOrder]
  3155. ])->first();
  3156. if(is_null($order)){
  3157. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  3158. }else if($order->ESTADO == 'B'){
  3159. return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en borradores.', [], 401);
  3160. }else if($order->ESTADO == 'R'){
  3161. return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en revisión.', [], 401);
  3162. }else if($order->ESTADO == 'E'){
  3163. return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque ha sido eliminado.', [], 401);
  3164. }
  3165. $analisisArr = json_decode($order->ANALISIS, true);
  3166. $teamsConf = $analisisArr['teamsConf'];
  3167. foreach($teamsConf as $key=>$val){
  3168. $val['ID'] = $this->encryptionController->encrypt($val['ID']);
  3169. $teamsConf[$key] = $val;
  3170. }
  3171. $analisisArr['teamsConf'] = $teamsConf;
  3172. $order->ANALISIS = json_encode($analisisArr);
  3173. $actions = DB::getQueryLog();
  3174. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3175. $now = $this->functionsController->now();
  3176. $nowStr = $now->toDateTimeString();
  3177. $idac = $this->functionsController->registerActivity(
  3178. $line,
  3179. 'S002V01M10GMPR',
  3180. 'S002V01F06SPMA',
  3181. 'S002V01P02VSPM',
  3182. 'Consulta',
  3183. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la simulación de la orden #$idOrder.",
  3184. $idUser,
  3185. $nowStr,
  3186. 'S002V01S02AOTR'
  3187. );
  3188. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3189. return $this->responseController->makeResponse(false, 'EXITO.', $order);
  3190. }
  3191. public function getOrderWithActivator($idOrder, $idUser, $line){
  3192. DB::enableQueryLog();
  3193. $idUser = $this->encryptionController->decrypt($idUser);
  3194. if(!$idUser){
  3195. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3196. }
  3197. $usr = DB::table('S002V01TUSUA')->where([
  3198. ['USUA_NULI', '=', $line],
  3199. ['USUA_IDUS', '=', $idUser],
  3200. ])->first();
  3201. if(is_null($usr)){
  3202. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3203. }
  3204. $idOrder = $this->encryptionController->decrypt($idOrder);
  3205. if(!$idOrder){
  3206. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3207. }
  3208. $order = DB::table('S002V01TOTPR')->select([
  3209. 'OTPR_IDOT AS IDORDEN',
  3210. 'OTPR_DEIN AS DESCRIPCION',
  3211. 'OTPR_ININ AS INSTRUCCIONES',
  3212. 'OTPR_EQIN AS EQUIPAMIENTO',
  3213. 'OTPR_FIAP AS FECHAINICIO',
  3214. 'OTPR_FTAP AS FECHAFINAL',
  3215. 'OTPR_TIIN AS TIEINMEST',
  3216. 'OTPR_DTIN AS TIETOTEST',
  3217. 'OTPR_ACAS AS ACTIVADOR',
  3218. 'OTPR_CLAS AS CLASIFICACION',
  3219. 'OTPR_ESTA AS ESTADO',
  3220. 'ACTI_PRIO AS PRIORIDAD',
  3221. 'ACTI_TIAC AS TIPOACTIVADOR',
  3222. 'ACTI_COAC AS CONFIGACTIVADOR',
  3223. ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  3224. ['OTPR_NULI', '=', $line],
  3225. ['OTPR_IDOT', '=', $idOrder],
  3226. ])->first();
  3227. if(is_null($order)){
  3228. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3229. }
  3230. $now = $this->functionsController->now();
  3231. $nowStr = $now->toDateTimeString();
  3232. $actions = DB::getQueryLog();
  3233. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3234. $idac = $this->functionsController->registerActivity(
  3235. $line,
  3236. 'S002V01M10GMPR',
  3237. 'S002V01F02AFDT',
  3238. 'S002V01P01OTAT',
  3239. 'Consulta',
  3240. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la información de la orden #$idOrder.",
  3241. $idUser,
  3242. $nowStr,
  3243. 'S002V01S02AOTR'
  3244. );
  3245. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3246. return $this->responseController->makeResponse(false, 'EXITO.', $order);
  3247. }
  3248. public function updateOrderWithActivator(Request $request){
  3249. DB::enableQueryLog();
  3250. $validator = Validator::make($request->all(), [
  3251. 'id_user' => 'required|string',
  3252. 'linea' => 'required|integer',
  3253. 'id_order' => 'required|string',
  3254. 'id_activator' => 'required|string',
  3255. 'start_date' => 'required|date',
  3256. 'end_date' => 'required|date',
  3257. 'activator_type' => 'required|string|in:Calendario,Sintoma,Medida,Valor',
  3258. 'priority' => 'required|string|in:1,2,3,4',
  3259. 'config_activator' => 'required|json',
  3260. ]);
  3261. if($validator->fails()){
  3262. return $this->responseController->makeResponse(
  3263. true,
  3264. "Se encontraron uno o más errores.",
  3265. $this->responseController->makeErrors(
  3266. $validator->errors()->messages()
  3267. ),
  3268. 401
  3269. );
  3270. }
  3271. $form = $request->all();
  3272. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3273. if(!$idUser){
  3274. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3275. }
  3276. $usr = DB::table('S002V01TUSUA')->where([
  3277. ['USUA_IDUS', '=', $idUser],
  3278. ['USUA_NULI', '=', $form['linea']],
  3279. ])->first();
  3280. if(is_null($usr)){
  3281. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3282. }
  3283. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  3284. if(!$idOrder){
  3285. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3286. }
  3287. $order = DB::table('S002V01TOTPR')->where([
  3288. ['OTPR_NULI', '=', $form['linea']],
  3289. ['OTPR_IDOT', '=', $idOrder],
  3290. ])->first();
  3291. if(is_null($order)){
  3292. return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404);
  3293. }
  3294. $idActivator = $this->encryptionController->decrypt($form['id_activator']);
  3295. if(!$idActivator){
  3296. return $this->responseController->makeResponse(true, 'El ID del activador solicitado no está encriptado correctamente.', [], 400);
  3297. }
  3298. $activator = DB::table('S002V01TACTI')->where([
  3299. ['ACTI_IDAC', '=', $idActivator],
  3300. ['ACTI_NULI', '=', $form['linea']]
  3301. ])->first();
  3302. if(is_null($activator)){
  3303. return $this->responseController->makeResponse(true, 'El activador solicitado no existe.', [], 404);
  3304. }
  3305. $now = $this->functionsController->now();
  3306. $nowStr = $now->toDateTimeString();
  3307. DB::table('S002V01TOTPR')->where([
  3308. ['OTPR_NULI', '=', $form['linea']],
  3309. ['OTPR_IDOT', '=', $idOrder],
  3310. ])->update([
  3311. 'OTPR_ACAS' => $idActivator,
  3312. 'OTPR_FIAP' => $form['start_date'],
  3313. 'OTPR_FTAP' => $form['end_date'],
  3314. 'OTPR_USMO' => $idUser,
  3315. 'OTPR_FEMO' => $nowStr,
  3316. ]);
  3317. DB::table('S002V01TACTI')->where([
  3318. ['ACTI_IDAC', '=', $idActivator],
  3319. ['ACTI_NULI', '=', $form['linea']]
  3320. ])->update([
  3321. 'ACTI_PRIO' => $form['priority'],
  3322. 'ACTI_TIAC' => $form['activator_type'],
  3323. 'ACTI_COAC' => $form['config_activator'],
  3324. 'ACTI_USMO' => $idUser,
  3325. 'ACTI_FEMO' => $nowStr,
  3326. ]);
  3327. $actions = DB::getQueryLog();
  3328. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3329. $idac = $this->functionsController->registerActivity(
  3330. $form['linea'],
  3331. 'S002V01M10GMPR',
  3332. 'S002V01F02AFDT',
  3333. 'S002V01P02ACAC',
  3334. 'Actualización',
  3335. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden #$idOrder y el activador #$idActivator.",
  3336. $idUser,
  3337. $nowStr,
  3338. 'S002V01S02AOTR'
  3339. );
  3340. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3341. return $this->responseController->makeResponse(false, 'EXITO.');
  3342. }
  3343. public function printOrderSimulation($idOrder, $idUser, $line){
  3344. DB::enableQueryLog();
  3345. $idUser = $this->encryptionController->decrypt($idUser);
  3346. if(!$idUser){
  3347. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3348. }
  3349. $usr = DB::table('S002V01TUSUA')->where([
  3350. ['USUA_NULI', '=', $line],
  3351. ['USUA_IDUS', '=', $idUser],
  3352. ])->first();
  3353. if(is_null($usr)){
  3354. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3355. }
  3356. $idOrder = $this->encryptionController->decrypt($idOrder);
  3357. if(!$idOrder){
  3358. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3359. }
  3360. $order = DB::table('S002V01TOTPR')->where([
  3361. ['OTPR_NULI', '=', $line],
  3362. ['OTPR_IDOT', '=', $idOrder]
  3363. ])->first();
  3364. if(is_null($order)){
  3365. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3366. }
  3367. $simulation = DB::table('S002V01TRESI')->where([
  3368. ['RESI_NULI', '=', $line],
  3369. ['RESI_IDOT', '=', $idOrder]
  3370. ])->first();
  3371. if(is_null($simulation)){
  3372. return $this->responseController->makeResponse(true, "La orden #$idOrder aún no ha sido simulada.", [], 401);
  3373. }
  3374. $content = json_decode($simulation->RESI_CUSI, true);
  3375. $html = "
  3376. <html>
  3377. <head>
  3378. <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">
  3379. <style>
  3380. .main-icon-cell{
  3381. width: 50px;
  3382. height: 50px;
  3383. }
  3384. .main-icon-container{
  3385. width: 50px;
  3386. height: 50px;
  3387. border-radius: 64px;
  3388. border-style: solid;
  3389. padding-left: 8px;
  3390. padding-top: 8px;
  3391. border-color: rgba(0, 0, 0, 0.8);
  3392. }
  3393. .icon-container{
  3394. padding-left: 8px;
  3395. width: 42px;
  3396. height: 42px;
  3397. }
  3398. .instruction-font{
  3399. color: rgba(0, 0, 0, 0.8);
  3400. font-size: 24px;
  3401. padding-left: 8px;
  3402. font-weight: 600;
  3403. }
  3404. .space-cell{
  3405. width: 50px;
  3406. }
  3407. </style>
  3408. </head>
  3409. <body>
  3410. <table width=\"100%\">
  3411. ";
  3412. foreach($content as $item){
  3413. $imgContent = file_get_contents("C:\inetpub\wwwroot\sam\storage\app\\files\\$item[icon].png");
  3414. $imgB64 = "data:image/png;base64, " . base64_encode($imgContent);
  3415. $html .= "
  3416. <tr>
  3417. ";
  3418. if(!$item['isMain']){
  3419. $html .= '<td class="space-cell"></td>';
  3420. }
  3421. $html .= "
  3422. <td class=\"main-icon-cell\">
  3423. <div class=\"
  3424. ";
  3425. if($item['isMain']){
  3426. $html .= 'main-icon-container">';
  3427. }else{
  3428. $html .= 'icon-container ">';
  3429. }
  3430. $html .= "
  3431. <img src=\"$imgB64\" width=\"42\" height=\"42\">
  3432. </div>
  3433. </td>
  3434. <td class=\"instruction-font\" colspan=\"
  3435. ";
  3436. if($item['isMain']){
  3437. $html .= '2';
  3438. }
  3439. $html .= "
  3440. \">$item[label]</td>
  3441. </tr>
  3442. ";
  3443. }
  3444. $html .= "
  3445. </table>
  3446. </body>
  3447. </html>";
  3448. $filePath = $this->functionsController->getBasePath() . '\public_files\\';
  3449. $noar = "simulacion_orden_$idOrder";
  3450. $exte = "pdf";
  3451. $line = intval($line);
  3452. $line = $line < 10 ? "0$line" : "$line";
  3453. $como = "GMPR";
  3454. $cldo = "OR";
  3455. $now = $this->functionsController->now();
  3456. $nowStr = $now->toDateTimeString();
  3457. $nowArr = explode(" ", $nowStr);
  3458. $dateArr = explode("-", $nowArr[0]);
  3459. $year = substr($dateArr[0], 2);
  3460. $fecr = $year . $dateArr[1] .$dateArr[2];
  3461. $sec = DB::table('S002V01TAFAL')->where([
  3462. ['AFAL_NULI', '=', $line],
  3463. ['AFAL_COMO', '=', $como],
  3464. ['AFAL_CLDO', '=', $cldo],
  3465. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3466. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  3467. for($i = strlen($nuse); $i < 6; $i++){
  3468. $nuse = "0$nuse";
  3469. }
  3470. $ver = DB::table('S002V01TAFAL')->where([
  3471. ['AFAL_NULI', '=', $line],
  3472. ['AFAL_COMO', '=', $como],
  3473. ['AFAL_CLDO', '=', $cldo],
  3474. ['AFAL_NOAR', '=', $noar],
  3475. ['AFAL_EXTE', '=', $exte],
  3476. ])->orderBy('AFAL_NUVE', 'desc')->first();
  3477. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  3478. for($i = strlen($nuve); $i < 2; $i++){
  3479. $nuve = "0$nuve";
  3480. }
  3481. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  3482. $dompdf = new Dompdf();
  3483. $dompdf ->loadHtml($html);
  3484. $dompdf->setPaper('A4', 'portrait');
  3485. $dompdf->render();
  3486. $output = $dompdf->output();
  3487. $tempFile = $filePath . $fileName;
  3488. if(!file_exists($tempFile)){
  3489. fopen($tempFile, 'w');
  3490. }
  3491. file_put_contents($tempFile, $output);
  3492. $ubic = Storage::putFile('files', new File($tempFile));
  3493. $ubic = str_replace("/", "\\", $ubic);
  3494. $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
  3495. $tama = filesize($ubic);
  3496. $usac = json_encode([$idUser]);
  3497. unlink($tempFile);
  3498. DB::table('S002V01TAFAL')->insert([
  3499. 'AFAL_NULI' => $line,
  3500. 'AFAL_COMO' => $como,
  3501. 'AFAL_CLDO' => $cldo,
  3502. 'AFAL_FECR' => $fecr,
  3503. 'AFAL_NUSE' => $nuse,
  3504. 'AFAL_NUVE' => $nuve,
  3505. 'AFAL_NOAR' => $noar,
  3506. 'AFAL_EXTE' => $exte,
  3507. 'AFAL_TAMA' => $tama,
  3508. 'AFAL_UBIC' => $ubic,
  3509. 'AFAL_USAC' => $usac,
  3510. 'AFAL_USRE' => $idUser,
  3511. 'AFAL_FERE' => $nowStr,
  3512. ]);
  3513. $filesArr = json_decode($order->OTPR_DONE, true);
  3514. $filesArr[] = $fileName;
  3515. $filesStr = json_encode($filesArr);
  3516. DB::table('S002V01TOTPR')->where([
  3517. ['OTPR_NULI', '=', $line],
  3518. ['OTPR_IDOT', '=', $idOrder]
  3519. ])->update([
  3520. 'OTPR_DONE' => $filesStr,
  3521. 'OTPR_USMO' => $idUser,
  3522. 'OTPR_FEMO' => $nowStr
  3523. ]);
  3524. $actions = DB::getQueryLog();
  3525. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3526. $idac = $this->functionsController->registerActivity(
  3527. $line,
  3528. 'S002V01M10GMPR',
  3529. 'S002V01F06SPMA',
  3530. 'S002V01P02VSPM',
  3531. 'Registro',
  3532. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.",
  3533. $idUser,
  3534. $nowStr,
  3535. 'S002V01S02AOTR'
  3536. );
  3537. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3538. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  3539. }
  3540. public function saveOrderSimulation(Request $request){
  3541. DB::enableQueryLog();
  3542. $validator = Validator::make($request->all(), [
  3543. 'id_user' => 'required|string',
  3544. 'linea' => 'required|integer',
  3545. 'id_order' => 'required|string',
  3546. 'content' => 'required|json',
  3547. ]);
  3548. if ($validator->fails()) {
  3549. return $this->responseController->makeResponse(
  3550. true,
  3551. "Se encontraron uno o más errores.",
  3552. $this->responseController->makeErrors(
  3553. $validator->errors()->messages()
  3554. ),
  3555. 401
  3556. );
  3557. }
  3558. $form = $request->all();
  3559. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3560. if (!$idUser) {
  3561. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3562. }
  3563. $usr = DB::table('S002V01TUSUA')->where([
  3564. ['USUA_NULI', '=', $form['linea']],
  3565. ['USUA_IDUS', '=', $idUser],
  3566. ])->first();
  3567. if (is_null($usr)) {
  3568. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3569. }
  3570. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  3571. if(!$idOrder){
  3572. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3573. }
  3574. $order = DB::table('S002V01TOTPR')->where([
  3575. ['OTPR_NULI', '=', $form['linea']],
  3576. ['OTPR_IDOT', '=', $idOrder],
  3577. ])->first();
  3578. if(is_null($order)){
  3579. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  3580. }
  3581. $simulation = DB::table('S002V01TRESI')->where([
  3582. ['RESI_NULI', '=', $form['linea']],
  3583. ['RESI_IDOT', '=', $idOrder],
  3584. ])->first();
  3585. $now = $this->functionsController->now();
  3586. $nowStr = $now->toDateTimeString();
  3587. if(is_null($simulation)){
  3588. DB::table('S002V01TRESI')->insert([
  3589. 'RESI_NULI' => $form['linea'],
  3590. 'RESI_IDOT' => $idOrder,
  3591. 'RESI_CUSI' => $form['content'],
  3592. 'RESI_FUSI' => $nowStr,
  3593. 'RESI_UUSI' => $idUser,
  3594. ]);
  3595. }else{
  3596. $timestamp = $now->timestamp;
  3597. $history = $simulation->RESI_HISI == null ? [] : json_decode($simulation->RESI_HISI, true);
  3598. $history[$timestamp] = [
  3599. 'USUARIO' => $simulation->RESI_UUSI,
  3600. 'FECHA' => $simulation->RESI_FUSI,
  3601. 'CONTENIDO' => $simulation->RESI_CUSI,
  3602. ];
  3603. $historyStr = json_encode($history);
  3604. DB::table('S002V01TRESI')->where([
  3605. ['RESI_NULI', '=', $form['linea']],
  3606. ['RESI_IDOT', '=', $idOrder],
  3607. ])->update([
  3608. 'RESI_CUSI' => $form['content'],
  3609. 'RESI_FUSI' => $nowStr,
  3610. 'RESI_UUSI' => $idUser,
  3611. 'RESI_HISI' => $historyStr,
  3612. ]);
  3613. }
  3614. $actions = DB::getQueryLog();
  3615. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3616. $idac = $this->functionsController->registerActivity(
  3617. $form['linea'],
  3618. 'S002V01M10GMPR',
  3619. 'S002V01F06SPMA',
  3620. 'S002V01P02VSPM',
  3621. 'Registro',
  3622. "El usuario $name (" . $usr->USUA_IDUS . ") registró una simulación para la orden #$idOrder.",
  3623. $idUser,
  3624. $nowStr,
  3625. 'S002V01S02AOTR'
  3626. );
  3627. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3628. return $this->responseController->makeResponse(false, 'EXITO.');
  3629. }
  3630. public function printOrderDetails($idOrder, $idUser, $line){
  3631. DB::enableQueryLog();
  3632. $idUser = $this->encryptionController->decrypt($idUser);
  3633. if(!$idUser){
  3634. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3635. }
  3636. $usr = DB::table('S002V01TUSUA')->where([
  3637. ['USUA_NULI', '=', $line],
  3638. ['USUA_IDUS', '=', $idUser]
  3639. ])->first();
  3640. if(is_null($usr)){
  3641. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3642. }
  3643. $idOrder = $this->encryptionController->decrypt($idOrder);
  3644. if(!$idOrder){
  3645. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3646. }
  3647. $order = DB::table('S002V01TOTPR')->join(
  3648. 'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC',
  3649. )->where([
  3650. ['OTPR_NULI', '=', $line],
  3651. ['OTPR_IDOT', '=', $idOrder]
  3652. ])->first();
  3653. if(is_null($order)){
  3654. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3655. }
  3656. $html = "
  3657. <html>
  3658. <head>
  3659. <style>
  3660. table{
  3661. border-collapse: separate;
  3662. border-spacing: 0;
  3663. width: 100%;
  3664. }
  3665. .cell-title{
  3666. font-size: 12px;
  3667. font-weight: bold;
  3668. padding: 8px 8px 4px 8px;
  3669. }
  3670. .top-corners-radius{
  3671. border-radius: 4px 4px 0 0;
  3672. }
  3673. .left-bottom-corner-radius{
  3674. border-radius: 0 0 0 4px;
  3675. }
  3676. .right-bottom-corner-radius{
  3677. border-radius: 0 0 4px 0;
  3678. }
  3679. .cell-content{
  3680. padding: 4px 8px 8px 8px;
  3681. font-size: 16px;
  3682. color: rgba(0, 0, 0, 0.7);
  3683. }
  3684. .border-top{ border-top: 1px solid #dddddd; }
  3685. .border-left{ border-left: 1px solid #dddddd; }
  3686. .border-right{ border-right: 1px solid #dddddd; }
  3687. .border-bottom{ border-bottom: 1px solid #dddddd; }
  3688. </style>
  3689. </head>
  3690. <body>
  3691. <table>
  3692. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title top-corners-radius border-top border-left border-right\">Descripción</td></tr>
  3693. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">" . $order->OTPR_DEIN . "</td></tr>
  3694. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Instrucciones</td></tr>
  3695. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">
  3696. ";
  3697. $instructions = json_decode($order->OTPR_ININ, true);
  3698. $cont = 1;
  3699. foreach($instructions as $instruction){
  3700. $html .= $cont . ".- " . $instruction['INSTRUCCION'] . "<br>";
  3701. $cont++;
  3702. }
  3703. $startDate = $this->functionsController->formatDateTime($order->OTPR_FIAP);
  3704. $endDate = $this->functionsController->formatDateTime($order->OTPR_FTAP);
  3705. $html .= "
  3706. </td></tr>
  3707. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Equipamiento relacionado</td></tr>
  3708. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">" . $order->OTPR_EQIN . "</td></tr>
  3709. <tr>
  3710. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Fecha y hora de inicio</td>
  3711. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha y hora final</td>
  3712. </tr>
  3713. <tr>
  3714. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right\">$startDate</td>
  3715. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right\">$endDate</td>
  3716. </tr>
  3717. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Análisis presupuestario</td></tr>
  3718. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">
  3719. ";
  3720. $analisis = $order->OTPR_SEAN == null ? 'Sin configuración' : json_decode($order->OTPR_SEAN, true);
  3721. if(gettype($analisis) == 'array'){
  3722. //PENDIENTE
  3723. $teamsConf = $analisis['teamsConf'];
  3724. foreach($teamsConf as $key=>$team){
  3725. /*var_dump($key);
  3726. echo "<br>";*/
  3727. }
  3728. $html .= "
  3729. PENDIENTE
  3730. </td></tr>
  3731. ";
  3732. }else{
  3733. $html .= "
  3734. $analisis
  3735. </td></tr>
  3736. ";
  3737. }
  3738. $html .= "
  3739. <tr>
  3740. <td width=\"33%\" colspan=\"2\" class=\"cell-title border-top border-left border-right\">Clasificación</td>
  3741. <td width=\"34%\" colspan=\"2\" class=\"cell-title border-top border-right\">Duración total estimada</td>
  3742. <td width=\"33%\" colspan=\"2\" class=\"cell-title border-top border-right\">Tiempo de inmovilización estimado</td>
  3743. </tr>
  3744. <tr>
  3745. <td width=\"33%\" colspan=\"2\" class=\"cell-content border-left border-right\">" . $order->OTPR_CLAS . "</td>
  3746. <td width=\"34%\" colspan=\"2\" class=\"cell-content border-right\">" . $order->OTPR_DTIN . " hora(s)</td>
  3747. <td width=\"33%\" colspan=\"2\" class=\"cell-content border-right\">" . $order->OTPR_TIIN . " hora(s)</td>
  3748. </tr>
  3749. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Personal involucrado</td></tr>
  3750. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3751. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Recursos requerido</td></tr>
  3752. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3753. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Documentos requeridos</td></tr>
  3754. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3755. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Contratos requeridos</td></tr>
  3756. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3757. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Información del activador</td></tr>
  3758. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3759. <tr>
  3760. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Usuario que registró</td>
  3761. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha de registro</td>
  3762. </tr>
  3763. <tr>
  3764. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right\">PENDIENTE</td>
  3765. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right\">PENDIENTE</td>
  3766. </tr>
  3767. <tr>
  3768. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Usuario de la última modificación</td>
  3769. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha de la última modificación</td>
  3770. </tr>
  3771. <tr>
  3772. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right border-bottom left-bottom-corner-radius\">PENDIENTE</td>
  3773. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right border-bottom right-bottom-corner-radius\">PENDIENTE</td>
  3774. </tr>
  3775. </table>
  3776. </body>
  3777. </html>
  3778. ";
  3779. $filePath = $this->functionsController->getBasePath() . '\public_files\\';
  3780. $noar = "detalles_orden_$idOrder";
  3781. $exte = "pdf";
  3782. $line = intval($line);
  3783. $line = $line < 10 ? "0$line" : "$line";
  3784. $como = "GMPR";
  3785. $cldo = "OR";
  3786. $now = $this->functionsController->now();
  3787. $nowStr = $now->toDateTimeString();
  3788. $nowArr = explode(" ", $nowStr);
  3789. $dateArr = explode("-", $nowArr[0]);
  3790. $year = substr($dateArr[0], 2);
  3791. $fecr = $year . $dateArr[1] .$dateArr[2];
  3792. $sec = DB::table('S002V01TAFAL')->where([
  3793. ['AFAL_NULI', '=', $line],
  3794. ['AFAL_COMO', '=', $como],
  3795. ['AFAL_CLDO', '=', $cldo],
  3796. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3797. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  3798. for($i = strlen($nuse); $i < 6; $i++){
  3799. $nuse = "0$nuse";
  3800. }
  3801. $ver = DB::table('S002V01TAFAL')->where([
  3802. ['AFAL_NULI', '=', $line],
  3803. ['AFAL_COMO', '=', $como],
  3804. ['AFAL_CLDO', '=', $cldo],
  3805. ['AFAL_NOAR', '=', $noar],
  3806. ['AFAL_EXTE', '=', $exte],
  3807. ])->orderBy('AFAL_NUVE', 'desc')->first();
  3808. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  3809. for($i = strlen($nuve); $i < 2; $i++){
  3810. $nuve = "0$nuve";
  3811. }
  3812. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  3813. $dompdf = new Dompdf();
  3814. $dompdf->loadHtml($html);
  3815. $dompdf->setPaper('A4', 'portrait');
  3816. $dompdf->render();
  3817. $output = $dompdf->output();
  3818. $tempFile = $filePath . $fileName;
  3819. if(!file_exists($tempFile)){
  3820. fopen($tempFile, 'w');
  3821. }
  3822. file_put_contents($tempFile, $output);
  3823. $ubic = Storage::putFile('files', new File($tempFile));
  3824. $ubic = str_replace("/", "\\", $ubic);
  3825. $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
  3826. $tama = filesize($ubic);
  3827. $usac = json_encode([$idUser]);
  3828. unlink($tempFile);
  3829. DB::table('S002V01TAFAL')->insert([
  3830. 'AFAL_NULI' => $line,
  3831. 'AFAL_COMO' => $como,
  3832. 'AFAL_CLDO' => $cldo,
  3833. 'AFAL_FECR' => $fecr,
  3834. 'AFAL_NUSE' => $nuse,
  3835. 'AFAL_NUVE' => $nuve,
  3836. 'AFAL_NOAR' => $noar,
  3837. 'AFAL_EXTE' => $exte,
  3838. 'AFAL_TAMA' => $tama,
  3839. 'AFAL_UBIC' => $ubic,
  3840. 'AFAL_USAC' => $usac,
  3841. 'AFAL_USRE' => $idUser,
  3842. 'AFAL_FERE' => $nowStr,
  3843. ]);
  3844. $filesArr = json_decode($order->OTPR_DONE, true);
  3845. $filesArr[] = $fileName;
  3846. $filesStr = json_encode($filesArr);
  3847. DB::table('S002V01TOTPR')->where([
  3848. ['OTPR_NULI', '=', $line],
  3849. ['OTPR_IDOT', '=', $idOrder]
  3850. ])->update([
  3851. 'OTPR_DONE' => $filesStr,
  3852. 'OTPR_USMO' => $idUser,
  3853. 'OTPR_FEMO' => $nowStr
  3854. ]);
  3855. $actions = DB::getQueryLog();
  3856. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3857. $idac = $this->functionsController->registerActivity(
  3858. $line,
  3859. 'S002V01M10GMPR',
  3860. 'S002V01F06SPMA',
  3861. 'S002V01P02VSPM',
  3862. 'Registro',
  3863. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.",
  3864. $idUser,
  3865. $nowStr,
  3866. 'S002V01S02AOTR'
  3867. );
  3868. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3869. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  3870. }
  3871. public function extractMaintenancePlan($idOrder, $idUser, $line) {
  3872. DB::enableQueryLog();
  3873. $idUser = $this->encryptionController->decrypt($idUser);
  3874. if(!$idUser){
  3875. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3876. }
  3877. $usr = DB::table('S002V01TUSUA')->where([
  3878. ['USUA_NULI', '=', $line],
  3879. ['USUA_IDUS', '=', $idUser],
  3880. ])->first();
  3881. if(is_null($usr)){
  3882. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3883. }
  3884. $idOrder = $this->encryptionController->decrypt($idOrder);
  3885. if(!$idOrder){
  3886. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3887. }
  3888. $order = DB::table('S002V01TOTPR')->join(
  3889. 'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC',
  3890. )->where([
  3891. ['OTPR_NULI', '=', $line],
  3892. ['OTPR_IDOT', '=', $idOrder]
  3893. ])->first();
  3894. if(is_null($order)){
  3895. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3896. }
  3897. $html = file_get_contents($this->templatesUbic . "01-GMPR-PL-010101-000003=01=PDF_PLAN_MANTENIMIENTO.html");
  3898. $logo = file_get_contents($this->functionsController->getBasePath() . "\storage\app\public\global_resources\sam-short-logo.png");
  3899. $logoStr = "data:image/svg+xml;base64," . base64_encode($logo);
  3900. $html = str_replace("%stcImage%", $logoStr, $html);
  3901. $now = $this->functionsController->now();
  3902. $nowStr = $now->toDateTimeString();
  3903. $currentDate = $this->functionsController->buildHumanCurrentDate($nowStr);
  3904. $html = str_replace("%currentDate%", $currentDate, $html);
  3905. $html = str_replace("%idOrder%", $order->OTPR_IDOT, $html);
  3906. $startDateTimeArr = explode(" ", $order->OTPR_FIAP);
  3907. $startTimeArr = explode(":", $startDateTimeArr[1]);
  3908. $startHour = intval($startTimeArr[0]);
  3909. $startPeriod = $startHour < 12 ? 'AM' : 'PM';
  3910. $startHour = $startHour > 12 ? $startHour - 12 : $startHour;
  3911. $startTimeStr = "$startHour:$startTimeArr[1] $startPeriod";
  3912. $html = str_replace("%startTime%", $startTimeStr, $html);
  3913. $startDateTimeObj = new Carbon($order->OTPR_FIAP);
  3914. $totalDuration = floatval($order->OTPR_DTIN);
  3915. $totalDurationHours = intval($totalDuration);
  3916. $startDateTimeObj->addHours($totalDuration);
  3917. $totalDurationFloatMinutes = $this->functionsController->floatSub($totalDuration, $totalDurationHours);
  3918. $totalDurationFloatMinutes = $this->functionsController->floatMul($totalDurationFloatMinutes, 60);
  3919. $totalDurationMinutes = ceil($totalDurationFloatMinutes);
  3920. $startDateTimeObj->addMinutes($totalDurationMinutes);
  3921. $endDateTimeArr = explode(" ", $startDateTimeObj->toDateTimeString());
  3922. $endTimeArr = explode(":", $endDateTimeArr[1]);
  3923. $endHour = intval($endTimeArr[0]);
  3924. $endPeriod = $startHour < 12 ? 'AM' : 'PM';
  3925. $endHour = $endHour > 12 ? $endHour - 12 : $endHour;
  3926. $endTimeStr = "$endHour:$endTimeArr[1] $endPeriod";
  3927. $html = str_replace("%endTime%", $endTimeStr, $html);
  3928. $html = str_replace("%inmTime%", $order->OTPR_TIIN . " h", $html);
  3929. $html = str_replace("%totalTime%", $order->OTPR_DTIN . " h", $html);
  3930. $html = str_replace("%equipment%", $order->OTPR_EQIN, $html);
  3931. $html = str_replace("%description%", $order->OTPR_DEIN, $html);
  3932. $instructions = json_decode($order->OTPR_ININ, true);
  3933. $activitiesTableBody = "";
  3934. foreach($instructions as $k=>$v){
  3935. $key = $k + 1;
  3936. $activitiesTableBody .= "<tr>";
  3937. $activitiesTableBody .= "<td>$key</td>";
  3938. $activitiesTableBody .= "<td>$v[INSTRUCCION]</td>";
  3939. $activitiesTableBody .= "<td>";
  3940. /*foreach($v['ESPECIALIDADES'] as $v0){
  3941. /*$team = array_filter($teams, function($v1) use ($v0) {
  3942. return ($v1['ID'] == $v0);
  3943. });
  3944. $activitiesTableBody .= /*end($team)['ESP'] '--' . "<br>";
  3945. }*/
  3946. $activitiesTableBody .= "</td>";
  3947. $activitiesTableBody .= "</tr>";
  3948. }
  3949. $html = str_replace("%activitiesTableBody%", $activitiesTableBody, $html);
  3950. $personalArr = json_decode($order->OTPR_OPPR, true);
  3951. $constConf = json_decode($order->OTPR_SEAN, true);
  3952. $cont = 1;
  3953. $specialtiesTableBody = "";
  3954. foreach($personalArr as $k=>$v){
  3955. /*$team = array_filter($teams, function($v1) use ($k) {
  3956. return ($v1['ID'] == $k);
  3957. });*/
  3958. $specialtiesTableBody .= "<tr>";
  3959. $specialtiesTableBody .= "<td>$cont</td>";
  3960. $specialtiesTableBody .= "<td>" . /*end($team)['ESP']*/ '--' . "</td>";
  3961. $specialtiesTableBody .= "<td>";
  3962. foreach($constConf['teamsConf'][$k] as $v0){
  3963. $usrID = '-';//$v0['USER'];
  3964. $usrInv = DB::table('S002V01TUSUA')->where([
  3965. ['USUA_NULI', '=', $line],
  3966. ['USUA_IDUS', '=', $usrID],
  3967. ])->first();
  3968. $invName = /*$this->functionsController->joinName($usrInv->USUA_NOMB, $usrInv->USUA_APPA, $usrInv->USUA_APMA) . " ($usrID)"*/ '-';
  3969. $specialtiesTableBody .= $invName . "<br>";
  3970. }
  3971. $specialtiesTableBody .= "</td>";
  3972. $specialtiesTableBody .= "</tr>";
  3973. $cont++;
  3974. }
  3975. $html = str_replace("%specialtiesTableBody%", $specialtiesTableBody, $html);
  3976. $como = 'GMPR';
  3977. $cldo = 'OR';
  3978. $noar = "plan_de_mantenimiento_preventivo_orden_$idOrder";
  3979. $exte = "pdf";
  3980. $line = $line < 10 ? "0$line" : "$line";
  3981. $nowArr = explode(" ", $nowStr);
  3982. $dateArr = explode("-", $nowArr[0]);
  3983. $year = substr($dateArr[0], 2);
  3984. $fecr = $year . $dateArr[1] .$dateArr[2];
  3985. $sec = DB::table('S002V01TAFAL')->where([
  3986. ['AFAL_NULI', '=', $line],
  3987. ['AFAL_COMO', '=', $como],
  3988. ['AFAL_CLDO', '=', $cldo],
  3989. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3990. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  3991. for($i = strlen($nuse); $i < 6; $i++){
  3992. $nuse = "0$nuse";
  3993. }
  3994. $ver = DB::table('S002V01TAFAL')->where([
  3995. ['AFAL_NULI', '=', $line],
  3996. ['AFAL_COMO', '=', $como],
  3997. ['AFAL_CLDO', '=', $cldo],
  3998. ['AFAL_NOAR', '=', $noar],
  3999. ['AFAL_EXTE', '=', $exte],
  4000. ])->orderBy('AFAL_NUVE', 'desc')->first();
  4001. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  4002. for($i = strlen($nuve); $i < 2; $i++){
  4003. $nuve = "0$nuve";
  4004. }
  4005. $filePath = $this->functionsController->getBasePath() . '\public_files\\';
  4006. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  4007. $dompdf = new Dompdf();
  4008. $dompdf->loadHtml($html);
  4009. $dompdf->setPaper('A4', 'portrait');
  4010. $dompdf->render();
  4011. $output = $dompdf->output();
  4012. $tempFile = $filePath . $fileName;
  4013. if(!file_exists($tempFile)){
  4014. fopen($tempFile, 'w');
  4015. }
  4016. file_put_contents($tempFile, $output);
  4017. $ubic = Storage::putFile('files', new File($tempFile));
  4018. $ubic = str_replace("/", "\\", $ubic);
  4019. $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
  4020. $tama = filesize($ubic);
  4021. $usac = json_encode([$idUser]);
  4022. unlink($tempFile);
  4023. DB::table('S002V01TAFAL')->insert([
  4024. 'AFAL_NULI' => $line,
  4025. 'AFAL_COMO' => $como,
  4026. 'AFAL_CLDO' => $cldo,
  4027. 'AFAL_FECR' => $fecr,
  4028. 'AFAL_NUSE' => $nuse,
  4029. 'AFAL_NUVE' => $nuve,
  4030. 'AFAL_NOAR' => $noar,
  4031. 'AFAL_EXTE' => $exte,
  4032. 'AFAL_TAMA' => $tama,
  4033. 'AFAL_UBIC' => $ubic,
  4034. 'AFAL_USAC' => $usac,
  4035. 'AFAL_USRE' => $idUser,
  4036. 'AFAL_FERE' => $nowStr,
  4037. ]);
  4038. $filesArr = json_decode($order->OTPR_DONE, true);
  4039. $filesArr[] = $fileName;
  4040. $filesStr = json_encode($filesArr);
  4041. DB::table('S002V01TOTPR')->where([
  4042. ['OTPR_NULI', '=', $line],
  4043. ['OTPR_IDOT', '=', $idOrder]
  4044. ])->update([
  4045. 'OTPR_DONE' => $filesStr,
  4046. 'OTPR_USMO' => $idUser,
  4047. 'OTPR_FEMO' => $nowStr
  4048. ]);
  4049. $actions = DB::getQueryLog();
  4050. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4051. $idac = $this->functionsController->registerActivity(
  4052. $line,
  4053. 'S002V01M10GMPR',
  4054. 'S002V01F07EPMA',
  4055. 'S002V01P02DPMA',
  4056. 'Registro',
  4057. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento de la orden #$idOrder.",
  4058. $idUser,
  4059. $nowStr,
  4060. 'S002V01S02AOTR'
  4061. );
  4062. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4063. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  4064. }
  4065. public function getMaintenancePlanAnalysis($idFile, $idUser, $line) {
  4066. DB::enableQueryLog();
  4067. $idUser = $this->encryptionController->decrypt($idUser);
  4068. if(!$idUser){
  4069. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4070. }
  4071. $usr = DB::table('S002V01TUSUA')->where([
  4072. ['USUA_IDUS', '=', $idUser],
  4073. ['USUA_NULI', '=', $line]
  4074. ])->first();
  4075. if(is_null($usr)){
  4076. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4077. }
  4078. $idFile = $this->encryptionController->decrypt($idFile);
  4079. if(!$idFile){
  4080. return $this->responseController->makeResponse(true, 'El ID del archivo solicitado no está encriptado correctamente.', [], 400);
  4081. }
  4082. $tempFile = DB::table('S002V01TARTE')->where([
  4083. ['ARTE_NULI', '=', $line],
  4084. ['ARTE_IDAR', '=', $idFile]
  4085. ])->first();
  4086. if(is_null($tempFile)){
  4087. return $this->responseController->makeResponse(true, 'El archivo solicitado no está registrado.', [], 404);
  4088. }
  4089. $fileColumnsEsp = ['Id', 'Activo', 'Modo de tarea', 'Nombre', 'Duración', 'Comienzo', 'Fin', 'Trabajo_Programado', 'Costo', 'Duración de línea base estimada',
  4090. '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'];
  4091. $fileColumnsIng = ['ID', 'Active', 'Task Mode', 'Name', 'Duration', 'Start', 'Finish', 'Predecessors', 'Outline Level', 'Notes'];
  4092. $MONTHS_ESP = ['enero' => '01', 'febrero' => '02', 'marzo' => '03', 'abril' => '04', 'mayo' => '05', 'junio' => '06', 'julio' => '07', 'agosto' => '08',
  4093. 'septiembre' => '09', 'octubre' => '10', 'noviembre' => '11', 'diciembre' => '12'];
  4094. $MONTHS_ING = ['1' => '01', '2' => '02', '3' => '03', '4' => '04', '5' => '05', '6' => '06', '7' => '07', '8' => '08',
  4095. '9' => '09', '10' => '10', '11' => '11', '12' => '12'];
  4096. $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE);
  4097. $workSheet = $spreadsheet->getActiveSheet();
  4098. $maxColStr = $workSheet->getHighestColumn();
  4099. $maxCol = Coordinate::columnIndexFromString($maxColStr);
  4100. for($i = 1; $i <= $maxCol; $i++){
  4101. $colStr = Coordinate::stringFromColumnIndex($i);
  4102. $cell = $workSheet->getCell($colStr . "1");
  4103. $val = $cell->getValue();
  4104. if(!in_array($val, $fileColumnsEsp) && !in_array($val, $fileColumnsIng)){
  4105. return $this->responseController->makeResponse(true, 'El archivo tiene un formato inválido.', [], 400);
  4106. }
  4107. }
  4108. $instructions = [];
  4109. $maxRow = $workSheet->getHighestRow();
  4110. for($row = 2; $row <= $maxRow; $row++){
  4111. $activo = $workSheet->getCell("B$row")->getValue();
  4112. $language = $activo == 'Yes' ? 'I' : 'E';
  4113. if($activo == 'Sí' || $activo == 'Si' || $activo == 'Yes'){
  4114. $durationStr = $workSheet->getCell("E$row")->getValue();
  4115. $durationArr = explode(" ", $durationStr);
  4116. $duration = 0;
  4117. if($durationArr[1] == 'días' || $durationArr[1] == 'dias' || $durationArr[1] == 'día' || $durationArr[1] == 'dia' || $durationArr[1] == 'days' || $durationArr[1] == 'day'){
  4118. $daysFloat = floatval($durationArr[0]);
  4119. $daysInt = intval($daysFloat);
  4120. $duration += $daysInt * 24;
  4121. $hoursDec = $this->functionsController->floatSub($daysFloat, $daysInt);
  4122. $hoursFloat = $this->functionsController->floatMul($hoursDec, 24);
  4123. $duration = $this->functionsController->floatAdd($duration, $hoursFloat);
  4124. }
  4125. if($durationArr[1] == 'mins' || $durationArr[1] == 'min'){
  4126. $minsFloat = floatval($durationArr[0]);
  4127. $hoursFloat = $this->functionsController->floatDiv($minsFloat, 60);
  4128. $duration = $this->functionsController->floatAdd($duration, $hoursFloat);
  4129. }
  4130. $duration = round($duration, 5);
  4131. $startDateStr = $workSheet->getCell("F$row")->getValue();
  4132. $startDateArr = explode(" ", $startDateStr);
  4133. if($language == 'I'){
  4134. $americanDateArr = explode('/', $startDateArr[1]);
  4135. $startMonth = $MONTHS_ING[$americanDateArr[0]];
  4136. }else{
  4137. $startMonth = $MONTHS_ESP[$startDateArr[1]];
  4138. $startPeriod = $startDateArr[4] . $startDateArr[5];
  4139. $startPeriod = str_replace('.', '', $startPeriod);
  4140. $startHourArr = explode(":", $startDateArr[3]);
  4141. $startHour = intval($startHourArr[0]);
  4142. $startHour = $startPeriod == 'pm' && $startHour < 12 ? $startHour + 12 : $startHour;
  4143. $startHourStr = $startHour < 10 ? "0$startHour" : "$startHour";
  4144. $startDateTime = "$startDateArr[2]-$startMonth-$startDateArr[0] $startHourStr:$startHourArr[1]:00";
  4145. $startDateTimeObj = new Carbon($startDateTime);
  4146. $startTimestamp = $startDateTimeObj->timestamp;
  4147. $endDateStr = $workSheet->getCell("G$row")->getValue();
  4148. $endDateArr = explode(" ", $endDateStr);
  4149. $endMonth = $MONTHS_ESP[$endDateArr[1]];
  4150. $endPeriod = $endDateArr[4] . $endDateArr[5];
  4151. $endPeriod = str_replace('.', '', $endPeriod);
  4152. $endHourArr = explode(":", $endDateArr[3]);
  4153. $endHour = intval($endHourArr[0]);
  4154. $endHour = $endPeriod == 'pm' && $endHour < 12 ? $endHour + 12 : $endHour;
  4155. $endHourStr = $endHour < 10 ? "0$endHour" : "$endHour";
  4156. $endDateTime = "$endDateArr[2]-$endMonth-$endDateArr[0] $endHourStr:$endHourArr[1]:00";
  4157. $endDateTimeObj = new Carbon($endDateTime);
  4158. $endTimestamp = $endDateTimeObj->timestamp;
  4159. }
  4160. $difference = $endTimestamp - $startTimestamp;
  4161. $minutes = $this->functionsController->floatDiv($difference, 60);
  4162. $hours = $this->functionsController->floatDiv($minutes, 60);
  4163. $duration = round($hours, 5);
  4164. $instructions[] = [
  4165. "INSTRUCTION" => $workSheet->getCell("D$row")->getValue(),
  4166. "DURATION" => $duration,
  4167. "START" => $startDateTime,
  4168. "END" => $endDateTime,
  4169. "COST" => $workSheet->getCell("I$row")->getValue(),
  4170. ];
  4171. }
  4172. }
  4173. $now = $this->functionsController->now();
  4174. $nowStr = $now->toDateTimeString();
  4175. $actions = DB::getQueryLog();
  4176. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4177. $idac = $this->functionsController->registerActivity(
  4178. $line,
  4179. 'S002V01M10GMPR',
  4180. 'S002V01F10DIBI',
  4181. '-',
  4182. 'Consulta',
  4183. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el plan de mantenimiento para una nueva orden desde MS Project.",
  4184. $idUser,
  4185. $nowStr,
  4186. 'S002V01S02AOTR'
  4187. );
  4188. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4189. return $this->responseController->makeResponse(false, 'EXITO.', $instructions);
  4190. }
  4191. public function getFileToMSProject($idOrder, $idUser, $line) {
  4192. DB::enableQueryLog();
  4193. $idUser = $this->encryptionController->decrypt($idUser);
  4194. if(!$idUser){
  4195. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4196. }
  4197. $usr = DB::table('S002V01TUSUA')->where([
  4198. ['USUA_NULI', '=', $line],
  4199. ['USUA_IDUS', '=', $idUser],
  4200. ])->first();
  4201. if(is_null($usr)){
  4202. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4203. }
  4204. $idOrder = $this->encryptionController->decrypt($idOrder);
  4205. if(!$idOrder){
  4206. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  4207. }
  4208. $order = DB::table('S002V01TOTPR')->where([
  4209. ['OTPR_IDOT', '=', $idOrder],
  4210. ['OTPR_NULI', '=', $line]
  4211. ])->first();
  4212. if(is_null($order)){
  4213. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  4214. }
  4215. $cols = ['Id', 'Activo', 'Modo de tarea', 'Nombre', 'Duración', 'Comienzo', 'Fin', 'Trabajo_Programado', 'Costo', 'Duración de línea base estimada',
  4216. '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'];
  4217. $analysis = json_decode($order->OTPR_SEAN, true);
  4218. $instructionsConf = /*$analysis['instructionsConf']*/ '{}';
  4219. $instructions = json_decode($order->OTPR_ININ, true);
  4220. $arrCols = [];
  4221. $cont = 1;
  4222. foreach($instructions as $instruction){
  4223. $projectDuration = "";
  4224. if($instruction['DURACION'] < 24){
  4225. $duration = $instruction['DURACION'] * 60;
  4226. $projectDuration = "$duration min";
  4227. if($duration > 1){
  4228. $projectDuration .= "s";
  4229. }
  4230. }else{
  4231. $duration = $this->functionsController->floatDiv($instruction['DURACION'], 24);
  4232. $duration = round($duration, 2);
  4233. $projectDuration = "$duration día";
  4234. if($duration > 1){
  4235. $projectDuration .= "s";
  4236. }
  4237. }
  4238. $instructionStartDateTimeArr = explode(' ', $instruction['INICIO']);
  4239. $instructionStartTimeArr = explode(':', $instructionStartDateTimeArr[1]);
  4240. $instructionStartHour = intval($instructionStartTimeArr[0]);
  4241. if($instructionStartDateTimeArr[2] == 'PM' && $instructionStartHour < 12){
  4242. $instructionStartHour = $instructionStartHour + 12;
  4243. }
  4244. $instructionStartHourStr = $instructionStartHour < 10 ? "0$instructionStartHour" : "$instructionStartHour";
  4245. $instructionStartTimeStr = "$instructionStartHourStr:$instructionStartTimeArr[1]:00";
  4246. $instructionStartDateTimeStr = "$instructionStartDateTimeArr[0] $instructionStartTimeStr";
  4247. $instructionEndDateTimeArr = explode(' ', $instruction['FIN']);
  4248. $instructionEndTimeArr = explode(':', $instructionEndDateTimeArr[1]);
  4249. $instructionEndHour = intval($instructionEndTimeArr[0]);
  4250. if($instructionEndDateTimeArr[2] == 'PM' && $instructionEndHour < 12){
  4251. $instructionEndHour = $instructionEndHour + 12;
  4252. }
  4253. $instructionEndHourStr = $instructionEndHour < 10 ? "0$instructionEndHour" : "$instructionEndHour";
  4254. $instructionEndTimeStr = "$instructionEndHourStr:$instructionEndTimeArr[1]:00";
  4255. $instructionEndDateTimeStr = "$instructionEndDateTimeArr[0] $instructionEndTimeStr";
  4256. $projectStartDate = $this->functionsController->buildProjectDate($instructionStartDateTimeStr);
  4257. $projectEndDate = $this->functionsController->buildProjectDate($instructionEndDateTimeStr);
  4258. $cost = /*$instruction['ISFROMFILE'] ? $instruction['COSTO'] : $instructionsConf[$instruction['ID']]*/ '0';
  4259. $arrCol = [
  4260. "A" => $cont,
  4261. "B" => 'Sí',
  4262. "C" => 'Programada manualmente',
  4263. "D" => $instruction['INSTRUCCION'],
  4264. "E" => $projectDuration,
  4265. "F" => $projectStartDate,
  4266. "G" => $projectEndDate,
  4267. "H" => "0h",
  4268. "I" => $cost,
  4269. "J" => "0d",
  4270. "K" => "NOD",
  4271. "L" => "NOD",
  4272. "M" => "0h",
  4273. "N" => "0",
  4274. "O" => $projectDuration,
  4275. "P" => "0h",
  4276. "Q" => "0",
  4277. ];
  4278. $arrCols[] = $arrCol;
  4279. $cont++;
  4280. }
  4281. $now = $this->functionsController->now();
  4282. $nowStr = $now->toDateTimeString();
  4283. $dateTimeArr = explode(" ", $nowStr);
  4284. $dateArr = explode("-", $dateTimeArr[0]);
  4285. $year = substr($dateArr[0], 2);
  4286. $como = 'GMPR';
  4287. $cldo = 'OR';
  4288. $fecr = $year . $dateArr[1] . $dateArr[2];
  4289. $sec = DB::table('S002V01TAFAL')->where([
  4290. ['AFAL_NULI', '=', $line],
  4291. ['AFAL_COMO', '=', $como],
  4292. ['AFAL_CLDO', '=', $cldo],
  4293. ])->orderBy('AFAL_NUSE', 'desc')->first();
  4294. $nuse = "";
  4295. if(is_null($sec)){
  4296. $nuse = '000001';
  4297. }else{
  4298. $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
  4299. $nuse = "";
  4300. for($i = strlen($secu); $i < 6; $i++){
  4301. $nuse .= "0";
  4302. }
  4303. $nuse = $nuse . $secu;
  4304. }
  4305. $noar = "plan_de_mantenimiento_preventivo_ms_project_orden_$idOrder";
  4306. $exte = "xlsx";
  4307. $ver = DB::table('S002V01TAFAL')->where([
  4308. ['AFAL_NULI', '=', $line],
  4309. ['AFAL_COMO', '=', $como],
  4310. ['AFAL_CLDO', '=', $cldo],
  4311. ['AFAL_NOAR', '=', $noar],
  4312. ['AFAL_EXTE', '=', $exte],
  4313. ])->orderBy('AFAL_NUVE', 'desc')->first();
  4314. $nuve = "";
  4315. if(is_null($ver)){
  4316. $nuve = "01";
  4317. }else{
  4318. $vers = intval($ver->AFAL_NUVE) + 1;
  4319. $nuve = $vers < 10 ? "0$vers" : "$vers";
  4320. }
  4321. $line = $line < 10 ? "0$line" : "$line";
  4322. $filePath = 'C:\inetpub\wwwroot\sam\public_files\\';
  4323. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  4324. $tempFile = $filePath . $fileName;
  4325. if(file_exists($tempFile)){
  4326. unlink($tempFile);
  4327. }
  4328. $spreadsheet = new Spreadsheet();
  4329. $workSheet = $spreadsheet->getActiveSheet();
  4330. $colInd = 1;
  4331. foreach($cols as $colName){
  4332. $colStr = Coordinate::stringFromColumnIndex($colInd);
  4333. $workSheet->setCellValue($colStr . "1", $colName);
  4334. $workSheet->getColumnDimension($colStr)->setAutoSize(true);
  4335. $colInd++;
  4336. }
  4337. $row = 2;
  4338. foreach($arrCols as $col){
  4339. foreach($col as $k=>$v){
  4340. $workSheet->setCellValue($k . $row, $v);
  4341. }
  4342. $row++;
  4343. }
  4344. $writer = new Xlsx($spreadsheet);
  4345. $writer->save($tempFile);
  4346. $ubic = Storage::putFile('files', new File($tempFile));
  4347. $ubic = str_replace("/", "\\", $ubic);
  4348. $ubic = $this->functionsController->getBasePath() . "\storage\app\\" . $ubic;
  4349. $tama = filesize($ubic);
  4350. $usac = json_encode([$idUser]);
  4351. unlink($tempFile);
  4352. DB::table('S002V01TAFAL')->insert([
  4353. 'AFAL_NULI' => $line,
  4354. 'AFAL_COMO' => $como,
  4355. 'AFAL_CLDO' => $cldo,
  4356. 'AFAL_FECR' => $fecr,
  4357. 'AFAL_NUSE' => $nuse,
  4358. 'AFAL_NUVE' => $nuve,
  4359. 'AFAL_NOAR' => $noar,
  4360. 'AFAL_EXTE' => $exte,
  4361. 'AFAL_TAMA' => $tama,
  4362. 'AFAL_UBIC' => $ubic,
  4363. 'AFAL_USAC' => $usac,
  4364. 'AFAL_USRE' => $idUser,
  4365. 'AFAL_FERE' => $nowStr,
  4366. ]);
  4367. $filesArr = json_decode($order->OTPR_DONE, true);
  4368. $filesArr[] = $fileName;
  4369. $filesStr = json_encode($filesArr);
  4370. DB::table('S002V01TOTPR')->where([
  4371. ['OTPR_NULI', '=', $line],
  4372. ['OTPR_IDOT', '=', $idOrder]
  4373. ])->update([
  4374. 'OTPR_DONE' => $filesStr,
  4375. 'OTPR_USMO' => $idUser,
  4376. 'OTPR_FEMO' => $nowStr
  4377. ]);
  4378. $actions = DB::getQueryLog();
  4379. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4380. $idac = $this->functionsController->registerActivity(
  4381. $line,
  4382. 'S002V01M10GMPR',
  4383. 'S002V01F10DIBI',
  4384. '-',
  4385. 'Registro',
  4386. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento para MS Project de la orden #$idOrder.",
  4387. $idUser,
  4388. $nowStr,
  4389. 'S002V01S02AOTR'
  4390. );
  4391. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4392. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  4393. }
  4394. public function getOrderStaff($idOrder, $idUser, $line) {
  4395. DB::enableQueryLog();
  4396. $idUser = $this->encryptionController->decrypt($idUser);
  4397. if(!$idUser){
  4398. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4399. }
  4400. $usr = DB::table('S002V01TUSUA')->where([
  4401. ['USUA_NULI', '=', $line],
  4402. ['USUA_IDUS', '=', $idUser],
  4403. ])->first();
  4404. if(is_null($usr)){
  4405. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4406. }
  4407. $idOrder = $this->encryptionController->decrypt($idOrder);
  4408. if(!$idOrder){
  4409. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  4410. }
  4411. $order = DB::table('S002V01TOTPR')->where([
  4412. ['OTPR_IDOT', '=', $idOrder],
  4413. ['OTPR_NULI', '=', $line]
  4414. ])->first();
  4415. if(is_null($order)){
  4416. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  4417. }
  4418. $staffArr = json_decode($order->OTPR_OPPR, true);
  4419. $staffTmp = [];
  4420. foreach($staffArr as $val){
  4421. if($val['TYPE'] == 'EQ'){
  4422. $employees = DB::table('S002V01TPERS')->where([
  4423. ['PERS_NULI', '=', $line],
  4424. ['PERS_EQTR', '=', $val['ID']],
  4425. ])->get()->all();
  4426. foreach($employees as $employee){
  4427. if(!in_array($employee->PERS_IDPE, $staffTmp)){
  4428. $staffTmp[] = $employee->PERS_IDPE;
  4429. }
  4430. }
  4431. }else if($val['TYPE'] == 'SU'){
  4432. $employees = DB::table('S002V01TPERS')->where([
  4433. ['PERS_NULI', '=', $line],
  4434. ['PERS_IDPS', '=', $val['ID']],
  4435. ])->get()->all();
  4436. foreach($employees as $employee){
  4437. if(!in_array($employee->PERS_IDPE, $staffTmp)){
  4438. $staffTmp[] = $employee->PERS_IDPE;
  4439. }
  4440. }
  4441. }else{
  4442. $id = intval($val['ID']);
  4443. if(!in_array($id, $staffTmp)){
  4444. $staffTmp[] = $id;
  4445. }
  4446. }
  4447. }
  4448. $staffFn = [];
  4449. foreach($staffTmp as $empID){
  4450. $employee = DB::table('S002V01TPERS')->select([
  4451. 'PERS_IDPE AS IDEMPLEADO',
  4452. 'PERS_IDUS AS IDUSUARIO',
  4453. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'),
  4454. 'PERS_TICO AS TIPOCONTRATO',
  4455. 'PERS_IDPS AS IDSUBCONTRATISTA',
  4456. 'PESU_RASO AS RAZONSOCIAL',
  4457. 'PESU_REFI AS REGIMENFISCAL',
  4458. 'PERS_EQTR AS IDEQUIPO',
  4459. 'EQMA_NOMB AS NOMBREEQUIPO'
  4460. ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  4461. ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  4462. ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([
  4463. ['PERS_NULI', '=', $line],
  4464. ['PERS_IDPE', '=', $empID],
  4465. ])->first();
  4466. if(!is_null($employee)){
  4467. $staffFn[] = $employee;
  4468. }
  4469. }
  4470. $now = $this->functionsController->now();
  4471. $nowStr = $now->toDateTimeString();
  4472. $actions = DB::getQueryLog();
  4473. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4474. $idac = $this->functionsController->registerActivity(
  4475. $line,
  4476. 'S002V01M10GMPR',
  4477. 'S002V01F01COTP',
  4478. 'S002V01P03COTP',
  4479. 'Consulta',
  4480. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados de la orden #$idOrder.",
  4481. $idUser,
  4482. $nowStr,
  4483. 'S002V01S01ORTR'
  4484. );
  4485. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4486. return $this->responseController->makeResponse(false, 'EXITO.', $staffFn);
  4487. }
  4488. public function getOrderExecutionDetails($idExecution, $idUser, $line) {
  4489. DB::enableQueryLog();
  4490. $idUser = $this->encryptionController->decrypt($idUser);
  4491. if(!$idUser){
  4492. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4493. }
  4494. $usr = DB::table('S002V01TUSUA')->where([
  4495. ['USUA_NULI', '=', $line],
  4496. ['USUA_IDUS', '=', $idUser],
  4497. ])->first();
  4498. if(is_null($usr)){
  4499. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4500. }
  4501. $idExecution = $this->encryptionController->decrypt($idExecution);
  4502. if(!$idExecution){
  4503. return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada no está encriptado correctamente.', [], 400);
  4504. }
  4505. $idExecArr = explode('|', $idExecution);
  4506. if(count($idExecArr) < 4){
  4507. return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada tiene un formato inválido.', [], 400);
  4508. }
  4509. $execution = DB::table('S002V01TBEOT')->select([
  4510. 'BEOT_IDRE AS IDREGISTRO',
  4511. 'BEOT_IDOT AS IDORDEN',
  4512. 'BEOT_FEPR AS FECHAPROGRAMACION',
  4513. 'BEOT_TIAC AS TIPOACCION',
  4514. 'BEOT_TIOR AS TIPOORDEN',
  4515. 'BEOT_DTEJ AS TIEMPOEJECUCION',
  4516. 'BEOT_OBSE AS OBSERVACIONES',
  4517. 'BEOT_FEEJ AS FECHAEJECUCION',
  4518. 'BEOT_USEJ AS USUARIOEJECUCION',
  4519. 'BEOT_FEFI AS FECHAFINALIZACION',
  4520. 'BEOT_USFI AS USUARIOFINALIZO'
  4521. ])->where([
  4522. ['BEOT_IDRE', '=', $idExecArr[0]],
  4523. ['BEOT_NULI', '=', $line],
  4524. ['BEOT_IDOT', '=', $idExecArr[2]],
  4525. ['BEOT_FEPR', '=', $idExecArr[3]],
  4526. ])->first();
  4527. if(is_null($execution)){
  4528. return $this->responseController->makeResponse(true, 'El registro de la ejecución solicitada no existe.', [], 404);
  4529. }
  4530. $execution->IDREGISTRO = $this->encryptionController->encrypt($execution->IDREGISTRO);
  4531. $execution->IDORDEN = $this->encryptionController->encrypt($execution->IDORDEN);
  4532. $execUsr = DB::table('S002V01TUSUA')->where([
  4533. ['USUA_IDUS', '=', $execution->USUARIOEJECUCION],
  4534. ['USUA_NULI', '=', $line]
  4535. ])->first();
  4536. $execName = $this->functionsController->joinName($execUsr->USUA_NOMB, $execUsr->USUA_APPA, $execUsr->USUA_APMA);
  4537. $execution->USUARIOEJECUCION = $execName . " (" . $execution->USUARIOEJECUCION . ")";
  4538. if(!is_null($execution->USUARIOFINALIZO)){
  4539. $finUsr = DB::table('S002V01TUSUA')->where([
  4540. ['USUA_IDUS', '=', $execution->USUARIOFINALIZO],
  4541. ['USUA_NULI', '=', $line]
  4542. ])->first();
  4543. $finName = $this->functionsController->joinName($finUsr->USUA_NOMB, $finUsr->USUA_APPA, $finUsr->USUA_APMA);
  4544. $execution->USUARIOFINALIZO = $finName . " (" . $execution->USUARIOFINALIZO . ")";
  4545. }
  4546. $now = $this->functionsController->now();
  4547. $nowStr = $now->toDateTimeString();
  4548. $actions = DB::getQueryLog();
  4549. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4550. $idac = $this->functionsController->registerActivity(
  4551. $line,
  4552. 'S002V01M10GMPR',
  4553. 'S002V01F01COTP',
  4554. 'S002V01P03COTP',
  4555. 'Consulta',
  4556. "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].",
  4557. $idUser,
  4558. $nowStr,
  4559. 'S002V01S01ORTR'
  4560. );
  4561. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4562. return $this->responseController->makeResponse(false, 'EXITO.', $execution);
  4563. }
  4564. public function getWorkOrdersByEquipment($equipmentCode, $idUser, $line) {
  4565. DB::enableQueryLog();
  4566. $idUser = $this->encryptionController->decrypt($idUser);
  4567. if(!$idUser){
  4568. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4569. }
  4570. $usr = DB::table('S002V01TUSUA')->where([
  4571. ['USUA_NULI', '=', $line],
  4572. ['USUA_IDUS', '=', $idUser],
  4573. ])->first();
  4574. if(is_null($usr)){
  4575. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4576. }
  4577. $equipmentCode = $this->encryptionController->decrypt($equipmentCode);
  4578. if(!$equipmentCode){
  4579. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400);
  4580. }
  4581. $equipment = DB::table('S002V01TEQUI')->where([
  4582. ['EQUI_NULI', '=', $line],
  4583. ['EQUI_COEQ', '=', $equipmentCode]
  4584. ])->first();
  4585. if(is_null($equipment)){
  4586. return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404);
  4587. }
  4588. $workOrders = DB::table('S002V01TOTPR')->select([
  4589. 'OTPR_IDOT AS IDORDEN',
  4590. 'OTPR_EQIN AS EQUIPO',
  4591. 'OTPR_FIAP AS FECHAINICIO',
  4592. 'OTPR_FTAP AS FECHAFINAL',
  4593. 'OTPR_ACAS AS ACTIVADOR',
  4594. 'ACTI_TIAC AS TIPOACTIVADOR',
  4595. 'ACTI_PRIO AS PRIORIDAD',
  4596. 'OTPR_ESTA AS ESTATUS'
  4597. ])->where([
  4598. ['OTPR_NULI', '=', $line],
  4599. ['OTPR_EQIN', '=', $equipmentCode],
  4600. ['OTPR_ESTA', '!=', 'E'],
  4601. ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')
  4602. ->orderBy('OTPR_IDOT', 'desc')->get()->all();
  4603. foreach($workOrders as $key=>$order){
  4604. $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
  4605. $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO);
  4606. $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR);
  4607. if(!is_null($order->PRIORIDAD)){
  4608. $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
  4609. }
  4610. if($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null;
  4611. if($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null;
  4612. $workOrders[$key] = $order;
  4613. }
  4614. $now = $this->functionsController->now();
  4615. $nowStr = $now->toDateTimeString();
  4616. $actions = DB::getQueryLog();
  4617. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4618. $idac = $this->functionsController->registerActivity(
  4619. $line,
  4620. 'S002V01M10GMPR',
  4621. 'S002V01F01COTP',
  4622. 'S002V01P01HOTP',
  4623. 'Consulta',
  4624. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo relacionadas al equipamient $equipmentCode.",
  4625. $idUser,
  4626. $nowStr,
  4627. 'S002V01S01ORTR'
  4628. );
  4629. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4630. return $this->responseController->makeResponse(false, 'EXITO.', $workOrders);
  4631. }
  4632. // Visitas técnicas no programadas (Preventivas)
  4633. public function getVisit($idVisit, $idUser, $line)
  4634. {
  4635. DB::enableQueryLog();
  4636. $idUser = $this->encryptionController->decrypt($idUser);
  4637. if (!$idUser) {
  4638. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4639. }
  4640. $usr = DB::table('S002V01TUSUA')->where([
  4641. ['USUA_NULI', '=', $line],
  4642. ['USUA_IDUS', '=', $idUser],
  4643. ])->first();
  4644. if (is_null($usr)) {
  4645. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4646. }
  4647. $idVisit = $this->encryptionController->decrypt($idVisit);
  4648. if (!$idVisit) {
  4649. return $this->responseController->makeResponse(true, 'El ID de la visita no está encriptado correctamente.', [], 400);
  4650. }
  4651. $visit = DB::table('S002V01TRVTN')->select([
  4652. 'RVTN_IDVI AS ID_ORDEN',
  4653. 'RVTN_DEIN AS DESCRIPCION',
  4654. 'RVTN_EQRE AS CODIGO_EQUIPAMIENTO',
  4655. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  4656. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  4657. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  4658. 'RVTN_TESO AS TIEMPO_ESTIMADO',
  4659. 'RVTN_CORE AS CONTADOR',
  4660. 'RVTN_DRCO AS MEDIDAS',
  4661. 'RVTN_PRIO AS PRIORIDAD',
  4662. 'RVTN_MAUT AS RECURSOS',
  4663. 'RVTN_TIAC AS TIPO_ACTIVACION',
  4664. 'RVTN_DORE AS DOCUMENTOS_RELACIONADOS',
  4665. 'RVTN_CLAS AS CLASIFICACION',
  4666. 'RVTN_COME AS COMENTARIOS',
  4667. 'RVTN_ESTA AS ESTADO',
  4668. 'RVTN_USRE AS USUREG',
  4669. 'RVTN_FERE AS FECREG',
  4670. 'RVTN_HIES AS HISTORIAL',
  4671. 'RVTN_PEIN AS PERSONAL'
  4672. ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'RVTN_EQRE')
  4673. ->where([
  4674. ['RVTN_IDVI', '=', $idVisit],
  4675. ['RVTN_NULI', '=', $line],
  4676. ])->first();
  4677. if (is_null($visit)) {
  4678. return $this->responseController->makeResponse(true, 'La visita consultada no existe.', [], 404);
  4679. }
  4680. $visit->ID_ORDEN = $this->encryptionController->encrypt($visit->ID_ORDEN);
  4681. $visit->CODIGO_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->CODIGO_EQUIPAMIENTO);
  4682. if (!is_null($visit->ID_EQUIPAMIENTO)) {
  4683. $visit->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($visit->ID_EQUIPAMIENTO);
  4684. }
  4685. $visit->CONTADOR = $this->encryptionController->encrypt($visit->CONTADOR);
  4686. $visit->PRIORIDAD = $this->encryptionController->encrypt($visit->PRIORIDAD);
  4687. // Procesar PERSONAL
  4688. $staffArr = json_decode($visit->PERSONAL, true);
  4689. foreach ($staffArr as $key => $val) {
  4690. $specialty = DB::table('S002V01TGEES')->where([
  4691. ['GEES_NULI', '=', $line],
  4692. ['GEES_COES', '=', $val['ID']]
  4693. ])->first();
  4694. $val['ID'] = $this->encryptionController->encrypt($val['ID']);
  4695. $val['NAME'] = $specialty->GEES_NOES;
  4696. $staffArr[$key] = $val;
  4697. }
  4698. $visit->PERSONAL = json_encode($staffArr);
  4699. // Procesar MEDIDAS_OBJ
  4700. $measureArr = json_decode($visit->MEDIDAS, true);
  4701. if (!empty($measureArr)) {
  4702. $measureArr['CONTADOR'] = $this->encryptionController->encrypt($measureArr['CONTADOR']);
  4703. $measureArr['ID_MEDIDA'] = $this->encryptionController->encrypt($measureArr['ID_MEDIDA']);
  4704. $measureArr['ID_SERVICIO_WEB'] = $this->encryptionController->encrypt($measureArr['ID_SERVICIO_WEB']);
  4705. }
  4706. $visit->MEDIDAS_OBJ = $measureArr;
  4707. unset($visit->MEDIDAS);
  4708. // Procesar RECURSOS_ARR
  4709. $resources = json_decode($visit->RECURSOS, true);
  4710. $resourcesFn = [];
  4711. foreach ($resources as $resource) {
  4712. if ($resource['ID'] != 'SH') {
  4713. $resourceObj = DB::table('S002V01TINST')->where([
  4714. ['INST_NULI', '=', $line],
  4715. ['INST_IDIS', '=', $resource['ID']],
  4716. ])->first();
  4717. if (!is_null($resourceObj)) {
  4718. $resourcesFn[] = $resourceObj->INST_MODE;
  4719. }
  4720. }
  4721. }
  4722. $visit->RECURSOS_ARR = $resourcesFn;
  4723. // Procesar DOCUMENTOS_RELACIONADOS_ARR
  4724. $documentsArr = json_decode($visit->DOCUMENTOS_RELACIONADOS, true);
  4725. $documentsFn = [];
  4726. foreach ($documentsArr as $document) {
  4727. $documentArr = explode('=', $document);
  4728. $codeArr = explode('-', $documentArr[0]);
  4729. $file = DB::table('S002V01TAFAL')->where([
  4730. ['AFAL_NULI', '=', $line],
  4731. ['AFAL_COMO', '=', $codeArr[1]],
  4732. ['AFAL_CLDO', '=', $codeArr[2]],
  4733. ['AFAL_FECR', '=', $codeArr[3]],
  4734. ['AFAL_NUSE', '=', $codeArr[4]],
  4735. ['AFAL_NUVE', '=', $documentArr[1]]
  4736. ])->first();
  4737. $documentsFn[] = [
  4738. 'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE,
  4739. 'size' => $file->AFAL_TAMA
  4740. ];
  4741. }
  4742. $visit->DOCUMENTOS_RELACIONADOS_ARR = $documentsFn;
  4743. // Mapear TIPO_ACTIVACION
  4744. $activationTypes = ['M' => 'Manual', 'A' => 'Automática'];
  4745. $visit->TIPO_ACTIVACION = $activationTypes[$visit->TIPO_ACTIVACION];
  4746. // Mapear ESTADO (RVTN_ESTA enum: 'VA','EP','CP','CE','P','C','R','A','F')
  4747. // VA, EP, CP, CE: Solo para RVTN_TIAC='A' (Automática)
  4748. // P, C, R, A, F: Solo para RVTN_TIAC='M' (Manual)
  4749. $orderStates = [
  4750. 'VA' => 'Validado', // Automática
  4751. 'EP' => 'En progreso', // Automática
  4752. 'CP' => 'Cerrado pendiente', // Automática
  4753. 'CE' => 'Cerrado', // Automática
  4754. 'PE' => 'Pendiente', // Manual
  4755. 'CA' => 'Cancelado', // Manual
  4756. 'RE' => 'Rechazado', // Manual
  4757. 'EL' => 'Eliminado', // Manual
  4758. ];
  4759. $visit->ESTADO = $orderStates[$visit->ESTADO];
  4760. // Procesar usuarios
  4761. $usrReg = DB::table('S002V01TUSUA')->where([
  4762. ['USUA_NULI', '=', $line],
  4763. ['USUA_IDUS', '=', $visit->USUREG],
  4764. ])->first();
  4765. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  4766. $visit->USUREG = $nameReg . " (" . $visit->USUREG . ")";
  4767. $now = $this->functionsController->now();
  4768. $nowStr = $now->toDateTimeString();
  4769. $actions = DB::getQueryLog();
  4770. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4771. $idac = $this->functionsController->registerActivity(
  4772. $line,
  4773. 'S002V01M10GMPR',
  4774. 'S002V01F11RVTP',
  4775. 'S002V01P02COVI',
  4776. 'Consulta',
  4777. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la visita técnica #$idVisit.",
  4778. $idUser,
  4779. $nowStr,
  4780. 'S002V01S02AOTR'
  4781. );
  4782. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4783. return $this->responseController->makeResponse(false, 'EXITO.', $visit);
  4784. }
  4785. // Visitas técnicas no programadas (Preventivas)
  4786. public function assignOperariosToPreventiveVisit(Request $request)
  4787. {
  4788. DB::enableQueryLog();
  4789. $validator = Validator::make($request->all(), [
  4790. 'id_user' => 'required|string',
  4791. 'linea' => 'required|integer',
  4792. 'id_order' => 'required|string',
  4793. 'config' => 'required|json',
  4794. ]);
  4795. if ($validator->fails()) {
  4796. return $this->responseController->makeResponse(
  4797. true,
  4798. "Se encontraron uno o más errores.",
  4799. $this->responseController->makeErrors(
  4800. $validator->errors()->messages()
  4801. ),
  4802. 401
  4803. );
  4804. }
  4805. $form = $request->all();
  4806. $idUser = $this->encryptionController->decrypt($form['id_user']);
  4807. if (!$idUser) {
  4808. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  4809. }
  4810. $usr = DB::table('S002V01TUSUA')->where([
  4811. ['USUA_NULI', '=', $form['linea']],
  4812. ['USUA_IDUS', '=', $idUser]
  4813. ])->first();
  4814. if (is_null($usr)) {
  4815. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  4816. }
  4817. $idVisit = $this->encryptionController->decrypt($form['id_order']);
  4818. if (!$idVisit) {
  4819. return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
  4820. }
  4821. $visit = DB::table('S002V01TRVTN')->where([
  4822. ['RVTN_NULI', '=', $form['linea']],
  4823. ['RVTN_IDVI', '=', $idVisit]
  4824. ])->first();
  4825. if (is_null($visit)) {
  4826. return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
  4827. } else if ($visit->RVTN_ESTA != 'PE' && $visit->RVTN_ESTA != 'VA') {
  4828. return $this->responseController->makeResponse(true, 'La visita no está en un estado válido para asignar operarios.', [], 401);
  4829. }
  4830. $staffConfigArr = json_decode($form['config'], true);
  4831. $audience = [];
  4832. foreach ($staffConfigArr as $key => $val) {
  4833. if (!array_key_exists('SPECIALTY', $val) || !array_key_exists('STAFF', $val)) {
  4834. return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
  4835. }
  4836. $specialtyDec = $this->encryptionController->decrypt($val['SPECIALTY']);
  4837. if (!$specialtyDec) {
  4838. 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);
  4839. }
  4840. if (gettype($val['STAFF']) != 'array') {
  4841. return $this->responseController->makeResponse(true, "El contenedor de operarios en el item $key del arreglo de configuración de operarios es inválido.", [], 400);
  4842. }
  4843. foreach ($val['STAFF'] as $key0 => $val0) {
  4844. if (!array_key_exists('ID', $val0) || !array_key_exists('TYPE', $val0)) {
  4845. return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
  4846. }
  4847. $idDec = $this->encryptionController->decrypt($val0['ID']);
  4848. $employee = DB::table('S002V01TPERS')->where([
  4849. ['PERS_NULI', '=', $form['linea']],
  4850. ['PERS_IDPE', '=', $idDec]
  4851. ])->first();
  4852. if (is_null($employee)) {
  4853. return $this->responseController->makeResponse(true, "El operario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios no existe.", [], 404);
  4854. }
  4855. $audience[] = $employee->PERS_IDUS;
  4856. }
  4857. }
  4858. // Validación de cupo global (basado en RVTN_PEIN)
  4859. $planilla = json_decode($visit->RVTN_PEIN, true);
  4860. $cupoRequerido = 0;
  4861. if (!empty($planilla) && is_array($planilla)) {
  4862. foreach ($planilla as $pe) {
  4863. $cupoRequerido += intval($pe['CANT'] ?? 0);
  4864. }
  4865. }
  4866. // Obtener último VA
  4867. $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
  4868. $vaObj = null;
  4869. if (!empty($statusHistoryArr)) {
  4870. for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
  4871. if ($statusHistoryArr[$i]['ESTADO'] == 'VA') {
  4872. $vaObj = $statusHistoryArr[$i];
  4873. break;
  4874. }
  4875. }
  4876. }
  4877. $atencionActual = $vaObj && array_key_exists('ATENCION', $vaObj) ? $vaObj['ATENCION'] : [];
  4878. $aceptadosActual = 0;
  4879. foreach ($atencionActual as $itm) {
  4880. if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosActual++;
  4881. }
  4882. if ($cupoRequerido > 0 && $aceptadosActual >= $cupoRequerido) {
  4883. return $this->responseController->makeResponse(true, 'La planilla ya está completa. No se pueden asignar más operarios.', [], 401);
  4884. }
  4885. // Evitar invitación duplicada al mismo operario (ya invitado o ya respondió)
  4886. $yaInvitados = [];
  4887. foreach ($atencionActual as $itm) {
  4888. $yaInvitados[$itm['ID']] = $itm['RESPUESTA'] ?? '';
  4889. }
  4890. foreach ($audience as $opId) {
  4891. if (array_key_exists($opId, $yaInvitados)) {
  4892. return $this->responseController->makeResponse(true, "El operario $opId ya fue invitado o respondió anteriormente.", [], 401);
  4893. }
  4894. }
  4895. // Iniciar transacción
  4896. DB::beginTransaction();
  4897. try {
  4898. // Emitir notificación
  4899. $this->notificationsController->emitNotification(
  4900. 'S002V01M10GMPR',
  4901. "Visita de mantenimiento preventivo #$idVisit",
  4902. "Se ha asignado la visita de mantenimiento preventivo #$idVisit y requiere su atención.",
  4903. [[
  4904. 'BOTON' => 'Ver detalles',
  4905. 'FUNCION' => 'openPreventiveWorkOrderDetails',
  4906. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  4907. ], [
  4908. 'BOTON' => 'Atender visita',
  4909. 'FUNCION' => 'attendPreventiveWorkOrder',
  4910. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  4911. ], [
  4912. 'BOTON' => 'Ir al módulo',
  4913. 'FUNCION' => 'openModule',
  4914. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  4915. ]],
  4916. $audience,
  4917. $idUser,
  4918. $form['linea'],
  4919. $this->getSocketClient(),
  4920. $idVisit,
  4921. 'Preventivo'
  4922. );
  4923. $now = $this->functionsController->now();
  4924. $nowStr = $now->toDateTimeString();
  4925. $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
  4926. // Buscar si ya existe un objeto con estado VA
  4927. $vaStatusIndex = null;
  4928. foreach ($statusHistoryArr as $index => $status) {
  4929. if ($status['ESTADO'] == 'VA') {
  4930. $vaStatusIndex = $index;
  4931. break;
  4932. }
  4933. }
  4934. // Revalidar cupo justo antes de insertar (concurrencia)
  4935. $vaObjRef = null;
  4936. if (!empty($statusHistoryArr)) {
  4937. for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
  4938. if ($statusHistoryArr[$i]['ESTADO'] == 'VA') {
  4939. $vaObjRef = $statusHistoryArr[$i];
  4940. break;
  4941. }
  4942. }
  4943. }
  4944. $atencionRef = $vaObjRef && array_key_exists('ATENCION', $vaObjRef) ? $vaObjRef['ATENCION'] : [];
  4945. $aceptadosRef = 0;
  4946. foreach ($atencionRef as $itm) {
  4947. if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosRef++;
  4948. }
  4949. if ($cupoRequerido > 0 && $aceptadosRef >= $cupoRequerido) {
  4950. DB::rollBack();
  4951. return $this->responseController->makeResponse(true, 'La planilla ya está completa. No se pueden asignar más operarios.', [], 401);
  4952. }
  4953. // Crear nuevas invitaciones
  4954. $newInvitations = [];
  4955. foreach ($audience as $operarioId) {
  4956. $newInvitations[] = [
  4957. 'ID' => $operarioId,
  4958. 'FIRMA' => null,
  4959. 'RESPUESTA' => '',
  4960. 'COMENTARIOS' => ''
  4961. ];
  4962. }
  4963. if ($vaStatusIndex !== null) {
  4964. // Extender objeto VA existente
  4965. $statusHistoryArr[$vaStatusIndex]['ATENCION'] = array_merge(
  4966. $statusHistoryArr[$vaStatusIndex]['ATENCION'],
  4967. $newInvitations
  4968. );
  4969. // Agregar nuevos operarios a PERSONAL (sin duplicar)
  4970. $currentPersonal = $statusHistoryArr[$vaStatusIndex]['PERSONAL'] ?? [];
  4971. foreach ($audience as $operarioId) {
  4972. if (!in_array($operarioId, $currentPersonal)) {
  4973. $currentPersonal[] = $operarioId;
  4974. }
  4975. }
  4976. $statusHistoryArr[$vaStatusIndex]['PERSONAL'] = $currentPersonal;
  4977. } else {
  4978. // Crear nuevo objeto VA con todos los invitados en PERSONAL
  4979. $statusHistoryArr[] = [
  4980. 'USUARIO' => $idUser,
  4981. 'ESTADO' => 'VA',
  4982. 'FECHA' => $nowStr,
  4983. 'ATENCION' => $newInvitations,
  4984. 'PERSONAL' => $audience
  4985. ];
  4986. }
  4987. $statusHistoryStr = json_encode($statusHistoryArr);
  4988. // Actualizar la visita
  4989. DB::table('S002V01TRVTN')->where([
  4990. ['RVTN_IDVI', '=', $idVisit],
  4991. ['RVTN_NULI', '=', $form['linea']]
  4992. ])->update([
  4993. 'RVTN_ESTA' => 'VA',
  4994. 'RVTN_HIES' => $statusHistoryStr,
  4995. 'RVTN_USMO' => $idUser,
  4996. 'RVTN_FEMO' => $nowStr,
  4997. ]);
  4998. $actions = DB::getQueryLog();
  4999. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  5000. $idac = $this->functionsController->registerActivity(
  5001. $form['linea'],
  5002. 'S002V01M10GMPR',
  5003. 'S002V01F11RVTP',
  5004. 'S002V01P01REVI',
  5005. 'Actualización',
  5006. "El usuario $name (" . $usr->USUA_IDUS . ") asignó operarios a la visita preventiva #$idVisit.",
  5007. $idUser,
  5008. $nowStr,
  5009. 'S002V01S02AOTR'
  5010. );
  5011. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  5012. // Confirmar transacción
  5013. DB::commit();
  5014. return $this->responseController->makeResponse(false, 'EXITO.');
  5015. } catch (\Exception $e) {
  5016. // Revertir transacción en caso de error
  5017. DB::rollBack();
  5018. $actions = DB::getQueryLog();
  5019. $now = $this->functionsController->now();
  5020. $nowStr = $now->toDateTimeString();
  5021. $name = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
  5022. $idac = $this->functionsController->registerActivity(
  5023. $form['linea'],
  5024. 'S002V01M10GMPR',
  5025. 'S002V01F11RVTP',
  5026. 'S002V01P01REVI',
  5027. 'Error',
  5028. "Error al asignar operarios a la visita preventiva #$idVisit: " . $e->getMessage(),
  5029. $idUser,
  5030. $nowStr,
  5031. 'S002V01S02AOTR'
  5032. );
  5033. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  5034. return $this->responseController->makeResponse(
  5035. true,
  5036. 'Ocurrió un error al asignar operarios a la visita preventiva.',
  5037. ['error' => $e->getMessage()],
  5038. 500
  5039. );
  5040. }
  5041. }
  5042. // Visitas técnicas no programadas (Preventivas)
  5043. public function getVisitAttendance($idVisit, $idUser, $line)
  5044. {
  5045. DB::enableQueryLog();
  5046. $idUser = $this->encryptionController->decrypt($idUser);
  5047. if (!$idUser) {
  5048. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  5049. }
  5050. $usr = DB::table('S002V01TUSUA')->where([
  5051. ['USUA_NULI', '=', $line],
  5052. ['USUA_IDUS', '=', $idUser],
  5053. ])->first();
  5054. if (is_null($usr)) {
  5055. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  5056. }
  5057. $idVisit = $this->encryptionController->decrypt($idVisit);
  5058. if (!$idVisit) {
  5059. return $this->responseController->makeResponse(true, 'El ID de la visita relacionada no está encriptado correctamente', [], 400);
  5060. }
  5061. $visit = DB::table('S002V01TRVTN')->where([
  5062. ['RVTN_NULI', '=', $line],
  5063. ['RVTN_IDVI', '=', $idVisit]
  5064. ])->first();
  5065. if (is_null($visit)) {
  5066. return $this->responseController->makeResponse(true, 'La visita relacionada no está registrada.', [], 404);
  5067. }
  5068. // Validar que la visita esté en estado VA (validado)
  5069. // Puede estar en estado VA en RVTN_ESTA sin tener aún el objeto VA en RVTN_HIES
  5070. // (cuando se crea automáticamente pero aún no se han asignado operarios)
  5071. $visitStates = [
  5072. 'PE' => 'Pendiente',
  5073. 'CA' => 'Cancelado',
  5074. 'RE' => 'Rechazado',
  5075. 'EL' => 'Eliminado',
  5076. 'VA' => 'Validado',
  5077. 'EP' => 'En Proceso',
  5078. 'CP' => 'Cerrado Pendiente',
  5079. 'CE' => 'Cerrado'
  5080. ];
  5081. if ($visit->RVTN_ESTA !== 'VA') {
  5082. $statusKey = $visit->RVTN_ESTA;
  5083. $statusName = array_key_exists($statusKey, $visitStates) ? $visitStates[$statusKey] : $statusKey;
  5084. return $this->responseController->makeResponse(true, "La visita relacionada no está en el estado de validación (estado actual: $statusName)", [], 404);
  5085. }
  5086. $statusHistory = json_decode($visit->RVTN_HIES, true);
  5087. if (!is_array($statusHistory)) {
  5088. $statusHistory = [];
  5089. }
  5090. $validatedHistoryFilt = array_filter($statusHistory, function ($v, $k) {
  5091. return isset($v['ESTADO']) && $v['ESTADO'] == 'VA';
  5092. }, ARRAY_FILTER_USE_BOTH);
  5093. // Si no hay objeto VA en el historial pero el estado es VA, significa que aún no se han asignado operarios
  5094. if (empty($validatedHistoryFilt)) {
  5095. $statusKey = $visit->RVTN_ESTA;
  5096. $statusName = array_key_exists($statusKey, $visitStates) ? $visitStates[$statusKey] : $statusKey;
  5097. return $this->responseController->makeResponse(true, "La visita tiene estado $statusName pero aún no ha asignado operarios.", [], 404);
  5098. }
  5099. $validatedHistory = end($validatedHistoryFilt);
  5100. $attendance = array_key_exists('ATENCION', $validatedHistory) ? $validatedHistory['ATENCION'] : [];
  5101. $attendanceAux = [];
  5102. foreach ($attendance as $item) {
  5103. if ($item['RESPUESTA'] == 'A') {
  5104. $attendanceAux[] = $item;
  5105. }
  5106. }
  5107. return $this->responseController->makeResponse(false, 'EXITO', $attendanceAux);
  5108. }
  5109. // Visitas técnicas no programadas (Preventivas)
  5110. public function getVisitStaff($idVisit, $idUser, $line)
  5111. {
  5112. DB::enableQueryLog();
  5113. $idUser = $this->encryptionController->decrypt($idUser);
  5114. if (!$idUser) {
  5115. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  5116. }
  5117. $usr = DB::table('S002V01TUSUA')->where([
  5118. ['USUA_NULI', '=', $line],
  5119. ['USUA_IDUS', '=', $idUser],
  5120. ])->first();
  5121. if (is_null($usr)) {
  5122. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  5123. }
  5124. $idVisit = $this->encryptionController->decrypt($idVisit);
  5125. if (!$idVisit) {
  5126. return $this->responseController->makeResponse(true, 'El ID de la visita relacionada no está encriptado correctamente', [], 400);
  5127. }
  5128. $visit = DB::table('S002V01TRVTN')->where([
  5129. ['RVTN_NULI', '=', $line],
  5130. ['RVTN_IDVI', '=', $idVisit]
  5131. ])->first();
  5132. if (is_null($visit)) {
  5133. return $this->responseController->makeResponse(true, 'La visita relacionada no está registrada.', [], 404);
  5134. }
  5135. $staffArr = json_decode($visit->RVTN_PEIN, true);
  5136. $staffArrFn = [];
  5137. foreach ($staffArr as $val) {
  5138. if (array_key_exists('TYPE', $val)) {
  5139. if ($val['TYPE'] == 'EQ') {
  5140. $workTeamStaff = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
  5141. ['PERS_NULI', '=', $line],
  5142. ['PERS_EQTR', '=', $val['ID']]
  5143. ])->get()->all();
  5144. foreach ($workTeamStaff as $item) {
  5145. $itemID = $item->PERS_IDPE;
  5146. $itemFilt = array_filter($staffArrFn, function ($v, $k) use ($itemID) {
  5147. return $v['ID'] == $itemID;
  5148. }, ARRAY_FILTER_USE_BOTH);
  5149. if (count($itemFilt) <= 0) {
  5150. $staffArrFn[] = [
  5151. 'ID' => $itemID,
  5152. 'ID_USER' => $item->USUA_IDUS,
  5153. 'NAME' => $this->functionsController->joinName($item->USUA_NOMB, $item->USUA_APPA, $item->USUA_APMA),
  5154. 'TYPE' => $item->PERS_TICO,
  5155. ];
  5156. }
  5157. }
  5158. } else if ($val['TYPE'] == 'SU') {
  5159. $subcontratistStaff = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
  5160. ['PERS_NULI', '=', $line],
  5161. ['PERS_IDPS', '=', $val['ID']]
  5162. ])->get()->all();
  5163. foreach ($subcontratistStaff as $item) {
  5164. $itemID = $item->PERS_IDPE;
  5165. $itemFilt = array_filter($staffArrFn, function ($v, $k) use ($itemID) {
  5166. return $v['ID'] == $itemID;
  5167. }, ARRAY_FILTER_USE_BOTH);
  5168. if (count($itemFilt) <= 0) {
  5169. $staffArrFn[] = [
  5170. 'ID' => $itemID,
  5171. 'ID_USER' => $item->USUA_IDUS,
  5172. 'NAME' => $this->functionsController->joinName($item->USUA_NOMB, $item->USUA_APPA, $item->USUA_APMA),
  5173. 'TYPE' => $item->PERS_TICO,
  5174. ];
  5175. }
  5176. }
  5177. } else if ($val['TYPE'] == 'EM') {
  5178. $employee = DB::table('S002V01TPERS')->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')->where([
  5179. ['PERS_NULI', '=', $line],
  5180. ['PERS_IDPE', '=', $val['ID']]
  5181. ])->first();
  5182. if (!is_null($employee)) {
  5183. $itemID = $employee->PERS_IDPE;
  5184. $itemFilt = array_filter($staffArrFn, function ($v, $k) use ($itemID) {
  5185. return $v['ID'] == $itemID;
  5186. }, ARRAY_FILTER_USE_BOTH);
  5187. if (count($itemFilt) <= 0) {
  5188. $staffArrFn[] = [
  5189. 'ID' => $itemID,
  5190. 'ID_USER' => $employee->USUA_IDUS,
  5191. 'NAME' => $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA),
  5192. 'TYPE' => $employee->PERS_TICO,
  5193. ];
  5194. }
  5195. }
  5196. }
  5197. }
  5198. }
  5199. return $this->responseController->makeResponse(false, 'EXITO', $staffArr);
  5200. }
  5201. // Visitas técnicas no programadas (Preventivas)
  5202. public function getVisitStatusHistory($idOrder, $idUser, $line)
  5203. {
  5204. DB::enableQueryLog();
  5205. $idUser = $this->encryptionController->decrypt($idUser);
  5206. if (!$idUser) {
  5207. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  5208. }
  5209. $usr = DB::table('S002V01TUSUA')->where([
  5210. ['USUA_NULI', '=', $line],
  5211. ['USUA_IDUS', '=', $idUser],
  5212. ])->first();
  5213. if (is_null($usr)) {
  5214. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  5215. }
  5216. $idOrder = $this->encryptionController->decrypt($idOrder);
  5217. if (!$idOrder) {
  5218. return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente', [], 400);
  5219. }
  5220. $visit = DB::table('S002V01TRVTN')->select([
  5221. 'RVTN_HIES AS HISTORIAL',
  5222. ])->where([
  5223. ['RVTN_IDVI', '=', $idOrder],
  5224. ['RVTN_NULI', '=', $line]
  5225. ])->first();
  5226. if (is_null($visit)) {
  5227. return $this->responseController->makeResponse(true, 'La visita solicitada no está registrada.', [], 404);
  5228. }
  5229. $visitStates = [
  5230. 'PE' => 'Pendiente',
  5231. 'CA' => 'Cancelado',
  5232. 'RE' => 'Rechazado',
  5233. 'EL' => 'Eliminado',
  5234. 'VA' => 'Validado',
  5235. 'EP' => 'En Proceso',
  5236. 'CP' => 'Cerrado Pendiente',
  5237. 'CE' => 'Cerrado'
  5238. ];
  5239. $statusHistoryArr = json_decode($visit->HISTORIAL, true);
  5240. foreach ($statusHistoryArr as $key => $item) {
  5241. $item['ESTADO'] = $visitStates[$item['ESTADO']];
  5242. $usrSta = DB::table('S002V01TUSUA')->where([
  5243. ['USUA_NULI', '=', $line],
  5244. ['USUA_IDUS', '=', $item['USUARIO']]
  5245. ])->first();
  5246. if (!is_null($usrSta)) {
  5247. $usrStaName = $this->functionsController->joinName($usrSta->USUA_NOMB, $usrSta->USUA_APPA, $usrSta->USUA_APMA);
  5248. $item['USUARIO'] = $usrStaName . " (" . $item['USUARIO'] . ")";
  5249. } else {
  5250. $item['USUARIO'] = "Usuario no encontrado (" . $item['USUARIO'] . ")";
  5251. }
  5252. $statusHistoryArr[$key] = $item;
  5253. }
  5254. $now = $this->functionsController->now();
  5255. $nowStr = $now->toDateTimeString();
  5256. $actions = DB::getQueryLog();
  5257. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  5258. $idac = $this->functionsController->registerActivity(
  5259. $line,
  5260. 'S002V01M10GMPR',
  5261. 'S002V01F11RVTP',
  5262. '-',
  5263. 'Consulta',
  5264. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el historial de estados de la visita #$idOrder de mantenimiento preventivo.",
  5265. $idUser,
  5266. $nowStr,
  5267. 'S002V01S02AOTR'
  5268. );
  5269. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  5270. return $this->responseController->makeResponse(false, 'EXITO.', $statusHistoryArr);
  5271. }
  5272. // Visitas técnicas no programadas (Preventivas)
  5273. public function attendPreventiveVisit(Request $request)
  5274. {
  5275. DB::enableQueryLog();
  5276. $validator = Validator::make($request->all(), [
  5277. 'id_user' => 'required|string',
  5278. 'linea' => 'required|integer',
  5279. 'id_order' => 'required|string',
  5280. 'attendance' => 'required|string|in:A,R',
  5281. 'data' => 'required|string'
  5282. ]);
  5283. if ($validator->fails()) {
  5284. return $this->responseController->makeResponse(
  5285. true,
  5286. "Se encontraron uno o más errores.",
  5287. $this->responseController->makeErrors(
  5288. $validator->errors()->messages()
  5289. ),
  5290. 401
  5291. );
  5292. }
  5293. $form = $request->all();
  5294. $idUser = $this->encryptionController->decrypt($form['id_user']);
  5295. if (!$idUser) {
  5296. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  5297. }
  5298. $usr = DB::table('S002V01TUSUA')->where([
  5299. ['USUA_NULI', '=', $form['linea']],
  5300. ['USUA_IDUS', '=', $idUser]
  5301. ])->first();
  5302. if (is_null($usr)) {
  5303. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  5304. }
  5305. $idVisit = $this->encryptionController->decrypt($form['id_order']);
  5306. if (!$idVisit) {
  5307. return $this->responseController->makeResponse(true, 'El ID de la visita no fue encriptado correctamente.', [], 400);
  5308. }
  5309. $visit = DB::table('S002V01TRVTN')->where([
  5310. ['RVTN_NULI', '=', $form['linea']],
  5311. ['RVTN_IDVI', '=', $idVisit]
  5312. ])->first();
  5313. if (is_null($visit)) {
  5314. return $this->responseController->makeResponse(true, 'La visita solicitada no existe.', [], 404);
  5315. } else if ($visit->RVTN_ESTA != 'VA') {
  5316. return $this->responseController->makeResponse(true, 'La visita no está validada para atender.', [], 401);
  5317. }
  5318. // Validar datos según tipo de respuesta
  5319. if ($form['attendance'] == 'A' && !str_contains($form['data'], 'data:image/png')) {
  5320. return $this->responseController->makeResponse(true, 'El archivo de la firma capturada es inválido.', [], 400);
  5321. } else if ($form['attendance'] == 'R' && strlen($form['data']) < 10) {
  5322. return $this->responseController->makeResponse(true, 'La cadena de comentarios tiene una longitud menor a 10 caracteres.', [], 400);
  5323. }
  5324. // Cupo global requerido (RVTN_PEIN)
  5325. $planilla = json_decode($visit->RVTN_PEIN, true);
  5326. $cupoRequerido = 0;
  5327. if (!empty($planilla) && is_array($planilla)) {
  5328. foreach ($planilla as $pe) {
  5329. $cupoRequerido += intval($pe['CANT'] ?? 0);
  5330. }
  5331. }
  5332. // Obtener historial de estados
  5333. $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
  5334. // Buscar el último objeto con estado VA
  5335. $vaStatusIndex = null;
  5336. foreach ($statusHistoryArr as $index => $status) {
  5337. if ($status['ESTADO'] == 'VA') {
  5338. $vaStatusIndex = $index;
  5339. }
  5340. }
  5341. if ($vaStatusIndex === null) {
  5342. return $this->responseController->makeResponse(true, 'No se encontró un estado validado en el historial.', [], 404);
  5343. }
  5344. // Buscar el operario en el array ATENCION
  5345. $operatorIndex = null;
  5346. $atencionArr = $statusHistoryArr[$vaStatusIndex]['ATENCION'] ?? [];
  5347. foreach ($atencionArr as $index => $invitacion) {
  5348. if ($invitacion['ID'] == $idUser) {
  5349. $operatorIndex = $index;
  5350. break;
  5351. }
  5352. }
  5353. if ($operatorIndex === null) {
  5354. return $this->responseController->makeResponse(true, 'El usuario no está invitado a esta visita.', [], 401);
  5355. }
  5356. // Verificar si ya respondió
  5357. if (!empty($atencionArr[$operatorIndex]['RESPUESTA'])) {
  5358. $respuestaAnterior = $atencionArr[$operatorIndex]['RESPUESTA'] == 'A' ? 'aceptado' : 'rechazado';
  5359. return $this->responseController->makeResponse(true, "Ya ha $respuestaAnterior esta invitación.", [], 401);
  5360. }
  5361. // Bloquear aceptación si la planilla ya está completa (con base en aceptados actuales)
  5362. $aceptadosActual = 0;
  5363. foreach ($atencionArr as $itm) {
  5364. if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosActual++;
  5365. }
  5366. if ($form['attendance'] == 'A' && $cupoRequerido > 0 && $aceptadosActual >= $cupoRequerido) {
  5367. return $this->responseController->makeResponse(true, 'La planilla ya está completa. No es posible aceptar esta invitación.', [], 401);
  5368. }
  5369. // Iniciar transacción
  5370. DB::beginTransaction();
  5371. try {
  5372. $signature = null;
  5373. $comments = null;
  5374. if ($form['attendance'] == 'A') {
  5375. // Procesar firma
  5376. $filesPath = str_replace("app\\Http\\Controllers", "storage\\app\\files", __DIR__);
  5377. if (!file_exists($filesPath)) {
  5378. throw new \Exception('No se encontró la ubicación de almacenamiento de archivos.');
  5379. }
  5380. generateSignatureFileName:
  5381. $signatureFileName = $this->generateSignatureImageName();
  5382. $signatureFileDir = $filesPath . "\\" . $signatureFileName;
  5383. $signatureFileExists = file_exists($signatureFileDir);
  5384. if ($signatureFileExists) goto generateSignatureFileName;
  5385. $signatureFileData = str_replace("data:image/png;base64,", "", $form['data']);
  5386. file_put_contents($signatureFileDir, base64_decode($signatureFileData));
  5387. $now = $this->functionsController->now();
  5388. $year = $now->year;
  5389. $month = $now->month < 10 ? "0{$now->month}" : "{$now->month}";
  5390. $day = $now->day < 10 ? "0{$now->day}" : "{$now->day}";
  5391. $fecr = substr("$year", -2) . $month . $day;
  5392. $sec = DB::table('S002V01TAFAL')->where([
  5393. ['AFAL_COMO', '=', "GMPR"],
  5394. ['AFAL_CLDO', '=', "FO"],
  5395. ['AFAL_NULI', '=', $form['linea']],
  5396. ])->orderBy('AFAL_NUSE', 'desc')->first();
  5397. $nuse = 1;
  5398. if (!is_null($sec)) {
  5399. $nuse = intval($sec->AFAL_NUSE) + 1;
  5400. }
  5401. $noar = "firma_conformidad_" . $idUser;
  5402. $exte = "png";
  5403. $ver = DB::table('S002V01TAFAL')->where([
  5404. ['AFAL_NULI', '=', $form['linea']],
  5405. ['AFAL_COMO', '=', "GMPR"],
  5406. ['AFAL_CLDO', '=', "FO"],
  5407. ['AFAL_NOAR', '=', $noar],
  5408. ['AFAL_EXTE', '=', $exte],
  5409. ])->orderBy('AFAL_NUVE', 'desc')->first();
  5410. $nuve = 1;
  5411. if (!is_null($ver)) {
  5412. $nuve = intval($ver->AFAL_NUVE) + 1;
  5413. }
  5414. $tama = filesize($signatureFileDir);
  5415. $code = intval($form['linea']) < 10 ? "0{$form['linea']}" : "{$form['linea']}";
  5416. $code .= "-GMPR-FO-$fecr-";
  5417. for ($i = strlen((string)$nuse); $i < 6; $i++) {
  5418. $code .= "0";
  5419. }
  5420. $code .= "$nuse=";
  5421. $code .= $nuve < 10 ? "0$nuve=" : "$nuve=";
  5422. $code .= "$noar.$exte";
  5423. $usac = json_encode([$idUser]);
  5424. $nowStr = $now->toDateTimeString();
  5425. DB::table('S002V01TAFAL')->insert([
  5426. 'AFAL_NULI' => $form['linea'],
  5427. 'AFAL_COMO' => "GMPR",
  5428. 'AFAL_CLDO' => "FO",
  5429. 'AFAL_FECR' => $fecr,
  5430. 'AFAL_NUSE' => $nuse,
  5431. 'AFAL_NUVE' => $nuve,
  5432. 'AFAL_NOAR' => $noar,
  5433. 'AFAL_EXTE' => $exte,
  5434. 'AFAL_TAMA' => $tama,
  5435. 'AFAL_UBIC' => $signatureFileDir,
  5436. 'AFAL_USAC' => $usac,
  5437. 'AFAL_USRE' => $idUser,
  5438. 'AFAL_FERE' => $nowStr
  5439. ]);
  5440. $signature = $code;
  5441. } else if ($form['attendance'] == 'R') {
  5442. $comments = $form['data'];
  5443. }
  5444. // Última verificación de cupo (concurrencia) antes de confirmar respuesta
  5445. $statusHistoryCheck = json_decode(DB::table('S002V01TRVTN')->where([
  5446. ['RVTN_NULI', '=', $form['linea']],
  5447. ['RVTN_IDVI', '=', $idVisit]
  5448. ])->value('RVTN_HIES'), true);
  5449. $vaObjChk = null;
  5450. if (!empty($statusHistoryCheck)) {
  5451. for ($i = count($statusHistoryCheck) - 1; $i >= 0; $i--) {
  5452. if ($statusHistoryCheck[$i]['ESTADO'] == 'VA') {
  5453. $vaObjChk = $statusHistoryCheck[$i];
  5454. break;
  5455. }
  5456. }
  5457. }
  5458. $aceptadosChk = 0;
  5459. $atencionChk = $vaObjChk && array_key_exists('ATENCION', $vaObjChk) ? $vaObjChk['ATENCION'] : [];
  5460. foreach ($atencionChk as $itm) {
  5461. if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosChk++;
  5462. }
  5463. if ($form['attendance'] == 'A' && $cupoRequerido > 0 && $aceptadosChk >= $cupoRequerido) {
  5464. DB::rollBack();
  5465. return $this->responseController->makeResponse(true, 'La planilla ya está completa. No es posible aceptar esta invitación.', [], 401);
  5466. }
  5467. // Actualizar el objeto en ATENCION
  5468. $statusHistoryArr[$vaStatusIndex]['ATENCION'][$operatorIndex]['RESPUESTA'] = $form['attendance'];
  5469. $statusHistoryArr[$vaStatusIndex]['ATENCION'][$operatorIndex]['FIRMA'] = $signature;
  5470. $statusHistoryArr[$vaStatusIndex]['ATENCION'][$operatorIndex]['COMENTARIOS'] = $comments;
  5471. $statusHistoryStr = json_encode($statusHistoryArr);
  5472. $now = $this->functionsController->now();
  5473. $nowStr = $now->toDateTimeString();
  5474. // Actualizar la visita
  5475. DB::table('S002V01TRVTN')->where([
  5476. ['RVTN_NULI', '=', $form['linea']],
  5477. ['RVTN_IDVI', '=', $idVisit]
  5478. ])->update([
  5479. "RVTN_HIES" => $statusHistoryStr,
  5480. "RVTN_USMO" => $idUser,
  5481. "RVTN_FEMO" => $nowStr,
  5482. ]);
  5483. $userName = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  5484. $action = $form['attendance'] == 'A' ? 'aceptó' : 'rechazó';
  5485. // Preparar notificaciones
  5486. $notificationActions = [];
  5487. if ($form['attendance'] == 'A') {
  5488. $notificationActions[] = [
  5489. 'BOTON' => 'Revisar firma',
  5490. 'FUNCION' => 'reviewSignatureInPreventiveVisit',
  5491. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit), $this->encryptionController->encrypt($idUser)])
  5492. ];
  5493. } else if ($form['attendance'] == 'R') {
  5494. $notificationActions[] = [
  5495. 'BOTON' => 'Revisar comentarios',
  5496. 'FUNCION' => 'reviewCommentsInPreventiveVisit',
  5497. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit), $this->encryptionController->encrypt($idUser)])
  5498. ];
  5499. $notificationActions[] = [
  5500. 'BOTON' => 'Reasignar visita',
  5501. 'FUNCION' => 'revalidatePreventiveVisit',
  5502. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
  5503. ];
  5504. }
  5505. $notificationActions[] = [
  5506. 'BOTON' => 'Ir al módulo',
  5507. 'FUNCION' => 'openModule',
  5508. 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
  5509. ];
  5510. // Notificar al regulador (usuario 0000000001)
  5511. $this->notificationsController->emitNotification(
  5512. 'S002V01M10GMPR',
  5513. "Visita de mantenimiento preventivo #$idVisit",
  5514. "El usuario $userName ($idUser) $action atender la visita de mantenimiento preventivo #$idVisit.",
  5515. $notificationActions,
  5516. ['0000000001'],
  5517. $idUser,
  5518. $form['linea'],
  5519. $this->getSocketClient(),
  5520. $idVisit,
  5521. 'Preventivo'
  5522. );
  5523. $actions = DB::getQueryLog();
  5524. $idac = $this->functionsController->registerActivity(
  5525. $form['linea'],
  5526. 'S002V01M10GMPR',
  5527. 'S002V01F11RVTP',
  5528. 'S002V01P01REVI',
  5529. 'Actualización',
  5530. "El usuario $userName (" . $usr->USUA_IDUS . ") $action atender la visita preventiva #$idVisit.",
  5531. $idUser,
  5532. $nowStr,
  5533. 'S002V01S02AOTR'
  5534. );
  5535. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  5536. // Confirmar transacción
  5537. DB::commit();
  5538. return $this->responseController->makeResponse(false, 'EXITO');
  5539. } catch (\Exception $e) {
  5540. // Revertir transacción en caso de error
  5541. DB::rollBack();
  5542. $actions = DB::getQueryLog();
  5543. $now = $this->functionsController->now();
  5544. $nowStr = $now->toDateTimeString();
  5545. $userName = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
  5546. $idac = $this->functionsController->registerActivity(
  5547. $form['linea'],
  5548. 'S002V01M10GMPR',
  5549. 'S002V01F11RVTP',
  5550. 'S002V01P01REVI',
  5551. 'Error',
  5552. "Error al procesar la respuesta de la visita preventiva #$idVisit: " . $e->getMessage(),
  5553. $idUser,
  5554. $nowStr,
  5555. 'S002V01S02AOTR'
  5556. );
  5557. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  5558. return $this->responseController->makeResponse(
  5559. true,
  5560. 'Ocurrió un error al procesar la respuesta de la visita.',
  5561. ['error' => $e->getMessage()],
  5562. 500
  5563. );
  5564. }
  5565. }
  5566. private function generateSignatureImageName()
  5567. {
  5568. $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"];
  5569. $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"];
  5570. $numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"];
  5571. $fileName = "";
  5572. for ($i = 0; $i < 40; $i++) {
  5573. $charTypeSelector = rand(0, 2);
  5574. $selectedChar = "";
  5575. switch ($charTypeSelector) {
  5576. case 0:
  5577. $charSelector = rand(0, count($upperLetters) - 1);
  5578. $selectedChar = $upperLetters[$charSelector];
  5579. break;
  5580. case 1:
  5581. $charSelector = rand(0, count($lowerLetters) - 1);
  5582. $selectedChar = $lowerLetters[$charSelector];
  5583. break;
  5584. case 2:
  5585. $charSelector = rand(0, count($numbers) - 1);
  5586. $selectedChar = $numbers[$charSelector];
  5587. break;
  5588. }
  5589. $selectedChar = empty($selectedChar) ? 'A' : $selectedChar;
  5590. $fileName .= $selectedChar;
  5591. }
  5592. return $fileName . '.png';
  5593. }
  5594. }