| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626 |
- <?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',
- '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' || $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'] = [];
- }
- }
- // Validar que el operario no haya registrado comentario ya
- foreach ($cpStatus['COMENTARIOS_OPERARIOS'] 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
- $commentsRegistered = count($cpStatus['COMENTARIOS_OPERARIOS']);
- $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 si es necesario
- $commentsArr = json_decode($visit->RVTN_COME, true);
- if (!is_array($commentsArr)) {
- $commentsArr = [];
- }
- // Solo agregar comentario de cambio de estado si es el primer comentario (cambio EP -> CP)
- if ($isFirstComment) {
- $commentsArr['CCP'] = 'Inicio de registro de comentarios de finalización por operarios.';
- }
- $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 != 'PE' && $visit->RVTN_ESTA != 'VA') {
- return $this->responseController->makeResponse(true, 'La visita no está en un estado válido para asignar operarios.', [], 401);
- }
- $staffConfigArr = json_decode($form['config'], true);
- $audience = [];
- foreach ($staffConfigArr as $key => $val) {
- if (!array_key_exists('SPECIALTY', $val) || !array_key_exists('STAFF', $val)) {
- return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
- }
- $specialtyDec = $this->encryptionController->decrypt($val['SPECIALTY']);
- if (!$specialtyDec) {
- return $this->responseController->makeResponse(true, "El identificador de la especialidad en el item $key del arreglo de configuración de operarios no fue encriptado correctamente.", [], 400);
- }
- if (gettype($val['STAFF']) != 'array') {
- return $this->responseController->makeResponse(true, "El contenedor de operarios en el item $key del arreglo de configuración de operarios es inválido.", [], 400);
- }
- foreach ($val['STAFF'] as $key0 => $val0) {
- if (!array_key_exists('ID', $val0) || !array_key_exists('TYPE', $val0)) {
- return $this->responseController->makeResponse(true, "El item $key del arreglo de configuración de operarios tiene un formato inválido.", [], 400);
- }
- $idDec = $this->encryptionController->decrypt($val0['ID']);
- $employee = DB::table('S002V01TPERS')->where([
- ['PERS_NULI', '=', $form['linea']],
- ['PERS_IDPE', '=', $idDec]
- ])->first();
- if (is_null($employee)) {
- return $this->responseController->makeResponse(true, "El operario $key0 de la especialidad $specialtyDec del arreglo de configuración de operarios no existe.", [], 404);
- }
- $audience[] = $employee->PERS_IDUS;
- }
- }
- // Validación de cupo global (basado en RVTN_PEIN)
- $planilla = json_decode($visit->RVTN_PEIN, true);
- $cupoRequerido = 0;
- if (!empty($planilla) && is_array($planilla)) {
- foreach ($planilla as $pe) {
- $cupoRequerido += intval($pe['CANT'] ?? 0);
- }
- }
- // Obtener último VA
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- $vaObj = null;
- if (!empty($statusHistoryArr)) {
- for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
- if ($statusHistoryArr[$i]['ESTADO'] == 'VA') {
- $vaObj = $statusHistoryArr[$i];
- break;
- }
- }
- }
- $atencionActual = $vaObj && array_key_exists('ATENCION', $vaObj) ? $vaObj['ATENCION'] : [];
- $aceptadosActual = 0;
- foreach ($atencionActual as $itm) {
- if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosActual++;
- }
- if ($cupoRequerido > 0 && $aceptadosActual >= $cupoRequerido) {
- return $this->responseController->makeResponse(true, 'La planilla ya está completa. No se pueden asignar más operarios.', [], 401);
- }
- // Evitar invitación duplicada al mismo operario (ya invitado o ya respondió)
- $yaInvitados = [];
- foreach ($atencionActual as $itm) {
- $yaInvitados[$itm['ID']] = $itm['RESPUESTA'] ?? '';
- }
- foreach ($audience as $opId) {
- if (array_key_exists($opId, $yaInvitados)) {
- return $this->responseController->makeResponse(true, "El operario $opId ya fue invitado o respondió anteriormente.", [], 401);
- }
- }
- // Iniciar transacción
- DB::beginTransaction();
- try {
- // Emitir notificación
- $this->notificationsController->emitNotification(
- 'S002V01M10GMPR',
- "Visita de mantenimiento preventivo #$idVisit",
- "Se ha asignado la visita de mantenimiento preventivo #$idVisit y requiere su atención.",
- [[
- 'BOTON' => 'Ver detalles',
- 'FUNCION' => 'openPreventiveWorkOrderDetails',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Atender visita',
- 'FUNCION' => 'attendPreventiveWorkOrder',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt($idVisit)])
- ], [
- 'BOTON' => 'Ir al módulo',
- 'FUNCION' => 'openModule',
- 'PARAMETROS' => json_encode([$this->encryptionController->encrypt('GMPR/AOTR/RVTP')])
- ]],
- $audience,
- $idUser,
- $form['linea'],
- $this->getSocketClient(),
- $idVisit,
- 'Preventivo'
- );
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $statusHistoryArr = json_decode($visit->RVTN_HIES, true);
- // Buscar si ya existe un objeto con estado VA
- $vaStatusIndex = null;
- foreach ($statusHistoryArr as $index => $status) {
- if ($status['ESTADO'] == 'VA') {
- $vaStatusIndex = $index;
- break;
- }
- }
- // Revalidar cupo justo antes de insertar (concurrencia)
- $vaObjRef = null;
- if (!empty($statusHistoryArr)) {
- for ($i = count($statusHistoryArr) - 1; $i >= 0; $i--) {
- if ($statusHistoryArr[$i]['ESTADO'] == 'VA') {
- $vaObjRef = $statusHistoryArr[$i];
- break;
- }
- }
- }
- $atencionRef = $vaObjRef && array_key_exists('ATENCION', $vaObjRef) ? $vaObjRef['ATENCION'] : [];
- $aceptadosRef = 0;
- foreach ($atencionRef as $itm) {
- if (($itm['RESPUESTA'] ?? '') === 'A') $aceptadosRef++;
- }
- if ($cupoRequerido > 0 && $aceptadosRef >= $cupoRequerido) {
- DB::rollBack();
- return $this->responseController->makeResponse(true, 'La planilla ya está completa. No se pueden asignar más operarios.', [], 401);
- }
- // Crear nuevas invitaciones
- $newInvitations = [];
- foreach ($audience as $operarioId) {
- $newInvitations[] = [
- 'ID' => $operarioId,
- 'FIRMA' => null,
- 'RESPUESTA' => '',
- 'COMENTARIOS' => ''
- ];
- }
- if ($vaStatusIndex !== null) {
- // Extender objeto VA existente
- $statusHistoryArr[$vaStatusIndex]['ATENCION'] = array_merge(
- $statusHistoryArr[$vaStatusIndex]['ATENCION'],
- $newInvitations
- );
- // Agregar nuevos operarios a PERSONAL (sin duplicar)
- $currentPersonal = $statusHistoryArr[$vaStatusIndex]['PERSONAL'] ?? [];
- foreach ($audience as $operarioId) {
- if (!in_array($operarioId, $currentPersonal)) {
- $currentPersonal[] = $operarioId;
- }
- }
- $statusHistoryArr[$vaStatusIndex]['PERSONAL'] = $currentPersonal;
- } else {
- // Crear nuevo objeto VA con todos los invitados en PERSONAL
- $statusHistoryArr[] = [
- 'USUARIO' => $idUser,
- 'ESTADO' => 'VA',
- 'FECHA' => $nowStr,
- 'ATENCION' => $newInvitations,
- 'PERSONAL' => $audience
- ];
- }
- $statusHistoryStr = json_encode($statusHistoryArr);
- // Actualizar la visita
- DB::table('S002V01TRVTN')->where([
- ['RVTN_IDVI', '=', $idVisit],
- ['RVTN_NULI', '=', $form['linea']]
- ])->update([
- 'RVTN_ESTA' => 'VA',
- 'RVTN_HIES' => $statusHistoryStr,
- 'RVTN_USMO' => $idUser,
- 'RVTN_FEMO' => $nowStr,
- ]);
- $actions = DB::getQueryLog();
- $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Actualización',
- "El usuario $name (" . $usr->USUA_IDUS . ") asignó operarios a la visita preventiva #$idVisit.",
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- // Confirmar transacción
- DB::commit();
- return $this->responseController->makeResponse(false, 'EXITO.');
- } catch (\Exception $e) {
- // Revertir transacción en caso de error
- DB::rollBack();
- $actions = DB::getQueryLog();
- $now = $this->functionsController->now();
- $nowStr = $now->toDateTimeString();
- $name = $this->functionsController->joinName($usr->USUA_NOMB ?? '', $usr->USUA_APPA ?? '', $usr->USUA_APMA ?? '');
- $idac = $this->functionsController->registerActivity(
- $form['linea'],
- 'S002V01M10GMPR',
- 'S002V01F11RVTP',
- 'S002V01P01REVI',
- 'Error',
- "Error al asignar operarios a la visita preventiva #$idVisit: " . $e->getMessage(),
- $idUser,
- $nowStr,
- 'S002V01S02AOTR'
- );
- $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
- return $this->responseController->makeResponse(
- true,
- 'Ocurrió un error al asignar operarios a la visita preventiva.',
- ['error' => $e->getMessage()],
- 500
- );
- }
- }
- // Visitas técnicas no programadas (Preventivas)
- public function getVisitAttendance($idVisit, $idUser, $line)
- {
- DB::enableQueryLog();
- $idUser = $this->encryptionController->decrypt($idUser);
- if (!$idUser) {
- return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
- }
- $usr = DB::table('S002V01TUSUA')->where([
- ['USUA_NULI', '=', $line],
- ['USUA_IDUS', '=', $idUser],
- ])->first();
- if (is_null($usr)) {
- return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
- }
- $idVisit = $this->encryptionController->decrypt($idVisit);
- if (!$idVisit) {
- return $this->responseController->makeResponse(true, 'El ID de la visita relacionada no está encriptado correctamente', [], 400);
- }
- $visit = DB::table('S002V01TRVTN')->where([
- ['RVTN_NULI', '=', $line],
- ['RVTN_IDVI', '=', $idVisit]
- ])->first();
- if (is_null($visit)) {
- return $this->responseController->makeResponse(true, 'La visita relacionada no está registrada.', [], 404);
- }
- // Validar que la visita esté en estado VA (validado)
- // Puede estar en estado VA en RVTN_ESTA sin tener aún el objeto VA en RVTN_HIES
- // (cuando se crea automáticamente pero aún no se han asignado operarios)
- $visitStates = [
- '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';
- }
- }
|