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