PreventiveMaintenanceController.php 218 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160
  1. <?php
  2. namespace App\Http\Controllers;
  3. use Illuminate\Http\Request;
  4. use Illuminate\Support\Facades\DB;
  5. use Illuminate\Support\Facades\Validator;
  6. use Illuminate\Support\Carbon;
  7. use Dompdf\Dompdf;
  8. use Illuminate\Support\Facades\Storage;
  9. use Illuminate\Http\File;
  10. use PhpOffice\PhpSpreadsheet\IOFactory;
  11. use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
  12. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  13. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  14. class PreventiveMaintenanceController extends Controller{
  15. private $responseController;
  16. private $encryptionController;
  17. private $functionsController;
  18. private $templatesUbic;
  19. private $documentManagementController;
  20. private $requestLineController;
  21. public function __construct(){
  22. $this->responseController = new ResponseController();
  23. $this->encryptionController = new EncryptionController();
  24. $this->functionsController = new FunctionsController();
  25. $this->templatesUbic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\public\pdf_templates\\01_03_GMPR\\";
  26. $this->documentManagementController = new DocumentManagementController();
  27. $this->requestLineController = new RequestLineController();
  28. }
  29. public function registerWorkOrder(Request $request){
  30. DB::enableQueryLog();
  31. $validator = Validator::make($request->all(), [
  32. 'id_user' => 'required|string',
  33. 'linea' => 'required|integer',
  34. 'description' => 'required|string',
  35. 'instructions' => 'required|json',
  36. 'start_date' => 'required|date',
  37. 'start_hour' => 'required|string',
  38. 'end_date' => 'date',
  39. 'end_hour' => 'string',
  40. 'equipment' => 'required|string',
  41. 'inm_time' => 'required|numeric',
  42. 'total_time' => 'required|numeric',
  43. 'resources' => 'required|json',
  44. 'activator' => 'required|string',
  45. 'attached' => 'json',
  46. 'exists' => 'required|string|in:S,N',
  47. 'id_order' => 'required_if:exists,=,S|string',
  48. 'clasification' => 'required|string|max:100',
  49. 'staff' => 'required|json',
  50. ]);
  51. if($validator->fails()){
  52. return $this->responseController->makeResponse(
  53. true,
  54. "Se encontraron uno o más errores.",
  55. $this->responseController->makeErrors(
  56. $validator->errors()->messages()
  57. ),
  58. 401
  59. );
  60. }
  61. $form = $request->all();
  62. $idUser = $this->encryptionController->decrypt($form['id_user']);
  63. if(!$idUser){
  64. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  65. }
  66. $usr = DB::table('S002V01TUSUA')->where([
  67. ['USUA_NULI', '=', $form['linea']],
  68. ['USUA_IDUS', '=', $idUser]
  69. ])->first();
  70. if(is_null($usr)){
  71. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  72. }
  73. $idActivator = $this->encryptionController->decrypt($form['activator']);
  74. if(!$idActivator){
  75. return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400);
  76. }
  77. $activator = DB::table('S002V01TACTI')->where([
  78. ['ACTI_NULI', '=', $form['linea']],
  79. ['ACTI_IDAC', '=', $idActivator]
  80. ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first();
  81. if(is_null($activator)){
  82. return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
  83. }
  84. $startDateTime = "$form[start_date] $form[start_hour]";
  85. $validStartDateTime = $this->functionsController->validateDate($startDateTime);
  86. if(!$validStartDateTime){
  87. return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400);
  88. }
  89. $dateTimeStart = new Carbon($startDateTime);
  90. if($activator->ACTI_TIAC == 'Calendario' || $activator->ACTI_TIAC == 'Sintoma'){
  91. $activatorConfig = json_decode($activator->ACTI_COAC, true);
  92. $activatorStartDate = explode('T', $activatorConfig['startDate'])[0];
  93. $activatorStartDateTime = "$activatorStartDate $activatorConfig[startHour]";
  94. $activatorStartDateTimeObj = new Carbon($activatorStartDateTime);
  95. if($dateTimeStart->lt($activatorStartDateTimeObj)){
  96. 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);
  97. }
  98. }
  99. $ftap = '0001-01-01 00:00:00';
  100. if(isset($form['end_hour'])){
  101. $endDateTime = "$form[end_date] $form[end_hour]";
  102. $validEndDateTime = $this->functionsController->validateDate($endDateTime);
  103. if(!$validEndDateTime){
  104. return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400);
  105. }
  106. $dateTimeEnd = new Carbon("$endDateTime");
  107. if($dateTimeStart->gt($dateTimeEnd)){
  108. return $this->responseController->makeResponse(true, 'La hora de término es menor a la hora de inicio.', [], 400);
  109. }
  110. $ftap = $dateTimeEnd->toDateTimeString();
  111. }
  112. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  113. if(!$equipmentCode){
  114. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
  115. }
  116. $equipment = DB::table('S002V01TEQUI')->where([
  117. ['EQUI_NULI', '=', $form['linea']],
  118. ['EQUI_COEQ', '=', $equipmentCode]
  119. ])->first();
  120. if(is_null($equipment)){
  121. return $this->responseController->makeResponse(true, 'El equipaiento seleccionado no existe.', [], 404);
  122. }else if($activator->CONA_COEQ != $equipmentCode){
  123. return $this->responseController->makeResponse(true, 'El activador seleccionado no puede ser asignado al equipamiento relacionado, ya que el contador pertenece a otro equipo.', [], 401);
  124. }else if(floatval($form['inm_time']) > floatval($form['total_time'])){
  125. return $this->responseController->makeResponse(true, 'El tiempo de inmovilización aproximado no puede ser mayor al tiempo de duración aproximada.', [], 400);
  126. }
  127. $staffArr = json_decode($form['staff'], true);
  128. if(empty($staffArr)){
  129. return $this->responseController->makeResponse(true, 'El JSON de personal está vacío.', [], 400);
  130. }
  131. $staff = [];
  132. foreach($staffArr as $val){
  133. if(!array_key_exists('TYPE', $val) && !array_key_exists('ID', $val)){
  134. return $this->responseController->makeResponse(true, "El arreglo del personal no tiene un formato válido.", [], 400);
  135. }
  136. $typeStr = '';
  137. if($val['TYPE'] == 'EQ'){
  138. $typeStr = 'equipo de trabajo';
  139. }else if($val['TYPE'] == 'SU'){
  140. $typeStr = 'subcontratista';
  141. }else if($val['TYPE'] == 'EM'){
  142. $typeStr = 'empleado';
  143. }
  144. $key = $this->encryptionController->decrypt($val['ID']);
  145. if(!$key){
  146. return $this->responseController->makeResponse(true, "El ID del $typeStr no fue encriptado correctamente.", [], 400);
  147. }
  148. $res = null;
  149. if($val['TYPE'] == 'EQ'){
  150. $res = DB::table('S002V01TEQMA')->where([
  151. ['EQMA_NULI', '=', $form['linea']],
  152. ['EQMA_IDEQ', '=', $key],
  153. ])->first();
  154. }else if($val['TYPE'] == 'SU'){
  155. $res = DB::table('S002V01TPESU')->where([
  156. ['PESU_NULI', '=', $form['linea']],
  157. ['PESU_IDPS', '=', $key],
  158. ])->first();
  159. }else if($val['TYPE'] == 'EM'){
  160. $res = DB::table('S002V01TPERS')->where([
  161. ['PERS_NULI', '=', $form['linea']],
  162. ['PERS_IDPE', '=', $key],
  163. ])->first();
  164. }
  165. if(is_null($res)){
  166. return $this->responseController->makeResponse(true, "El $typeStr no está registrado.", [], 400);
  167. }
  168. $staff[] = [
  169. 'ID' => $key,
  170. 'TYPE' => $val['TYPE']
  171. ];
  172. }
  173. $instructionsArr = json_decode($form['instructions'], true);
  174. foreach($instructionsArr as $key=>$instruction){
  175. $instructionInd = $key + 1;
  176. $instructionStartDateTime = new Carbon($instruction['INICIO']);
  177. if($instructionStartDateTime->lt($dateTimeStart)){
  178. 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);
  179. }
  180. if(isset($form['end_hour'])){
  181. $dateTimeEnd = new Carbon($ftap);
  182. $instructionEndDateTime = new Carbon($instruction['FIN']);
  183. if($instructionEndDateTime->gt($dateTimeEnd)){
  184. 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);
  185. }
  186. }
  187. }
  188. $oppr = json_encode($staff);
  189. $now = $this->functionsController->now();
  190. $nowStr = $now->toDateTimeString();
  191. $fiap = $dateTimeStart->toDateTimeString();
  192. $attachedArrFn = [];
  193. if(isset($form['attached'])){
  194. $attachedArr = json_decode($form['attached'], true);
  195. foreach($attachedArr as $key=>$attached){
  196. $idDec = $this->encryptionController->decrypt($attached['id']);
  197. if(!$idDec){
  198. return $this->responseController->makeResponse(true, "El ID del documento en la posición $key no fue encriptado correctamente.", [], 400);
  199. }
  200. if($attached['type'] == 'Existente'){
  201. $codeArr = explode('=', $idDec);
  202. $codeArr0 = explode('-', $codeArr[0]);
  203. $file = DB::table('S002V01TAFAL')->where([
  204. ['AFAL_NULI', '=', $form['linea']],
  205. ['AFAL_COMO', '=', $codeArr0[1]],
  206. ['AFAL_CLDO', '=', $codeArr0[2]],
  207. ['AFAL_FECR', '=', $codeArr0[3]],
  208. ['AFAL_NUSE', '=', $codeArr0[4]],
  209. ['AFAL_NUVE', '=', $codeArr[1]],
  210. ])->first();
  211. if(is_null($file)){
  212. return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
  213. }else if($file->AFAL_ESTA == 'Eliminado'){
  214. return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
  215. }
  216. $attachedArrFn[] = $idDec;
  217. }else if($attached['type'] == 'Nuevo'){
  218. $tempFile = DB::table('S002V01TARTE')->where([
  219. ['ARTE_IDAR', '=', $idDec],
  220. ['ARTE_NULI', '=', $form['linea']]
  221. ])->first();
  222. if(is_null($tempFile)){
  223. return $this->responseController->makeResponse(true, "El documento en la posición $key no existe.", [], 404);
  224. }else if($tempFile->ARTE_ESTA == 'Eliminado'){
  225. return $this->responseController->makeResponse(true, "El documento en la posición $key está eliminado.", [], 404);
  226. }
  227. $finalFile = $this->documentManagementController->moveFinalFile($form['linea'], 'GMPR', 'OR', $tempFile, $idUser);
  228. if(!$finalFile){
  229. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  230. }else{
  231. $attachedArrFn[] = $finalFile[1];
  232. }
  233. }
  234. }
  235. }
  236. $done = json_encode($attachedArrFn);
  237. $orderCreated = null;
  238. if($form['exists'] == 'S'){
  239. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  240. if(!$idOrder){
  241. return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
  242. }
  243. $order = DB::table('S002V01TOTPR')->where([
  244. ['OTPR_IDOT', '=', $idOrder],
  245. ['OTPR_NULI', '=', $form['linea']]
  246. ])->first();
  247. if(is_null($order)){
  248. return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404);
  249. }
  250. DB::table('S002V01TOTPR')->where([
  251. ['OTPR_IDOT', '=', $idOrder],
  252. ['OTPR_NULI', '=', $form['linea']]
  253. ])->update([
  254. 'OTPR_DEIN' => $form['description'],
  255. 'OTPR_ININ' => $form['instructions'],
  256. 'OTPR_EQIN' => $equipmentCode,
  257. 'OTPR_FIAP' => $fiap,
  258. 'OTPR_FTAP' => $ftap,
  259. 'OTPR_TIIN' => $form['inm_time'],
  260. 'OTPR_OPPR' => $oppr,
  261. 'OTPR_DTIN' => $form['total_time'],
  262. 'OTPR_RHRE' => $form['resources'],
  263. 'OTPR_DONE' => $done,
  264. 'OTPR_ACAS' => $idActivator,
  265. 'OTPR_CLAS' => $form['clasification'],
  266. 'OTPR_ESTA' => 'R',
  267. 'OTPR_USMO' => $idUser,
  268. 'OTPR_FEMO' => $nowStr,
  269. ]);
  270. $orderCreated = $idOrder;
  271. }else{
  272. $idOrder = DB::table('S002V01TOTPR')->insertGetId([
  273. 'OTPR_NULI' => $form['linea'],
  274. 'OTPR_DEIN' => $form['description'],
  275. 'OTPR_ININ' => $form['instructions'],
  276. 'OTPR_EQIN' => $equipmentCode,
  277. 'OTPR_FIAP' => $fiap,
  278. 'OTPR_FTAP' => $ftap,
  279. 'OTPR_TIIN' => $form['inm_time'],
  280. 'OTPR_OPPR' => $oppr,
  281. 'OTPR_DTIN' => $form['total_time'],
  282. 'OTPR_RHRE' => $form['resources'],
  283. 'OTPR_DONE' => $done,
  284. 'OTPR_ACAS' => $idActivator,
  285. 'OTPR_CLAS' => $form['clasification'],
  286. 'OTPR_ESTA' => 'R',
  287. 'OTPR_USRE' => $idUser,
  288. 'OTPR_FERE' => $nowStr,
  289. ]);
  290. $orderCreated = $idOrder;
  291. }
  292. //Pendiente revisar con stock
  293. $resources = json_decode($form['resources'], true);
  294. if(empty($resources)){
  295. return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
  296. }
  297. $responseCheckItems = $this->requestLineController->checkItemsWorkOrder($resources, $orderCreated, $idUser, $form['linea']);
  298. if ($responseCheckItems['error']) {
  299. return $this->responseController->makeResponse(true, $responseCheckItems['msg'], $responseCheckItems['response'], 400);
  300. }
  301. $actions = DB::getQueryLog();
  302. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  303. $idac = $this->functionsController->registerActivity(
  304. $form['linea'],
  305. 'S002V01M10GMPR',
  306. 'S002V01F01COTP',
  307. 'S002V01P01ROTR',
  308. 'Registro',
  309. "El usuario $name (" . $usr->USUA_IDUS . ") registró la orden de trabajo #$idOrder.",
  310. $idUser,
  311. $nowStr,
  312. 'S002V01S01ORTR'
  313. );
  314. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  315. return $this->responseController->makeResponse(false, 'EXITO.');
  316. }
  317. public function getWorkOrders($idUser, $line){
  318. DB::enableQueryLog();
  319. $idUser = $this->encryptionController->decrypt($idUser);
  320. if(!$idUser){
  321. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  322. }
  323. $usr = DB::table('S002V01TUSUA')->where([
  324. ['USUA_NULI', '=', $line],
  325. ['USUA_IDUS', '=', $idUser],
  326. ])->first();
  327. if(is_null($usr)){
  328. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  329. }
  330. $workOrders = DB::table('S002V01TOTPR')->select([
  331. 'OTPR_IDOT AS IDORDEN',
  332. 'OTPR_EQIN AS EQUIPO',
  333. 'OTPR_FIAP AS FECHAINICIO',
  334. 'OTPR_FTAP AS FECHAFINAL',
  335. 'OTPR_ACAS AS ACTIVADOR',
  336. 'ACTI_TIAC AS TIPOACTIVADOR',
  337. 'ACTI_PRIO AS PRIORIDAD',
  338. 'OTPR_ESTA AS ESTATUS'
  339. ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')
  340. ->where('OTPR_NULI', '=', $line)
  341. ->orderBy('OTPR_IDOT', 'desc')->get()->all();
  342. foreach($workOrders as $key=>$order){
  343. $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
  344. $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO);
  345. $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR);
  346. if(!is_null($order->PRIORIDAD)){
  347. $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
  348. }
  349. if($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null;
  350. if($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null;
  351. $workOrders[$key] = $order;
  352. }
  353. $now = $this->functionsController->now();
  354. $nowStr = $now->toDateTimeString();
  355. $actions = DB::getQueryLog();
  356. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  357. $idac = $this->functionsController->registerActivity(
  358. $line,
  359. 'S002V01M10GMPR',
  360. 'S002V01F01COTP',
  361. 'S002V01P01HOTP',
  362. 'Consulta',
  363. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo registradas.",
  364. $idUser,
  365. $nowStr,
  366. 'S002V01S01ORTR'
  367. );
  368. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  369. return $this->responseController->makeResponse(false, 'EXITO.', $workOrders);
  370. }
  371. public function getWorkOrdersByMonth($month, $year, $idUser, $line){
  372. //PENDIENTE ELIMINAR
  373. DB::enableQueryLog();
  374. $idUser = $this->encryptionController->decrypt($idUser);
  375. if(!$idUser){
  376. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  377. }
  378. $usr = DB::table('S002V01TUSUA')->where([
  379. ['USUA_NULI', '=', $line],
  380. ['USUA_IDUS', '=', $idUser],
  381. ])->first();
  382. if(is_null($usr)){
  383. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  384. }
  385. $events = DB::table('S002V01TOTPR')->where([
  386. ['OTPR_NULI', '=', $line],
  387. ['OTPR_ESTA', '!=', 'Eliminado'],
  388. ])->orderBy(
  389. 'OTPR_FIIN', 'asc'
  390. )->orderBy(
  391. 'OTPR_HIIN', 'asc'
  392. )->orderBy(
  393. 'OTPR_PRIO', 'asc'
  394. )->get()->all();
  395. try{
  396. $firstDay = new Carbon("$year-$month-01", 'America/Mexico_city');
  397. $days = $firstDay->daysInMonth;
  398. $lastDay = new Carbon("$year-$month-$days", 'America/Mexico_city');
  399. }catch(\Carbon\Exceptions\InvalidFormatException $e){
  400. return $this->responseController->makeResponse(true, 'El mes o el año tienen un formato incorrecto', [], 400);
  401. }
  402. $eventsArr = [];
  403. foreach($events as $event){
  404. $repetition = json_decode($event->OTPR_REPE, true);
  405. $startDate = new Carbon($event->OTPR_FIIN, 'America/Mexico_city');
  406. switch($repetition['type']){
  407. case "NR":
  408. if($startDate->gte($firstDay) && $startDate->lte($lastDay)){
  409. $dateStr = $startDate->toDateString();
  410. $exec = DB::table('S002V01TBEOT')->where([
  411. ['BEOT_NULI', '=', $line],
  412. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  413. ['BEOT_FEPR', '=', $dateStr],
  414. ])->first();
  415. $esta = 'NE';
  416. if(!is_null($exec)){
  417. $estatus = $exec->BEOT_TIAC;
  418. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  419. }
  420. $eventsArr[$dateStr][] = [
  421. 'IDORDEN' => $event->OTPR_IDOT,
  422. 'TITULO' => $event->OTPR_TIOR,
  423. 'ESTATUS' => $esta,
  424. ];
  425. }
  426. break;
  427. case "SE":
  428. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  429. while($iniAux->lte($lastDay)){
  430. $dateStr = $iniAux->toDateString();
  431. $exec = DB::table('S002V01TBEOT')->where([
  432. ['BEOT_NULI', '=', $line],
  433. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  434. ['BEOT_FEPR', '=', $dateStr],
  435. ])->first();
  436. $esta = 'NE';
  437. if(!is_null($exec)){
  438. $estatus = $exec->BEOT_TIAC;
  439. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  440. }
  441. $eventsArr[$dateStr][] = [
  442. 'IDORDEN' => $event->OTPR_IDOT,
  443. 'TITULO' => $event->OTPR_TIOR,
  444. 'ESTATUS' => $esta,
  445. ];
  446. $iniAux->addWeek();
  447. }
  448. break;
  449. case "ME":
  450. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  451. while($iniAux->lte($lastDay)){
  452. $dateStr = $iniAux->toDateString();
  453. $exec = DB::table('S002V01TBEOT')->where([
  454. ['BEOT_NULI', '=', $line],
  455. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  456. ['BEOT_FEPR', '=', $dateStr],
  457. ])->first();
  458. $esta = 'NE';
  459. if(!is_null($exec)){
  460. $estatus = $exec->BEOT_TIAC;
  461. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  462. }
  463. $eventsArr[$dateStr][] = [
  464. 'IDORDEN' => $event->OTPR_IDOT,
  465. 'TITULO' => $event->OTPR_TIOR,
  466. 'ESTATUS' => $esta,
  467. ];
  468. $iniAux->addMonth();
  469. }
  470. break;
  471. case "AN":
  472. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  473. while($iniAux->lte($lastDay)){
  474. $dateStr = $iniAux->toDateString();
  475. $exec = DB::table('S002V01TBEOT')->where([
  476. ['BEOT_NULI', '=', $line],
  477. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  478. ['BEOT_FEPR', '=', $dateStr],
  479. ])->first();
  480. $esta = 'NE';
  481. if(!is_null($exec)){
  482. $estatus = $exec->BEOT_TIAC;
  483. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  484. }
  485. $eventsArr[$dateStr][] = [
  486. 'IDORDEN' => $event->OTPR_IDOT,
  487. 'TITULO' => $event->OTPR_TIOR,
  488. 'ESTATUS' => $esta,
  489. ];
  490. $iniAux->addYear();
  491. }
  492. break;
  493. case "TD":
  494. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  495. while($iniAux->lte($lastDay)){
  496. $dateStr = $iniAux->toDateString();
  497. $exec = DB::table('S002V01TBEOT')->where([
  498. ['BEOT_NULI', '=', $line],
  499. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  500. ['BEOT_FEPR', '=', $dateStr],
  501. ])->first();
  502. $esta = 'NE';
  503. if(!is_null($exec)){
  504. $estatus = $exec->BEOT_TIAC;
  505. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  506. }
  507. $eventsArr[$iniAux->toDateString()][] = [
  508. 'IDORDEN' => $event->OTPR_IDOT,
  509. 'TITULO' => $event->OTPR_TIOR,
  510. 'ESTATUS' => $esta,
  511. ];
  512. $iniAux->addDay();
  513. }
  514. break;
  515. case "PE":
  516. $periods = ['D', 'W', 'M', 'Y'];
  517. $config = json_decode($repetition['config'], true);
  518. $repeatEvery = explode('|', $config['repeatEvery']);
  519. $endsAt = explode('|', $config['endsAt']);
  520. $period = $periods[intval($repeatEvery[1])];
  521. switch($endsAt[0]){
  522. case "N":
  523. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  524. while($iniAux->lte($lastDay)){
  525. if($period == 'W'){
  526. $weekStart = (new Carbon($iniAux->toDateTimeString(), 'America/Mexico_city'))->subDays($iniAux->dayOfWeek);
  527. for($i = 0; $i < 7; $i++){
  528. $dayName = $weekStart->dayName;
  529. $dayName = strtolower($dayName);
  530. $dayName = substr($dayName, 0, 3);
  531. if($config['repeatOn'][$dayName] && $weekStart->gte($startDate)){
  532. $dateStr = $weekStart->toDateString();
  533. $exec = DB::table('S002V01TBEOT')->where([
  534. ['BEOT_NULI', '=', $line],
  535. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  536. ['BEOT_FEPR', '=', $dateStr],
  537. ])->first();
  538. $esta = 'NE';
  539. if(!is_null($exec)){
  540. $estatus = $exec->BEOT_TIAC;
  541. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  542. }
  543. $eventsArr[$dateStr][] = [
  544. 'IDORDEN' => $event->OTPR_IDOT,
  545. 'TITULO' => $event->OTPR_TIOR,
  546. 'ESTATUS' => $esta,
  547. ];
  548. }
  549. $weekStart->addDay();
  550. }
  551. }else{
  552. $dateStr = $iniAux->toDateString();
  553. $exec = DB::table('S002V01TBEOT')->where([
  554. ['BEOT_NULI', '=', $line],
  555. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  556. ['BEOT_FEPR', '=', $dateStr],
  557. ])->first();
  558. $esta = 'NE';
  559. if(!is_null($exec)){
  560. $estatus = $exec->BEOT_TIAC;
  561. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  562. }
  563. $eventsArr[$dateStr][] = [
  564. 'IDORDEN' => $event->OTPR_IDOT,
  565. 'TITULO' => $event->OTPR_TIOR,
  566. 'ESTATUS' => $esta,
  567. ];
  568. }
  569. if($period == 'D') $iniAux->addDays(intval($repeatEvery[0]));
  570. if($period == 'W') $iniAux->addWeeks(intval($repeatEvery[0]));
  571. if($period == 'M') $iniAux->addMonths(intval($repeatEvery[0]));
  572. if($period == 'Y') $iniAux->addYears(intval($repeatEvery[0]));
  573. }
  574. break;
  575. case "O":
  576. $endDateArr = explode('-', $endsAt[1]);
  577. $month = intval($endDateArr[1]) + 1 < 10 ? "0" . intval($endDateArr[1]) + 1 : "" . intval($endDateArr[1]) + 1 . "";
  578. $endDateStr = "$endDateArr[2]-$month-$endDateArr[0]";
  579. $endDate = new Carbon($endDateStr, 'America/Mexico_city');
  580. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  581. while($iniAux->lte($lastDay)){
  582. if($period == 'W'){
  583. $weekStart = (new Carbon($iniAux->toDateTimeString(), 'America/Mexico_city'))->subDays($iniAux->dayOfWeek);
  584. for($i = 0; $i < 7; $i++){
  585. $dayName = $weekStart->dayName;
  586. $dayName = strtolower($dayName);
  587. $dayName = substr($dayName, 0, 3);
  588. if($config['repeatOn'][$dayName] && $weekStart->gte($startDate) && $weekStart->lte($endDate)){
  589. $dateStr = $weekStart->toDateString();
  590. $exec = DB::table('S002V01TBEOT')->where([
  591. ['BEOT_NULI', '=', $line],
  592. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  593. ['BEOT_FEPR', '=', $dateStr],
  594. ])->first();
  595. $esta = 'NE';
  596. if(!is_null($exec)){
  597. $estatus = $exec->BEOT_TIAC;
  598. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  599. }
  600. $eventsArr[$dateStr][] = [
  601. 'IDORDEN' => $event->OTPR_IDOT,
  602. 'TITULO' => $event->OTPR_TIOR,
  603. 'ESTATUS' => $esta,
  604. ];
  605. }
  606. $weekStart->addDay();
  607. }
  608. }else{
  609. if($iniAux->lte($endDate)){
  610. $dateStr = $iniAux->toDateString();
  611. $exec = DB::table('S002V01TBEOT')->where([
  612. ['BEOT_NULI', '=', $line],
  613. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  614. ['BEOT_FEPR', '=', $dateStr],
  615. ])->first();
  616. $esta = 'NE';
  617. if(!is_null($exec)){
  618. $estatus = $exec->BEOT_TIAC;
  619. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  620. }
  621. $eventsArr[$dateStr][] = [
  622. 'IDORDEN' => $event->OTPR_IDOT,
  623. 'TITULO' => $event->OTPR_TIOR,
  624. 'ESTATUS' => $esta,
  625. ];
  626. }
  627. }
  628. if($period == 'D') $iniAux->addDays(intval($repeatEvery[0]));
  629. if($period == 'W') $iniAux->addWeeks(intval($repeatEvery[0]));
  630. if($period == 'M') $iniAux->addMonths(intval($repeatEvery[0]));
  631. if($period == 'Y') $iniAux->addYears(intval($repeatEvery[0]));
  632. }
  633. break;
  634. case "A":
  635. $repeat = intval($endsAt[2]);
  636. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  637. $cont = 0;
  638. while($iniAux->lte($lastDay)){
  639. if($period == 'W'){
  640. $weekStart = (new Carbon($iniAux->toDateTimeString(), 'America/Mexico_city'))->subDays($iniAux->dayOfWeek);
  641. for($i = 0; $i < 7; $i++){
  642. $dayName = $weekStart->dayName;
  643. $dayName = strtolower($dayName);
  644. $dayName = substr($dayName, 0, 3);
  645. if($config['repeatOn'][$dayName] && $weekStart->gte($startDate) && $cont < $repeat){
  646. $dateStr = $weekStart->toDateString();
  647. $exec = DB::table('S002V01TBEOT')->where([
  648. ['BEOT_NULI', '=', $line],
  649. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  650. ['BEOT_FEPR', '=', $dateStr],
  651. ])->first();
  652. $esta = 'NE';
  653. if(!is_null($exec)){
  654. $estatus = $exec->BEOT_TIAC;
  655. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  656. }
  657. $eventsArr[$dateStr][] = [
  658. 'IDORDEN' => $event->OTPR_IDOT,
  659. 'TITULO' => $event->OTPR_TIOR,
  660. 'ESTATUS' => $esta,
  661. ];
  662. }
  663. $weekStart->addDay();
  664. }
  665. }else{
  666. if($cont < $repeat){
  667. $dateStr = $iniAux->toDateString();
  668. $exec = DB::table('S002V01TBEOT')->where([
  669. ['BEOT_NULI', '=', $line],
  670. ['BEOT_IDOT', '=', $event->OTPR_IDOT],
  671. ['BEOT_FEPR', '=', $dateStr],
  672. ])->first();
  673. $esta = 'NE';
  674. if(!is_null($exec)){
  675. $estatus = $exec->BEOT_TIAC;
  676. $esta = $estatus == 'Ejecucion' ? 'EJ' : ($estatus == 'Finalizado' ? 'FI' : 'CA');
  677. }
  678. $eventsArr[$dateStr][] = [
  679. 'IDORDEN' => $event->OTPR_IDOT,
  680. 'TITULO' => $event->OTPR_TIOR,
  681. 'ESTATUS' => $esta,
  682. ];
  683. }
  684. }
  685. if($period == 'D') $iniAux->addDays(intval($repeatEvery[0]));
  686. if($period == 'W') $iniAux->addWeeks(intval($repeatEvery[0]));
  687. if($period == 'M') $iniAux->addMonths(intval($repeatEvery[0]));
  688. if($period == 'Y') $iniAux->addYears(intval($repeatEvery[0]));
  689. $cont++;
  690. }
  691. break;
  692. }
  693. break;
  694. }
  695. }
  696. $eventsF = [];
  697. foreach($eventsArr as $fec => $events){
  698. foreach($events as $event){
  699. $eventsF[] = [
  700. "IDORDEN" => $event['IDORDEN'],
  701. "TITULO" => $event['TITULO'],
  702. "FECHA" => $fec,
  703. 'ESTATUS' => array_key_exists('ESTATUS', $event) ? $event['ESTATUS'] : '-',
  704. ];
  705. }
  706. }
  707. $now = $this->functionsController->now();
  708. $nowStr = $now->toDateTimeString();
  709. $actions = DB::getQueryLog();
  710. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  711. $idac = $this->functionsController->registerActivity(
  712. $line,
  713. 'S002V01M10GMPR',
  714. 'S002V01F01COTP',
  715. 'S002V01P02COME',
  716. 'Consulta',
  717. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los eventos del mes $month del $year.",
  718. $idUser,
  719. $nowStr,
  720. 'S002V01S01ORTR'
  721. );
  722. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  723. return $this->responseController->makeResponse(false, 'EXITO.', $eventsF);
  724. }
  725. public function getWorkOrdersByDay($day, $month, $year, $idUser, $line){
  726. //PENDIENTE ELIMINAR
  727. DB::enableQueryLog();
  728. $idUser = $this->encryptionController->decrypt($idUser);
  729. if(!$idUser){
  730. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente', [], 400);
  731. }
  732. $usr = DB::table('S002V01TUSUA')->where([
  733. ['USUA_NULI', '=', $line],
  734. ['USUA_IDUS', '=', $idUser],
  735. ])->first();
  736. if(is_null($usr)){
  737. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  738. }
  739. $events = DB::table('S002V01TOTPR')->select([
  740. 'OTPR_IDOT AS IDORDEN',
  741. 'OTPR_TIOR AS TITULO',
  742. 'OTPR_FIIN AS FECHAINICIO',
  743. 'OTPR_HIIN AS HORAINICIO',
  744. 'OTPR_TIES AS TIEMPOESTIMADO',
  745. 'OTPR_CEIN AS CODIGOEQUIPO',
  746. 'OTPR_CLAS AS CLASIFICACION',
  747. 'OTPR_PRIO AS PRIORIDAD',
  748. 'OTPR_ESTA AS ESTADO',
  749. 'OTPR_REPE AS REPETICION'
  750. ])->where([
  751. ['OTPR_NULI', '=', $line]
  752. ])->orderBy(
  753. 'OTPR_FIIN', 'asc'
  754. )->orderBy(
  755. 'OTPR_HIIN', 'asc'
  756. )->orderBy(
  757. 'OTPR_PRIO', 'asc'
  758. )->get()->all();
  759. try{
  760. $consultedDay = new Carbon("$year-$month-$day", 'America/Mexico_city');
  761. $firstDay = new Carbon("$year-$month-01", 'America/Mexico_city');
  762. $days = $firstDay->daysInMonth;
  763. $lastDay = new Carbon("$year-$month-$days", 'America/Mexico_city');
  764. }catch(\Carbon\Exceptions\InvalidFormatException $e){
  765. return $this->responseController->makeResponse(true, 'El día, mes o el año tienen un formato incorrecto', [], 400);
  766. }
  767. $eventsArr = [];
  768. foreach($events as $event){
  769. $repetition = json_decode($event->REPETICION, true);
  770. $startDate = new Carbon($event->FECHAINICIO, 'America/Mexico_city');
  771. $startDate = new Carbon($startDate->toDateString(), 'America/Mexico_city');
  772. switch($repetition['type']){
  773. case "NR":
  774. if($consultedDay->eq($startDate)){
  775. $eventsArr[$startDate->toDateString()][] = $event;
  776. }
  777. break;
  778. case "SE":
  779. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  780. while($iniAux->lte($lastDay)){
  781. if($consultedDay->eq($iniAux)){
  782. $eventsArr[$iniAux->toDateString()][] = $event;
  783. }
  784. $iniAux->addWeek();
  785. }
  786. break;
  787. case "ME":
  788. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  789. while($iniAux->lte($lastDay)){
  790. if($consultedDay->eq($iniAux)){
  791. $eventsArr[$iniAux->toDateString()][] = $event;
  792. }
  793. $iniAux->addMonth();
  794. }
  795. break;
  796. case "AN":
  797. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  798. while($iniAux->lte($lastDay)){
  799. if($consultedDay->eq($iniAux)){
  800. $eventsArr[$iniAux->toDateString()][] = $event;
  801. }
  802. $iniAux->addYear();
  803. }
  804. break;
  805. case "TD":
  806. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  807. while($iniAux->lte($lastDay)){
  808. if($consultedDay->eq($iniAux)){
  809. $eventsArr[$iniAux->toDateString()][] = $event;
  810. }
  811. $iniAux->addDay();
  812. }
  813. break;
  814. case "PE":
  815. $periods = ['D', 'W', 'M', 'Y'];
  816. $config = json_decode($repetition['config'], true);
  817. $repeatEvery = explode('|', $config['repeatEvery']);
  818. $endsAt = explode('|', $config['endsAt']);
  819. $period = $periods[intval($repeatEvery[1])];
  820. switch($endsAt[0]){
  821. case "N":
  822. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  823. while($iniAux->lte($lastDay)){
  824. if($period == 'W'){
  825. $weekStart = (new Carbon($iniAux->toDateTimeString(), 'America/Mexico_city'))->subDays($iniAux->dayOfWeek);
  826. for($i = 0; $i < 7; $i++){
  827. $dayName = $weekStart->dayName;
  828. $dayName = strtolower($dayName);
  829. $dayName = substr($dayName, 0, 3);
  830. if($config['repeatOn'][$dayName] && $weekStart->gte($startDate)){
  831. if($consultedDay->eq($weekStart)){
  832. $eventsArr[$weekStart->toDateString()][] = $event;
  833. }
  834. }
  835. $weekStart->addDay();
  836. }
  837. }else{
  838. if($consultedDay->eq($iniAux)){
  839. $eventsArr[$iniAux->toDateString()][] = $event;
  840. }
  841. }
  842. if($period == 'D') $iniAux->addDays(intval($repeatEvery[0]));
  843. if($period == 'W') $iniAux->addWeeks(intval($repeatEvery[0]));
  844. if($period == 'M') $iniAux->addMonths(intval($repeatEvery[0]));
  845. if($period == 'Y') $iniAux->addYears(intval($repeatEvery[0]));
  846. }
  847. break;
  848. case "O":
  849. $endDateArr = explode('-', $endsAt[1]);
  850. $month = intval($endDateArr[1]) + 1 < 10 ? "0" . intval($endDateArr[1]) + 1 : "" . intval($endDateArr[1]) + 1 . "";
  851. $endDateStr = "$endDateArr[2]-$month-$endDateArr[0]";
  852. $endDate = new Carbon($endDateStr, 'America/Mexico_city');
  853. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  854. while($iniAux->lte($lastDay)){
  855. if($period == 'W'){
  856. $weekStart = (new Carbon($iniAux->toDateTimeString(), 'America/Mexico_city'))->subDays($iniAux->dayOfWeek);
  857. for($i = 0; $i < 7; $i++){
  858. $dayName = $weekStart->dayName;
  859. $dayName = strtolower($dayName);
  860. $dayName = substr($dayName, 0, 3);
  861. if($config['repeatOn'][$dayName] && $weekStart->gte($startDate) && $weekStart->lte($endDate)){
  862. if($consultedDay->eq($weekStart)){
  863. $eventsArr[$weekStart->toDateString()][] = $event;
  864. }
  865. }
  866. $weekStart->addDay();
  867. }
  868. }else{
  869. if($iniAux->lte($endDate)){
  870. if($consultedDay->eq($iniAux)){
  871. $eventsArr[$iniAux->toDateString()][] = $event;
  872. }
  873. }
  874. }
  875. if($period == 'D') $iniAux->addDays(intval($repeatEvery[0]));
  876. if($period == 'W') $iniAux->addWeeks(intval($repeatEvery[0]));
  877. if($period == 'M') $iniAux->addMonths(intval($repeatEvery[0]));
  878. if($period == 'Y') $iniAux->addYears(intval($repeatEvery[0]));
  879. }
  880. break;
  881. case "A":
  882. $repeat = intval($endsAt[2]);
  883. $iniAux = new Carbon($startDate->toDateTimeString(), 'America/Mexico_city');
  884. $cont = 0;
  885. while($iniAux->lte($lastDay)){
  886. if($period == 'W'){
  887. $weekStart = (new Carbon($iniAux->toDateTimeString(), 'America/Mexico_city'))->subDays($iniAux->dayOfWeek);
  888. for($i = 0; $i < 7; $i++){
  889. $dayName = $weekStart->dayName;
  890. $dayName = strtolower($dayName);
  891. $dayName = substr($dayName, 0, 3);
  892. if($config['repeatOn'][$dayName] && $weekStart->gte($startDate) && $cont < $repeat){
  893. if($consultedDay->eq($weekStart)){
  894. $eventsArr[$weekStart->toDateString()][] = $event;
  895. }
  896. }
  897. $weekStart->addDay();
  898. }
  899. }else{
  900. if($cont < $repeat){
  901. if($consultedDay->eq($iniAux)){
  902. $eventsArr[$iniAux->toDateString()][] = $event;
  903. }
  904. }
  905. }
  906. if($period == 'D') $iniAux->addDays(intval($repeatEvery[0]));
  907. if($period == 'W') $iniAux->addWeeks(intval($repeatEvery[0]));
  908. if($period == 'M') $iniAux->addMonths(intval($repeatEvery[0]));
  909. if($period == 'Y') $iniAux->addYears(intval($repeatEvery[0]));
  910. $cont++;
  911. }
  912. break;
  913. }
  914. break;
  915. }
  916. }
  917. $eventsF = [];
  918. foreach($eventsArr as $fec => $events){
  919. foreach($events as $event){
  920. $exec = DB::table('S002V01TBEOT')->where([
  921. ['BEOT_NULI', '=', $line],
  922. ['BEOT_IDOT', '=', $event->IDORDEN],
  923. ['BEOT_FEPR', '=', $fec]
  924. ])->first();
  925. if(!is_null($exec)){
  926. $event->ESTADO = $exec->BEOT_TIAC;
  927. }
  928. $eventsF[] = $event;
  929. }
  930. }
  931. $now = $this->functionsController->now();
  932. $nowStr = $now->toDateTimeString();
  933. $actions = DB::getQueryLog();
  934. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  935. $idac = $this->functionsController->registerActivity(
  936. $line,
  937. 'S002V01M10GMPR',
  938. 'S002V01F01COTP',
  939. 'S002V01P03CODI',
  940. 'Consulta',
  941. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los eventos del día $day de $month del $year.",
  942. $idUser,
  943. $nowStr,
  944. 'S002V01S01ORTR'
  945. );
  946. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  947. return $this->responseController->makeResponse(false, 'EXITO.', $eventsF);
  948. }
  949. public function getWorkOrder($idOrder, $idUser, $line){
  950. DB::enableQueryLog();
  951. $idUser = $this->encryptionController->decrypt($idUser);
  952. if(!$idUser){
  953. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  954. }
  955. $usr = DB::table('S002V01TUSUA')->where([
  956. ['USUA_NULI', '=', $line],
  957. ['USUA_IDUS', '=', $idUser],
  958. ])->first();
  959. if(is_null($usr)){
  960. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  961. }
  962. $idOrder = $this->encryptionController->decrypt($idOrder);
  963. if(!$idOrder){
  964. return $this->responseController->makeResponse(true, 'El ID de la orden no está encriptado correctamente.', [], 400);
  965. }
  966. $workOrder = DB::table('S002V01TOTPR')->select([
  967. 'OTPR_IDOT AS IDORDEN',
  968. 'OTPR_DEIN AS DESCRIPCION',
  969. 'OTPR_ININ AS INSTRUCCIONES',
  970. 'OTPR_EQIN AS EQUIPAMIENTO',
  971. 'EQUI_TIPO AS TIPO_EQUIPAMIENTO',
  972. 'EQUI_MODE AS MODELO_EQUIPAMIENTO',
  973. 'EQUI_IDEQ AS ID_EQUIPAMIENTO',
  974. 'OTPR_FIAP AS FECHAINICIO',
  975. 'OTPR_FTAP AS FECHAFINAL',
  976. 'OTPR_SEAN AS ANALISIS',
  977. 'OTPR_TIIN AS TIEMPOINMOESTI',
  978. 'OTPR_CLAS AS CLASIFICACION',
  979. 'OTPR_OPPR AS OPERARIOS',
  980. 'OTPR_DTIN AS DURACIONTOTAL',
  981. 'OTPR_RHRE AS RECURSOS',
  982. 'OTPR_DONE AS DOCUMENTOS',
  983. 'OTPR_RECO AS CONTRATOS',
  984. 'OTPR_ACAS AS ACTIVADOR',
  985. 'ACTI_TIAC AS TIPOACTIVADOR',
  986. 'ACTI_PRIO AS PRIORIDAD',
  987. 'OTPR_ESTA AS ESTADO',
  988. 'OTPR_USRE AS USUARIOREGISTRA',
  989. 'OTPR_FERE AS FECHAREGISTRO',
  990. 'OTPR_USMO AS USUARIOMODIFICA',
  991. 'OTPR_FEMO AS FECHAMODIFICACION',
  992. ])->leftJoin('S002V01TEQUI', 'EQUI_COEQ', '=', 'OTPR_EQIN')
  993. ->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  994. ['OTPR_IDOT', '=', $idOrder],
  995. ['OTPR_NULI', '=', $line],
  996. ])->first();
  997. if(is_null($workOrder)){
  998. return $this->responseController->makeResponse(true, 'La orden de trabajo consultada no existe.', [], 404);
  999. }
  1000. $workOrder->IDORDEN = $this->encryptionController->encrypt($workOrder->IDORDEN);
  1001. $workOrder->EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->EQUIPAMIENTO);
  1002. $workOrder->ACTIVADOR = $this->encryptionController->encrypt($workOrder->ACTIVADOR);
  1003. if(!is_null($workOrder->ID_EQUIPAMIENTO)){
  1004. $workOrder->ID_EQUIPAMIENTO = $this->encryptionController->encrypt($workOrder->ID_EQUIPAMIENTO);
  1005. }
  1006. if(!is_null($workOrder->PRIORIDAD)){
  1007. $workOrder->PRIORIDAD = $this->encryptionController->encrypt($workOrder->PRIORIDAD);
  1008. }
  1009. $workOrder->FECHAFINAL = $workOrder->FECHAFINAL == '0001-01-01 00:00:00' ? null : $workOrder->FECHAFINAL;
  1010. $workOrder->FECHAINICIO = $workOrder->FECHAINICIO == '0001-01-01 00:00:00' ? null : $workOrder->FECHAINICIO;
  1011. $instructionsArr = json_decode($workOrder->INSTRUCCIONES, true);
  1012. foreach($instructionsArr as $key=>$instruction){
  1013. $instruction['ID'] = $this->encryptionController->encrypt($instruction['ID']);
  1014. $instructionsArr[$key] = $instruction;
  1015. }
  1016. $workOrder->INSTRUCCIONES = json_encode($instructionsArr);
  1017. $staffArr = json_decode($workOrder->OPERARIOS, true);
  1018. foreach($staffArr as $key=>$val){
  1019. if($val['TYPE'] == 'EQ'){
  1020. $workTeam = DB::table('S002V01TEQMA')->where([
  1021. ['EQMA_NULI', '=', $line],
  1022. ['EQMA_IDEQ', '=', $val['ID']]
  1023. ])->first();
  1024. $val['NAME'] = $workTeam->EQMA_NOMB . " (" . $val['ID'] . ")";
  1025. $val['SPEC'] = $workTeam->EQMA_ESPE;
  1026. $employees = DB::table('S002V01TPERS')
  1027. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  1028. ->where([
  1029. ['PERS_NULI', '=', $line],
  1030. ['PERS_EQTR', '=', $val['ID']]
  1031. ])->get()->all();
  1032. $staff = [];
  1033. foreach($employees as $employee){
  1034. $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
  1035. $staff[] = [
  1036. 'ID' => $this->encryptionController->encrypt($employee->PERS_IDPE),
  1037. 'NAME' => $employeeName . " (" . $employee->PERS_IDUS . ") (" . $employee->PERS_IDPE . ")",
  1038. 'ESPE' => $employee->PERS_ESPE,
  1039. ];
  1040. }
  1041. $val['PERS'] = $staff;
  1042. }else if($val['TYPE'] == 'SU'){
  1043. $subcontratist = DB::table('S002V01TPESU')->where([
  1044. ['PESU_NULI', '=', $line],
  1045. ['PESU_IDPS', '=', $val['ID']]
  1046. ])->first();
  1047. $val['NAME'] = $subcontratist->PESU_RASO . " (" . $subcontratist->PESU_REFI . ") (" . $val['ID'] . ")";
  1048. $val['SPEC'] = $subcontratist->PESU_ESPE;
  1049. $employees = DB::table('S002V01TPERS')
  1050. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  1051. ->where([
  1052. ['PERS_NULI', '=', $line],
  1053. ['PERS_IDPS', '=', $val['ID']]
  1054. ])->get()->all();
  1055. $staff = [];
  1056. foreach($employees as $employee){
  1057. $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
  1058. $staff[] = [
  1059. 'ID' => $this->encryptionController->encrypt($employee->PERS_IDPE),
  1060. 'NAME' => $employeeName . " (" . $employee->PERS_IDUS . ") (" . $employee->PERS_IDPE . ")",
  1061. 'ESPE' => $employee->PERS_ESPE,
  1062. ];
  1063. }
  1064. $val['PERS'] = $staff;
  1065. }else if($val['TYPE'] == 'EM'){
  1066. $employee = DB::table('S002V01TPERS')
  1067. ->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  1068. ->where([
  1069. ['PERS_NULI', '=', $line],
  1070. ['PERS_IDPE', '=', $val['ID']]
  1071. ])->first();
  1072. $employeeName = $this->functionsController->joinName($employee->USUA_NOMB, $employee->USUA_APPA, $employee->USUA_APMA);
  1073. $val['NAME'] = $employeeName . " (" . $employee->PERS_IDUS . ") (" . $val['ID'] . ")";
  1074. $val['SPEC'] = $employee->PERS_ESPE;
  1075. }
  1076. $val['ID'] = $this->encryptionController->encrypt($val['ID']);
  1077. $staffArr[$key] = $val;
  1078. }
  1079. $workOrder->OPERARIOS = json_encode($staffArr);
  1080. //PENDIENTE REVISAR LOS RECURSOS CON STOCK
  1081. $documentsArr = json_decode($workOrder->DOCUMENTOS, true);
  1082. $documentsFn = [];
  1083. foreach($documentsArr as $document){
  1084. $documentArr = explode('=', $document);
  1085. $codeArr = explode('-', $documentArr[0]);
  1086. $file = DB::table('S002V01TAFAL')->where([
  1087. ['AFAL_NULI', '=', $line],
  1088. ['AFAL_COMO', '=', $codeArr[1]],
  1089. ['AFAL_CLDO', '=', $codeArr[2]],
  1090. ['AFAL_FECR', '=', $codeArr[3]],
  1091. ['AFAL_NUSE', '=', $codeArr[4]],
  1092. ['AFAL_NUVE', '=', $documentArr[1]]
  1093. ])->first();
  1094. $documentsFn[] = [
  1095. 'id' => $this->encryptionController->encrypt($document),
  1096. 'name' => $file->AFAL_NOAR . '.' . $file->AFAL_EXTE,
  1097. 'size' => $file->AFAL_TAMA,
  1098. 'type' => 'Existente'
  1099. ];
  1100. }
  1101. $workOrder->DOCUMENTOS = json_encode($documentsFn);
  1102. if(!is_null($workOrder->ANALISIS)){
  1103. $analysisArr = json_decode($workOrder->ANALISIS, true);
  1104. $teamsConf = $analysisArr['teamsConf'];
  1105. foreach($teamsConf as $key=>$val){
  1106. $idEnc = $this->encryptionController->encrypt($val['ID']);
  1107. $val['ID'] = $idEnc;
  1108. if($val['TYPE'] != 'EM' && !is_null($val['ITEMS'])){
  1109. foreach($val['ITEMS'] as $k0=>$v0){
  1110. $idEmpEnc = $this->encryptionController->encrypt($v0['ID']);
  1111. $v0['ID'] = $idEmpEnc;
  1112. $val['ITEMS'][$k0] = $v0;
  1113. }
  1114. }
  1115. $teamsConf[$key] = $val;
  1116. }
  1117. $analysisArr['teamsConf'] = $teamsConf;
  1118. $workOrder->ANALISIS = json_encode($analysisArr);
  1119. }
  1120. $usrReg = DB::table('S002V01TUSUA')->where([
  1121. ['USUA_NULI', '=', $line],
  1122. ['USUA_IDUS', '=', $workOrder->USUARIOREGISTRA],
  1123. ])->first();
  1124. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  1125. $workOrder->USUARIOREGISTRA = $nameReg . " (" . $workOrder->USUARIOREGISTRA . ")";
  1126. if(!is_null($workOrder->USUARIOMODIFICA)){
  1127. $usrMod = DB::table('S002V01TUSUA')->where([
  1128. ['USUA_NULI', '=', $line],
  1129. ['USUA_IDUS', '=', $workOrder->USUARIOMODIFICA],
  1130. ])->first();
  1131. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA);
  1132. $workOrder->USUARIOMODIFICA = $nameMod . " (" . $workOrder->USUARIOMODIFICA . ")";
  1133. }
  1134. $now = $this->functionsController->now();
  1135. $nowStr = $now->toDateTimeString();
  1136. $actions = DB::getQueryLog();
  1137. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1138. $idac = $this->functionsController->registerActivity(
  1139. $line,
  1140. 'S002V01M10GMPR',
  1141. 'S002V01F01COTP',
  1142. 'S002V01P04COIN',
  1143. 'Consulta',
  1144. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la orden de trabajo #$idOrder.",
  1145. $idUser,
  1146. $nowStr,
  1147. 'S002V01S01ORTR'
  1148. );
  1149. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1150. return $this->responseController->makeResponse(false, 'EXITO.', $workOrder);
  1151. }
  1152. public function executePreventiveWorkOrder(Request $request){
  1153. DB::enableQueryLog();
  1154. $validator = Validator::make($request->all(), [
  1155. 'id_user' => 'required|string',
  1156. 'linea' => 'required|integer',
  1157. 'id_order' => 'required|integer',
  1158. 'execution_date' => 'required|date'
  1159. ]);
  1160. if($validator->fails()){
  1161. return $this->responseController->makeResponse(
  1162. true,
  1163. "Se encontraron uno o más errores.",
  1164. $this->responseController->makeErrors(
  1165. $validator->errors()->messages()
  1166. ),
  1167. 401
  1168. );
  1169. }
  1170. $form = $request->all();
  1171. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1172. if(!$idUser){
  1173. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1174. }
  1175. $usr = DB::table('S002V01TUSUA')->where([
  1176. ['USUA_NULI', '=', $form['linea']],
  1177. ['USUA_IDUS', '=', $idUser]
  1178. ])->first();
  1179. if(is_null($usr)){
  1180. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1181. }
  1182. $workOrder = DB::table('S002V01TOTPR')->where([
  1183. ['OTPR_NULI', '=', $form['linea']],
  1184. ['OTPR_IDOT', '=', $form['id_order']]
  1185. ])->first();
  1186. if(is_null($workOrder)){
  1187. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  1188. }else if($workOrder->OTPR_ESTA != 'A'){
  1189. return $this->responseController->makeResponse(true, 'La orden solicitada no está activa.', [], 401);
  1190. }
  1191. $execDate = new Carbon($form['execution_date']);
  1192. $fecIni = new Carbon($workOrder->OTPR_FIAP);
  1193. if($fecIni->gt($execDate)){
  1194. $tmp = $fecIni->toDateTimeString() . '|' . $execDate->toDateTimeString();
  1195. return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.' . $tmp, [], 400);
  1196. }
  1197. $execDateStr = $execDate->toDateString();
  1198. $execution = DB::table('S002V01TBEOT')->where([
  1199. ['BEOT_NULI', '=', $form['linea']],
  1200. ['BEOT_IDOT', '=', $form['id_order']],
  1201. ['BEOT_FEPR', '=', $execDateStr]
  1202. ])->first();
  1203. if(!is_null($execution)){
  1204. $estatus = $execution->BEOT_TIAC;
  1205. if($estatus == 'Ejecucion'){
  1206. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya fue realizada.", [], 401);
  1207. }else if($estatus == 'Cancelacion'){
  1208. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr fue cancelada.", [], 401);
  1209. }else if($estatus == 'Finalizado'){
  1210. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha finalizado.", [], 401);
  1211. }
  1212. }
  1213. $now = $this->functionsController->now();
  1214. $nowStr = $now->toDateTimeString();
  1215. DB::table('S002V01TBEOT')->insert([
  1216. 'BEOT_NULI' => $form['linea'],
  1217. 'BEOT_IDOT' => $form['id_order'],
  1218. 'BEOT_FEPR' => $execDateStr,
  1219. 'BEOT_TIAC' => 'Ejecucion',
  1220. 'BEOT_FEEJ' => $nowStr,
  1221. 'BEOT_USEJ' => $idUser,
  1222. ]);
  1223. $actions = DB::getQueryLog();
  1224. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1225. $idac = $this->functionsController->registerActivity(
  1226. $form['linea'],
  1227. 'S002V01M10GMPR',
  1228. 'S002V01F02EMOT',
  1229. '-',
  1230. 'Registro',
  1231. "El usuario $name (" . $usr->USUA_IDUS . ") ejecutó la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.",
  1232. $idUser,
  1233. $nowStr,
  1234. 'S002V01S01ORTR'
  1235. );
  1236. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1237. return $this->responseController->makeResponse(false, 'EXITO.');
  1238. }
  1239. public function cancelWorkOrder(Request $request){
  1240. //PENDIENTE REVISAR
  1241. DB::enableQueryLog();
  1242. $validator = Validator::make($request->all(), [
  1243. 'id_user' => 'required|string',
  1244. 'linea' => 'required|integer',
  1245. 'id_order' => 'required|integer',
  1246. 'execution_date' => 'required|date',
  1247. 'observations' => 'required|string',
  1248. ]);
  1249. if($validator->fails()){
  1250. return $this->responseController->makeResponse(
  1251. true,
  1252. "Se encontraron uno o más errores.",
  1253. $this->responseController->makeErrors(
  1254. $validator->errors()->messages()
  1255. ),
  1256. 401
  1257. );
  1258. }
  1259. $form = $request->all();
  1260. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1261. if(!$idUser){
  1262. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1263. }
  1264. $usr = DB::table('S002V01TUSUA')->where([
  1265. ['USUA_NULI', '=', $form['linea']],
  1266. ['USUA_IDUS', '=', $idUser]
  1267. ])->first();
  1268. if(is_null($usr)){
  1269. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1270. }
  1271. $workOrder = DB::table('S002V01TOTPR')->where([
  1272. ['OTPR_NULI', '=', $form['linea']],
  1273. ['OTPR_IDOT', '=', $form['id_order']]
  1274. ])->first();
  1275. if(is_null($workOrder)){
  1276. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  1277. }
  1278. $execDate = new Carbon($form['execution_date']);
  1279. $fecIni = new Carbon($workOrder->OTPR_FIAP);
  1280. if($fecIni->gt($execDate)){
  1281. return $this->responseController->makeResponse(true, 'La fecha de ejecución es menor a la fecha de inicio.', [], 400);
  1282. }
  1283. $execDateStr = $execDate->toDateString();
  1284. $execution = DB::table('S002V01TBEOT')->where([
  1285. ['BEOT_NULI', '=', $form['linea']],
  1286. ['BEOT_IDOT', '=', $form['id_order']],
  1287. ['BEOT_FEPR', '=', $execDateStr]
  1288. ])->first();
  1289. if(!is_null($execution)){
  1290. $estatus = $execution->BEOT_TIAC;
  1291. if($estatus == 'Ejecucion'){
  1292. 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);
  1293. }else if($estatus == 'Finalizado'){
  1294. 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);
  1295. }else if($estatus == 'Cancelacion'){
  1296. return $this->responseController->makeResponse(true, "La ejecución de la orden para la fecha $execDateStr ya ha sido cancelada.", [], 401);
  1297. }
  1298. }
  1299. $now = $this->functionsController->now();
  1300. $nowStr = $now->toDateTimeString();
  1301. DB::table('S002V01TBEOT')->insert([
  1302. 'BEOT_NULI' => $form['linea'],
  1303. 'BEOT_IDOT' => $form['id_order'],
  1304. 'BEOT_FEPR' => $execDateStr,
  1305. 'BEOT_TIAC' => 'Cancelacion',
  1306. 'BEOT_OBSE' => $form['observations'],
  1307. 'BEOT_FEEJ' => $nowStr,
  1308. 'BEOT_USEJ' => $idUser,
  1309. ]);
  1310. $actions = DB::getQueryLog();
  1311. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1312. $idac = $this->functionsController->registerActivity(
  1313. $form['linea'],
  1314. 'S002V01M10GMPR',
  1315. 'S002V01F02EMOT',
  1316. '-',
  1317. 'Registro',
  1318. "El usuario $name (" . $usr->USUA_IDUS . ") canceló la orden de trabajo #$form[id_order] programada para la fecha $execDateStr.",
  1319. $idUser,
  1320. $nowStr,
  1321. 'S002V01S01ORTR'
  1322. );
  1323. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1324. return $this->responseController->makeResponse(false, 'EXITO.');
  1325. }
  1326. public function deleteWorkOrder(Request $request){
  1327. DB::enableQueryLog();
  1328. $validator = Validator::make($request->all(), [
  1329. 'id_user' => 'required|string',
  1330. 'linea' => 'required|integer',
  1331. 'id_order' => 'required|string',
  1332. ]);
  1333. if($validator->fails()){
  1334. return $this->responseController->makeResponse(
  1335. true,
  1336. "Se encontraron uno o más errores.",
  1337. $this->responseController->makeErrors(
  1338. $validator->errors()->messages()
  1339. ),
  1340. 401
  1341. );
  1342. }
  1343. $form = $request->all();
  1344. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1345. if(!$idUser){
  1346. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1347. }
  1348. $usr = DB::table('S002V01TUSUA')->where([
  1349. ['USUA_NULI', '=', $form['linea']],
  1350. ['USUA_IDUS', '=', $idUser]
  1351. ])->first();
  1352. if(is_null($usr)){
  1353. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1354. }
  1355. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  1356. if(!$idOrder){
  1357. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no fue encriptado correctamente.', [], 400);
  1358. }
  1359. $workOrder = DB::table('S002V01TOTPR')->where([
  1360. ['OTPR_NULI', '=', $form['linea']],
  1361. ['OTPR_IDOT', '=', $idOrder]
  1362. ])->first();
  1363. if(is_null($workOrder)){
  1364. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  1365. }else if($workOrder->OTPR_ESTA == 'E'){
  1366. return $this->responseController->makeResponse(true, 'La orden solicitada está eliminada', [], 401);
  1367. }
  1368. $now = $this->functionsController->now();
  1369. $nowStr = $now->toDateTimeString();
  1370. DB::table('S002V01TOTPR')->where([
  1371. ['OTPR_IDOT', '=', $idOrder],
  1372. ['OTPR_NULI', '=', $form['linea']]
  1373. ])->update([
  1374. 'OTPR_ESTA' => 'E',
  1375. 'OTPR_USMO' => $idUser,
  1376. 'OTPR_FEMO' => $nowStr,
  1377. ]);
  1378. $actions = DB::getQueryLog();
  1379. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1380. $idac = $this->functionsController->registerActivity(
  1381. $form['linea'],
  1382. 'S002V01M10GMPR',
  1383. 'S002V01F04EOTP',
  1384. '-',
  1385. 'Eliminación',
  1386. "El usuario $name (" . $usr->USUA_IDUS . ") eliminó la orden de trabajo #$form[id_order].",
  1387. $idUser,
  1388. $nowStr,
  1389. 'S002V01S01ORTR'
  1390. );
  1391. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1392. return $this->responseController->makeResponse(false, 'EXITO.');
  1393. }
  1394. public function updateWorkOrder(Request $request){
  1395. //PENDIENTE ELIMINAR
  1396. DB::enableQueryLog();
  1397. $validator = Validator::make($request->all(), [
  1398. 'id_user' => 'required|string',
  1399. 'linea' => 'required|integer',
  1400. 'id_order' => 'required|integer',
  1401. 'title' => 'required|string',
  1402. 'repeat' => 'required|json',
  1403. 'start_date' => 'required|date',
  1404. 'start_hour' => 'required|string',
  1405. 'inm_time' => 'required|numeric',
  1406. 'description' => 'required|string|max:100',
  1407. 'clasification' => 'required|string|max:50',
  1408. 'priority' => 'required|string|in:1,2,3',
  1409. 'equipment' => 'required|string',
  1410. 'analisis' => 'required|string',
  1411. 'specialties' => 'required|json',
  1412. 'attached' => 'json',
  1413. ]);
  1414. if($validator->fails()){
  1415. return $this->responseController->makeResponse(
  1416. true,
  1417. "Se encontraron uno o más errores.",
  1418. $this->responseController->makeErrors(
  1419. $validator->errors()->messages()
  1420. ),
  1421. 401
  1422. );
  1423. }
  1424. $form = $request->all();
  1425. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1426. if(!$idUser){
  1427. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1428. }
  1429. $usr = DB::table('S002V01TUSUA')->where([
  1430. ['USUA_NULI', '=', $form['linea']],
  1431. ['USUA_IDUS', '=', $idUser]
  1432. ])->first();
  1433. if(is_null($usr)){
  1434. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1435. }
  1436. $workOrder = DB::table('S002V01TOTPR')->where([
  1437. ['OTPR_NULI', '=', $form['linea']],
  1438. ['OTPR_IDOT', '=', $form['id_order']]
  1439. ])->first();
  1440. if(is_null($workOrder)){
  1441. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  1442. }
  1443. $repeArr = json_decode($form['repeat'], true);
  1444. if(empty($repeArr)){
  1445. return $this->responseController->makeResponse(true, 'El JSON de repetición tiene un formato inválido.', [], 400);
  1446. }else if(!array_key_exists('type', $repeArr)){
  1447. return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de repetición.', [], 400);
  1448. }else if(!array_key_exists('config', $repeArr)){
  1449. return $this->responseController->makeResponse(true, 'El campo config no fue enviado en el JSON de repetición.', [], 400);
  1450. }
  1451. $hourArr = explode(' ', $form['start_hour']);
  1452. $timeArr = '';
  1453. if(count($hourArr) < 2){
  1454. return $this->responseController->makeResponse(true, 'La hora de inicio tiene un formato inválido.', [], 400);
  1455. }else if($hourArr[1] == 'PM'){
  1456. $hour = explode(':', $hourArr[0]);
  1457. $h = intval($hour[0]);
  1458. if($h != 12){
  1459. $h = $h + 12;
  1460. }
  1461. $hourStr = "$h:$hour[1]:00";
  1462. $timeArr .= " $hourStr";
  1463. }else if($hourArr[1] == 'AM'){
  1464. $hour = explode(':', $hourArr[0]);
  1465. $h = intval($hour[0]);
  1466. $hStr = $h < 10 ? "0$h" : "$h";
  1467. $hStr .= ":$hour[1]:00";
  1468. $timeArr .= " $hStr";
  1469. }else{
  1470. return $this->responseController->makeResponse(true, 'No se pudo determinar el periodo del horario.', [], 400);
  1471. }
  1472. $specialtiesArr = json_decode($form['specialties'], true);
  1473. if(empty($specialtiesArr)){
  1474. return $this->responseController->makeResponse(true, 'El JSON de especialidades tiene un formato inválido.', [], 400);
  1475. }
  1476. foreach($specialtiesArr as $specialty){
  1477. if(!array_key_exists('specialty', $specialty)){
  1478. return $this->responseController->makeResponse(true, 'El campo specialty no fue enviado en el JSON de especialidad.', [], 400);
  1479. }else if(!array_key_exists('type', $specialty)){
  1480. return $this->responseController->makeResponse(true, 'El campo type no fue enviado en el JSON de especialidad.', [], 400);
  1481. }else if(!array_key_exists('staff', $specialty)){
  1482. return $this->responseController->makeResponse(true, 'El campo staff no fue enviado en el JSON de especialidad.', [], 400);
  1483. }
  1484. }
  1485. $now = $this->functionsController->now();
  1486. $nowStr = $now->toDateTimeString();
  1487. $documents = isset($form['attached']) ? $form['attached'] : null;
  1488. DB::table('S002V01TOTPR')->where([
  1489. ['OTPR_IDOT', '=', $form['id_order']],
  1490. ['OTPR_NULI', '=', $form['linea']],
  1491. ])->update([
  1492. 'OTPR_TIOR' => $form['title'],
  1493. 'OTPR_REPE' => $form['repeat'],
  1494. 'OTPR_FIIN' => $form['start_date'],
  1495. 'OTPR_HIIN' => $timeArr,
  1496. 'OTPR_TIES' => $form['inm_time'],
  1497. 'OTPR_DEIN' => $form['description'],
  1498. 'OTPR_ANIN' => $form['analisis'],
  1499. 'OTPR_CEIN' => $form['equipment'],
  1500. 'OTPR_PERE' => $form['specialties'],
  1501. 'OTPR_CLAS' => $form['clasification'],
  1502. 'OTPR_PRIO' => $form['priority'],
  1503. 'OTPR_DONE' => $documents,
  1504. 'OTPR_USRE' => $idUser,
  1505. 'OTPR_FERE' => $nowStr,
  1506. ]);
  1507. $actions = DB::getQueryLog();
  1508. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1509. $idac = $this->functionsController->registerActivity(
  1510. $form['linea'],
  1511. 'S002V01M10GMPR',
  1512. 'S002V01F01COTP',
  1513. 'S002V01P01ROTR',
  1514. 'Actualización',
  1515. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden de trabajo $form[title] ($form[id_order]).",
  1516. $idUser,
  1517. $nowStr,
  1518. 'S002V01S01ORTR'
  1519. );
  1520. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1521. return $this->responseController->makeResponse(false, 'EXITO.');
  1522. }
  1523. public function geStartedtWorkOrders($idUser, $line){
  1524. //PENDIENTE REVISAR
  1525. DB::enableQueryLog();
  1526. $idUser = $this->encryptionController->decrypt($idUser);
  1527. if(!$idUser){
  1528. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  1529. }
  1530. $usr = DB::table('S002V01TUSUA')->where([
  1531. ['USUA_NULI', '=', $line],
  1532. ['USUA_IDUS', '=', $idUser]
  1533. ])->first();
  1534. if(is_null($usr)){
  1535. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado', [], 404);
  1536. }
  1537. $startedWorkOrders = DB::table('S002V01TBEOT')->select([
  1538. 'BEOT_IDRE AS IDREGISTRO',
  1539. 'BEOT_IDOT AS IDORDEN',
  1540. 'BEOT_FEPR AS FECHAPROGRAMA',
  1541. 'BEOT_FEEJ AS FECHAEJECUCION',
  1542. 'BEOT_USEJ AS USUARIOEJECUCION',
  1543. 'BEOT_TIAC AS ESTADO',
  1544. 'OTPR_TIOR AS TITULOORDEN',
  1545. 'OTPR_HIIN AS HORAPROGRAMA',
  1546. 'OTPR_TIES AS TIEMPOESTIMADO',
  1547. 'OTPR_PRIO AS PRIORIDAD',
  1548. ])->join('S002V01TOTPR', 'OTPR_IDOT', '=', 'BEOT_IDOT')->where([
  1549. ['BEOT_NULI', '=', $line],
  1550. ])->get()->all();
  1551. foreach($startedWorkOrders as $workOrder){
  1552. $usrEje = DB::table('S002V01TUSUA')->where([
  1553. ['USUA_NULI', '=', $line],
  1554. ['USUA_IDUS', '=', $workOrder->USUARIOEJECUCION]
  1555. ])->first();
  1556. $nameEje = $this->functionsController->joinName($usrEje->USUA_NOMB, $usrEje->USUA_APPA, $usrEje->USUA_APMA);
  1557. $workOrder->USUARIOEJECUCION = $nameEje . " (" . $workOrder->USUARIOEJECUCION . ")";
  1558. }
  1559. $now = $this->functionsController->now();
  1560. $nowStr = $now->toDateTimeString();
  1561. $actions = DB::getQueryLog();
  1562. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1563. $idac = $this->functionsController->registerActivity(
  1564. $line,
  1565. 'S002V01M10GMPR',
  1566. 'S002V01F05BEOT',
  1567. 'S002V01P01HOEJ',
  1568. 'Consulta',
  1569. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo en ejecución.",
  1570. $idUser,
  1571. $nowStr,
  1572. 'S002V01S01ORTR'
  1573. );
  1574. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1575. return $this->responseController->makeResponse(false, 'EXITO.', $startedWorkOrders);
  1576. }
  1577. public function endOrderExecution(Request $request){
  1578. DB::enableQueryLog();
  1579. $validator = Validator::make($request->all(), [
  1580. 'id_user' => 'required|string',
  1581. 'linea' => 'required|integer',
  1582. 'id_order' => 'required|integer',
  1583. 'id_reg' => 'required|integer',
  1584. 'observations' => 'required|string|min:50',
  1585. ]);
  1586. if($validator->fails()){
  1587. return $this->responseController->makeResponse(
  1588. true,
  1589. "Se encontraron uno o más errores.",
  1590. $this->responseController->makeErrors(
  1591. $validator->errors()->messages()
  1592. ),
  1593. 401
  1594. );
  1595. }
  1596. $form = $request->all();
  1597. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1598. if(!$idUser){
  1599. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1600. }
  1601. $usr = DB::table('S002V01TUSUA')->where([
  1602. ['USUA_NULI', '=', $form['linea']],
  1603. ['USUA_IDUS', '=', $idUser]
  1604. ])->first();
  1605. if(is_null($usr)){
  1606. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1607. }
  1608. $workOrder = DB::table('S002V01TOTPR')->where([
  1609. ['OTPR_NULI', '=', $form['linea']],
  1610. ['OTPR_IDOT', '=', $form['id_order']]
  1611. ])->first();
  1612. if(is_null($workOrder)){
  1613. return $this->responseController->makeResponse(true, 'La orden solicitada no existe', [], 404);
  1614. }
  1615. $register = DB::table('S002V01TBEOT')->where([
  1616. ['BEOT_NULI', '=', $form['linea']],
  1617. ['BEOT_IDRE', '=', $form['id_reg']],
  1618. ['BEOT_IDOT', '=', $form['id_order']]
  1619. ])->first();
  1620. if(is_null($register)){
  1621. return $this->responseController->makeResponse(true, 'El registro solicitado no existe', [], 404);
  1622. }else if($register->BEOT_TIAC == 'Cancelacion'){
  1623. return $this->responseController->makeResponse(true, 'El registro solicitado fue cancelado', [], 401);
  1624. }else if($register->BEOT_TIAC == 'Finalizado'){
  1625. return $this->responseController->makeResponse(true, 'El registro solicitado ya fue finalizado', [], 401);
  1626. }
  1627. $now = $this->functionsController->now();
  1628. $executionDate = new Carbon($register->BEOT_FEEJ);
  1629. $diff = $now->diffInMilliseconds($executionDate); //Milisegundos
  1630. $diff = $diff / 1000; //Segundos
  1631. $diff = $diff / 60; //Minutos
  1632. $diff = $diff / 60; //Horas
  1633. $nowStr = $now->toDateTimeString();
  1634. DB::table('S002V01TBEOT')->where([
  1635. ['BEOT_NULI', '=', $form['linea']],
  1636. ['BEOT_IDRE', '=', $form['id_reg']],
  1637. ['BEOT_IDOT', '=', $form['id_order']]
  1638. ])->update([
  1639. "BEOT_TIAC" => 'Finalizado',
  1640. "BEOT_DTEJ" => $diff,
  1641. "BEOT_OBSE" => $form['observations'],
  1642. "BEOT_FEFI" => $nowStr,
  1643. "BEOT_USFI" => $idUser,
  1644. ]);
  1645. $actions = DB::getQueryLog();
  1646. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1647. $idac = $this->functionsController->registerActivity(
  1648. $form['linea'],
  1649. 'S002V01M10GMPR',
  1650. 'S002V01F05SEOR',
  1651. '-',
  1652. 'Actualización',
  1653. "El usuario $name (" . $usr->USUA_IDUS . ") finalizó la ejecución del día ". $register->BEOT_FEPR ." de la orden #$form[id_order].",
  1654. $idUser,
  1655. $nowStr,
  1656. 'S002V01S02AOTR'
  1657. );
  1658. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1659. return $this->responseController->makeResponse(false, 'EXITO.');
  1660. }
  1661. public function getExecRegister($date, $idOrder, $idUser, $line){
  1662. DB::enableQueryLog();
  1663. $idUser = $this->encryptionController->decrypt($idUser);
  1664. if(!$idUser){
  1665. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  1666. }
  1667. $usr = DB::table('S002V01TUSUA')->where([
  1668. ['USUA_NULI', '=', $line],
  1669. ['USUA_IDUS', '=', $idUser],
  1670. ])->first();
  1671. if(is_null($usr)){
  1672. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  1673. }
  1674. $workOrder = DB::table('S002V01TOTPR')->where([
  1675. ['OTPR_IDOT', '=', $idOrder],
  1676. ['OTPR_NULI', '=', $line],
  1677. ])->first();
  1678. if(is_null($workOrder)){
  1679. return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404);
  1680. }
  1681. $validDate = $this->functionsController->validDate($date);
  1682. if(!$validDate){
  1683. return $this->responseController->makeResponse(true, 'La fecha enviada tiene un formato inválido.', [], 400);
  1684. }
  1685. $exec = DB::table('S002V01TBEOT')->where([
  1686. ['BEOT_NULI', '=', $line],
  1687. ['BEOT_IDOT', '=', $idOrder],
  1688. ['BEOT_FEPR', '=', $date],
  1689. ])->first();
  1690. $res = [
  1691. 'DESCRIPCION' => $workOrder->OTPR_DEIN,
  1692. 'EQUIPAMIENTO' => $workOrder->OTPR_EQIN,
  1693. 'FECHAINICIO' => $workOrder->OTPR_FIAP,
  1694. 'ESTADODEEJECUCION' => is_null($exec) ? 'Programada' : $exec->BEOT_TIAC,
  1695. 'IDREG' => is_null($exec) ? null : $exec->BEOT_IDRE,
  1696. 'OBSERVACIONES' => is_null($exec) ? null : $exec->BEOT_OBSE,
  1697. ];
  1698. $now = $this->functionsController->now();
  1699. $nowStr = $now->toDateTimeString();
  1700. $actions = DB::getQueryLog();
  1701. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1702. $idac = $this->functionsController->registerActivity(
  1703. $line,
  1704. 'S002V01M10GMPR',
  1705. 'S002V01F08VCPR',
  1706. '-',
  1707. 'Consulta',
  1708. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el estado de la ejecución de la orden #$idOrder para la fecha $date.",
  1709. $idUser,
  1710. $nowStr,
  1711. 'S002V01S02AOTR'
  1712. );
  1713. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  1714. return $this->responseController->makeResponse(false, 'EXITO.', $res);
  1715. }
  1716. public function copyWorkOrder(Request $request){
  1717. DB::enableQueryLog();
  1718. $validator = Validator::make($request->all(), [
  1719. 'id_user' => 'required|string',
  1720. 'linea' => 'required|integer',
  1721. 'id_order' => 'required|string',
  1722. 'equipment' => 'required|string',
  1723. ]);
  1724. if($validator->fails()){
  1725. return $this->responseController->makeResponse(
  1726. true,
  1727. "Se encontraron uno o más errores.",
  1728. $this->responseController->makeErrors(
  1729. $validator->errors()->messages()
  1730. ),
  1731. 401
  1732. );
  1733. }
  1734. $form = $request->all();
  1735. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1736. if(!$idUser){
  1737. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1738. }
  1739. $usr = DB::table('S002V01TUSUA')->where([
  1740. ['USUA_NULI', '=', $form['linea']],
  1741. ['USUA_IDUS', '=', $idUser],
  1742. ])->first();
  1743. if(is_null($usr)){
  1744. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1745. }
  1746. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  1747. if(!$idOrder){
  1748. return $this->responseController->makeResponse(true, 'El ID de la orden que desea copiar no fue encriptado correctamente.', [], 400);
  1749. }
  1750. $workOrder = DB::table('S002V01TOTPR')->where([
  1751. ['OTPR_NULI', '=', $form['linea']],
  1752. ['OTPR_IDOT', '=', $idOrder]
  1753. ])->first();
  1754. if(is_null($workOrder)){
  1755. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  1756. }
  1757. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  1758. if(!$equipmentCode){
  1759. return $this->responseController->makeResponse(true, 'El código del equipamiento no fue encriptado correctamente.', [], 400);
  1760. }
  1761. $equipment = DB::table('S002V01TEQUI')->where([
  1762. ['EQUI_NULI', '=', $form['linea']],
  1763. ['EQUI_COEQ', '=', $equipmentCode],
  1764. ])->first();
  1765. if(is_null($equipment)){
  1766. return $this->responseController->makeResponse(true, 'El equipamiento seleccionado no existe.', [], 404);
  1767. }else if($equipmentCode == $workOrder->OTPR_EQIN){
  1768. return $this->responseController->makeResponse(true, 'El equipo seleccionado es igual al de la orden copiada.', [], 400);
  1769. }
  1770. $now = $this->functionsController->now();
  1771. $nowStr = $now->toDateTimeString();
  1772. $idOrderNew = DB::table('S002V01TOTPR')->insertGetId([
  1773. "OTPR_NULI" => $form['linea'],
  1774. "OTPR_DEIN" => $workOrder->OTPR_DEIN,
  1775. "OTPR_ININ" => $workOrder->OTPR_ININ,
  1776. "OTPR_EQIN" => $equipmentCode,
  1777. "OTPR_FIAP" => $workOrder->OTPR_FIAP,
  1778. "OTPR_FTAP" => $workOrder->OTPR_FTAP,
  1779. "OTPR_SEAN" => $workOrder->OTPR_SEAN,
  1780. "OTPR_TIIN" => $workOrder->OTPR_TIIN,
  1781. "OTPR_OPPR" => $workOrder->OTPR_OPPR,
  1782. "OTPR_DTIN" => $workOrder->OTPR_DTIN,
  1783. "OTPR_RHRE" => $workOrder->OTPR_RHRE,
  1784. "OTPR_DONE" => '[]',
  1785. "OTPR_RECO" => $workOrder->OTPR_RECO,
  1786. "OTPR_ACAS" => $workOrder->OTPR_ACAS,
  1787. "OTPR_CLAS" => $workOrder->OTPR_CLAS,
  1788. "OTPR_ESTA" => 'R',
  1789. "OTPR_USRE" => $idUser,
  1790. "OTPR_FERE" => $nowStr,
  1791. ]);
  1792. $actions = DB::getQueryLog();
  1793. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  1794. $idac = $this->functionsController->registerActivity(
  1795. $form['linea'],
  1796. 'S002V01M10GMPR',
  1797. 'S002V01F06COVE',
  1798. '-',
  1799. 'Registro',
  1800. "El usuario $name (" . $usr->USUA_IDUS . ") copió la orden #$idOrder para el equipamiento $equipmentCode dentro de la orden #$idOrderNew.",
  1801. $idUser,
  1802. $nowStr,
  1803. 'S002V01S01ORTR'
  1804. );
  1805. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  1806. return $this->responseController->makeResponse(false, 'EXITO.');
  1807. }
  1808. public function savePresetWorkOrder(Request $request){
  1809. DB::enableQueryLog();
  1810. $validator = Validator::make($request->all(), [
  1811. 'id_user' => 'required|string',
  1812. 'linea' => 'required|integer',
  1813. 'exists' => 'required|string|in:S,N',
  1814. 'id_order' => 'required_if:exists,=,S|string',
  1815. 'description' => 'required|string',
  1816. 'instructions' => 'required|string',
  1817. 'start_date' => 'required|string',
  1818. 'start_hour' => 'required|string',
  1819. 'end_date' => 'required|string',
  1820. 'end_hour' => 'required|string',
  1821. 'equipment' => 'required|string',
  1822. 'inm_time' => 'required|string',
  1823. 'total_time' => 'required|string',
  1824. 'staff' => 'required|string',
  1825. 'attached' => 'required|string',
  1826. 'activator_type' => 'required|string',
  1827. 'activator' => 'required|string',
  1828. 'clasification' => 'required|string|max:100',
  1829. 'resources' => 'required|json',
  1830. ]);
  1831. if($validator->fails()){
  1832. return $this->responseController->makeResponse(
  1833. true,
  1834. "Se encontraron uno o más errores.",
  1835. $this->responseController->makeErrors(
  1836. $validator->errors()->messages()
  1837. ),
  1838. 401
  1839. );
  1840. }
  1841. $form = $request->all();
  1842. $idUser = $this->encryptionController->decrypt($form['id_user']);
  1843. if(!$idUser){
  1844. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  1845. }
  1846. $usr = DB::table('S002V01TUSUA')->where([
  1847. ['USUA_NULI', '=', $form['linea']],
  1848. ['USUA_IDUS', '=', $idUser],
  1849. ])->first();
  1850. if(is_null($usr)){
  1851. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  1852. }
  1853. $acas = '0';
  1854. if($form['activator'] != '-'){
  1855. $idActivator = $this->encryptionController->decrypt($form['activator']);
  1856. if(!$idActivator){
  1857. return $this->responseController->makeResponse(true, 'El ID del activador seleccionado no fue encriptado correctamente.', [], 400);
  1858. }
  1859. $activator = DB::table('S002V01TACTI')->where([
  1860. ['ACTI_NULI', '=', $form['linea']],
  1861. ['ACTI_IDAC', '=', $idActivator]
  1862. ])->join('S002V01TCONA', 'CONA_IDCO', '=', 'ACTI_CORE')->first();
  1863. if(is_null($activator)){
  1864. return $this->responseController->makeResponse(true, 'El activador seleccionado no está registrado.', [], 404);
  1865. }
  1866. $acas = $idActivator;
  1867. }
  1868. if($form['resources'] != '[]'){
  1869. //Pendiente revisar con stock
  1870. $resources = json_decode($form['resources'], true);
  1871. if(empty($resources)){
  1872. return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
  1873. }
  1874. }
  1875. $startDateTime = '0001-01-01 00:00:00';
  1876. if($form['start_date'] != '-' && $form['start_hour'] != '-'){
  1877. $startDateTime = "$form[start_date] $form[start_hour]";
  1878. $validStartDateTime = $this->functionsController->validateDate($startDateTime);
  1879. if(!$validStartDateTime){
  1880. return $this->responseController->makeResponse(true, 'La fecha u hora de inicio tienen un formato inválido.', [], 400);
  1881. }
  1882. }
  1883. $endDateTime = '0001-01-01 00:00:00';
  1884. if($form['end_date'] != '-' && $form['end_hour'] != '-'){
  1885. $endDateTime = "$form[end_date] $form[end_hour]";
  1886. $validEndDateTime = $this->functionsController->validateDate($endDateTime);
  1887. if(!$validEndDateTime){
  1888. return $this->responseController->makeResponse(true, 'La fecha u hora de término tienen un formato inválido.', [], 400);
  1889. }
  1890. }
  1891. $now = $this->functionsController->now();
  1892. $nowStr = $now->toDateTimeString();
  1893. $dein = $form['description'];
  1894. $eqin = '-';
  1895. if($form['equipment'] != '-'){
  1896. $equipmentCode = $this->encryptionController->decrypt($form['equipment']);
  1897. if(!$equipmentCode){
  1898. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no fue encriptado correctamente.', [], 400);
  1899. }
  1900. $equipment = DB::table('S002V01TEQUI')->where([
  1901. ['EQUI_NULI', '=', $form['linea']],
  1902. ['EQUI_COEQ', '=', $equipmentCode]
  1903. ])->first();
  1904. if(is_null($equipment)){
  1905. return $this->responseController->makeResponse(true, 'El equipaiento seleccionado no existe.', [], 404);
  1906. }
  1907. $eqin = $equipmentCode;
  1908. }
  1909. $tiin = $form['inm_time'] == '-' ? 0 : floatval($form['inm_time']);
  1910. $dtin = $form['total_time'] == '-' ? 0 : floatval($form['total_time']);
  1911. $staff = [];
  1912. if($form['staff'] != '-'){
  1913. $staffArr = json_decode($form['staff'], true);
  1914. foreach($staffArr as $val){
  1915. $typeStr = '';
  1916. if($val['TYPE'] == 'EQ'){
  1917. $typeStr = 'equipo de trabajo';
  1918. }else if($val['TYPE'] == 'SU'){
  1919. $typeStr = 'subcontratista';
  1920. }else if($val['TYPE'] == 'EM'){
  1921. $typeStr = 'empleado';
  1922. }
  1923. $key = $this->encryptionController->decrypt($val['ID']);
  1924. if(!$key){
  1925. return $this->responseController->makeResponse(true, "El ID del $typeStr no fue encriptado correctamente.", [], 400);
  1926. }
  1927. $res = null;
  1928. if($val['TYPE'] == 'EQ'){
  1929. $res = DB::table('S002V01TEQMA')->where([
  1930. ['EQMA_NULI', '=', $form['linea']],
  1931. ['EQMA_IDEQ', '=', $key],
  1932. ])->first();
  1933. }else if($val['TYPE'] == 'SU'){
  1934. $res = DB::table('S002V01TPESU')->where([
  1935. ['PESU_NULI', '=', $form['linea']],
  1936. ['PESU_IDPS', '=', $key],
  1937. ])->first();
  1938. }else if($val['TYPE'] == 'EM'){
  1939. $res = DB::table('S002V01TPERS')->where([
  1940. ['PERS_NULI', '=', $form['linea']],
  1941. ['PERS_IDPE', '=', $key],
  1942. ])->first();
  1943. }
  1944. if(is_null($res)){
  1945. return $this->responseController->makeResponse(true, "El $typeStr no está registrado.", [], 400);
  1946. }
  1947. $staff[] = [
  1948. 'ID' => $key,
  1949. 'TYPE' => $val['TYPE']
  1950. ];
  1951. }
  1952. }
  1953. $oppr = json_encode($staff);
  1954. $done = $form['attached'] == '-' ? null : $form['attached'];
  1955. $clas = $form['clasification'];
  1956. $inin = '[]';
  1957. if($form['instructions'] != '-'){
  1958. $instructions = json_decode($form['instructions'], true);
  1959. foreach($instructions as $key=>$instruction){
  1960. $instruction['ID'] = $this->encryptionController->decrypt($instruction['ID']);
  1961. $instructions[$key] = $instruction;
  1962. }
  1963. $inin = json_encode($instructions);
  1964. }
  1965. if($form['exists'] == 'N'){
  1966. $idOrder = DB::table('S002V01TOTPR')->insertGetId([
  1967. 'OTPR_NULI' => $form['linea'],
  1968. 'OTPR_DEIN' => $dein,
  1969. 'OTPR_ININ' => $inin,
  1970. 'OTPR_EQIN' => $eqin,
  1971. 'OTPR_FIAP' => $startDateTime,
  1972. 'OTPR_FTAP' => $endDateTime,
  1973. 'OTPR_TIIN' => $tiin,
  1974. 'OTPR_OPPR' => $oppr,
  1975. 'OTPR_DTIN' => $dtin,
  1976. 'OTPR_RHRE' => $form['resources'],
  1977. 'OTPR_DONE' => $done,
  1978. 'OTPR_ACAS' => $acas,
  1979. 'OTPR_CLAS' => $clas,
  1980. 'OTPR_ESTA' => 'B',
  1981. 'OTPR_USRE' => $idUser,
  1982. 'OTPR_FERE' => $nowStr,
  1983. ]);
  1984. }else{
  1985. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  1986. if(!$idOrder){
  1987. return $this->responseController->makeResponse(true, 'El ID de la orden no fue encriptado correctamente.', [], 400);
  1988. }
  1989. $order = DB::table('S002V01TOTPR')->where([
  1990. ['OTPR_NULI', '=', $form['linea']],
  1991. ['OTPR_IDOT', '=', $idOrder],
  1992. ])->first();
  1993. if(is_null($order)){
  1994. return $this->responseController->makeResponse(true, 'La orden enviada no existe.', [], 404);
  1995. }
  1996. DB::table('S002V01TOTPR')->where([
  1997. ['OTPR_NULI', '=', $form['linea']],
  1998. ['OTPR_IDOT', '=', $idOrder]
  1999. ])->update([
  2000. 'OTPR_DEIN' => $dein,
  2001. 'OTPR_ININ' => $inin,
  2002. 'OTPR_EQIN' => $eqin,
  2003. 'OTPR_FIAP' => $startDateTime,
  2004. 'OTPR_FTAP' => $endDateTime,
  2005. 'OTPR_TIIN' => $tiin,
  2006. 'OTPR_OPPR' => $oppr,
  2007. 'OTPR_DTIN' => $dtin,
  2008. 'OTPR_RHRE' => $form['resources'],
  2009. 'OTPR_DONE' => $done,
  2010. 'OTPR_ACAS' => $acas,
  2011. 'OTPR_CLAS' => $clas,
  2012. 'OTPR_USMO' => $idUser,
  2013. 'OTPR_FEMO' => $nowStr,
  2014. ]);
  2015. }
  2016. $actions = DB::getQueryLog();
  2017. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2018. $idac = $this->functionsController->registerActivity(
  2019. $form['linea'],
  2020. 'S002V01M10GMPR',
  2021. 'S002V01F01COTP',
  2022. 'S002V01P02ROTP',
  2023. 'Registro',
  2024. "El usuario $name (" . $usr->USUA_IDUS . ") registró un borrador para la orden de trabajo #$idOrder.",
  2025. $idUser,
  2026. $nowStr,
  2027. 'S002V01S01ORTR'
  2028. );
  2029. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2030. return $this->responseController->makeresponse(false, "EXITO");
  2031. }
  2032. public function getActiveOrders($idUser, $line){
  2033. DB::enableQueryLog();
  2034. $idUser = $this->encryptionController->decrypt($idUser);
  2035. if(!$idUser){
  2036. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2037. }
  2038. $usr = DB::table('S002V01TUSUA')->where([
  2039. ['USUA_NULI', '=', $line],
  2040. ['USUA_IDUS', '=', $idUser]
  2041. ])->first();
  2042. if(is_null($usr)){
  2043. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2044. }
  2045. $activeWorkOrders = DB::table('S002V01TOTPR')->select([
  2046. 'OTPR_IDOT AS IDORDEN',
  2047. 'OTPR_EQIN AS EQUIPAMIENTO',
  2048. 'OTPR_FIAP AS FECHAINICIO',
  2049. 'OTPR_FTAP AS FECHATERMINO',
  2050. 'OTPR_TIIN AS TIEMPOESTIMADO',
  2051. 'OTPR_DTIN AS TIEMPOTOTAL',
  2052. 'OTPR_CLAS AS CLASIFICACION',
  2053. 'OTPR_ACAS AS ACTIVADOR',
  2054. 'ACTI_PRIO AS PRIORIDAD',
  2055. 'ACTI_TIAC AS TIPOACTIVADOR'
  2056. ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  2057. ['OTPR_NULI', '=', $line],
  2058. ['OTPR_ESTA', '=', 'A']
  2059. ])->get()->all();
  2060. $now = $this->functionsController->now();
  2061. $nowStr = $now->toDateTimeString();
  2062. $actions = DB::getQueryLog();
  2063. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2064. $idac = $this->functionsController->registerActivity(
  2065. $line,
  2066. 'S002V01M10GMPR',
  2067. 'S002V01F01ACMA',
  2068. 'S002V01P01OTAC',
  2069. 'Consulta',
  2070. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de mantenimiento preventivo activas.",
  2071. $idUser,
  2072. $nowStr,
  2073. 'S002V01S02AOTR'
  2074. );
  2075. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2076. return $this->responseController->makeResponse(false, 'EXITO.', $activeWorkOrders);
  2077. }
  2078. public function getPreventiveCalendar($fecIni, $fecFin, $idUser, $line){
  2079. DB::enableQueryLog();
  2080. $idUser = $this->encryptionController->decrypt($idUser);
  2081. if(!$idUser){
  2082. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2083. }
  2084. $usr = DB::table('S002V01TUSUA')->where([
  2085. ['USUA_NULI', '=', $line],
  2086. ['USUA_IDUS', '=', $idUser],
  2087. ])->first();
  2088. if(is_null($usr)){
  2089. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2090. }
  2091. if(!$this->functionsController->validDate($fecIni)){
  2092. return $this->responseController->makeResponse(true, 'La fecha de inicio es inválida.', [], 400);
  2093. }
  2094. if(!$this->functionsController->validDate($fecFin)){
  2095. return $this->responseController->makeResponse(true, 'La fecha final es inválida.', [], 400);
  2096. }
  2097. $fecIniObj = new Carbon($fecIni . ' 00:00:00');
  2098. $fecFinObj = new Carbon($fecFin . ' 23:59:59');
  2099. $workOrders = DB::table('S002V01TOTPR')->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  2100. ['OTPR_NULI', '=', $line],
  2101. ['OTPR_ESTA', '=', 'A'],
  2102. ])->get()->all();
  2103. $programmedWorkOrders = [];
  2104. foreach($workOrders as $order){
  2105. $orderStart = new Carbon($order->OTPR_FIAP);
  2106. if($order->ACTI_TIAC == 'Calendario' || $order->ACTI_TIAC == 'Sintoma'){
  2107. $repeatConfig = json_decode($order->ACTI_COAC, true);
  2108. switch($repeatConfig['repeat']){
  2109. case 'AN':
  2110. while ($orderStart->lte($fecFinObj)){
  2111. if($orderStart->gte($fecIniObj)){
  2112. $reg = DB::table('S002V01TBEOT')->where([
  2113. ['BEOT_NULI', '=', $line],
  2114. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2115. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2116. ])->first();
  2117. $programmedWorkOrders[] = [
  2118. "IDORDEN" => $order->OTPR_IDOT,
  2119. "EVENTCOLOR" => $repeatConfig['color'],
  2120. "DATE" => $orderStart->toDateString(),
  2121. "TYPE" => $order->ACTI_TIAC,
  2122. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2123. ];
  2124. }
  2125. $orderStart->addYear();
  2126. }
  2127. break;
  2128. case 'ME':
  2129. while ($orderStart->lte($fecFinObj)){
  2130. if($orderStart->gte($fecIniObj)){
  2131. $reg = DB::table('S002V01TBEOT')->where([
  2132. ['BEOT_NULI', '=', $line],
  2133. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2134. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2135. ])->first();
  2136. $programmedWorkOrders[] = [
  2137. "IDORDEN" => $order->OTPR_IDOT,
  2138. "EVENTCOLOR" => $repeatConfig['color'],
  2139. "DATE" => $orderStart->toDateString(),
  2140. "TYPE" => $order->ACTI_TIAC,
  2141. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2142. ];
  2143. }
  2144. $orderStart->addMonth();
  2145. }
  2146. break;
  2147. case 'SE':
  2148. while ($orderStart->lte($fecFinObj)){
  2149. if($orderStart->gte($fecIniObj)){
  2150. $reg = DB::table('S002V01TBEOT')->where([
  2151. ['BEOT_NULI', '=', $line],
  2152. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2153. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2154. ])->first();
  2155. $programmedWorkOrders[] = [
  2156. "IDORDEN" => $order->OTPR_IDOT,
  2157. "EVENTCOLOR" => $repeatConfig['color'],
  2158. "DATE" => $orderStart->toDateString(),
  2159. "TYPE" => $order->ACTI_TIAC,
  2160. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2161. ];
  2162. }
  2163. $orderStart->addWeek();
  2164. }
  2165. break;
  2166. case 'TD':
  2167. while ($orderStart->lte($fecFinObj)){
  2168. if($orderStart->gte($fecIniObj)){
  2169. $reg = DB::table('S002V01TBEOT')->where([
  2170. ['BEOT_NULI', '=', $line],
  2171. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2172. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2173. ])->first();
  2174. $programmedWorkOrders[] = [
  2175. "IDORDEN" => $order->OTPR_IDOT,
  2176. "EVENTCOLOR" => $repeatConfig['color'],
  2177. "DATE" => $orderStart->toDateString(),
  2178. "TYPE" => $order->ACTI_TIAC,
  2179. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2180. ];
  2181. }
  2182. $orderStart->addDay();
  2183. }
  2184. break;
  2185. case 'NR':
  2186. if($orderStart->gte($fecIniObj) && $orderStart->lte($fecFinObj)){
  2187. $reg = DB::table('S002V01TBEOT')->where([
  2188. ['BEOT_NULI', '=', $line],
  2189. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2190. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2191. ])->first();
  2192. $programmedWorkOrders[] = [
  2193. "IDORDEN" => $order->OTPR_IDOT,
  2194. "EVENTCOLOR" => $repeatConfig['color'],
  2195. "DATE" => $orderStart->toDateString(),
  2196. "TYPE" => $order->ACTI_TIAC,
  2197. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2198. ];
  2199. }
  2200. break;
  2201. case 'PE':
  2202. $customRepeat = json_decode($repeatConfig['customRepeat'], true);
  2203. $repeatEvery = explode('|', $customRepeat['repeatEvery']);
  2204. switch($repeatEvery[1]){
  2205. case '0':
  2206. //Repeticiones por día
  2207. $days = intval($repeatEvery[0]);
  2208. while ($orderStart->lte($fecFinObj)){
  2209. if($orderStart->gte($fecIniObj)){
  2210. $reg = DB::table('S002V01TBEOT')->where([
  2211. ['BEOT_NULI', '=', $line],
  2212. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2213. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2214. ])->first();
  2215. $programmedWorkOrders[] = [
  2216. "IDORDEN" => $order->OTPR_IDOT,
  2217. "EVENTCOLOR" => $repeatConfig['color'],
  2218. "DATE" => $orderStart->toDateString(),
  2219. "TYPE" => $order->ACTI_TIAC,
  2220. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2221. ];
  2222. }
  2223. $orderStart->addDays($days);
  2224. }
  2225. break;
  2226. case '1':
  2227. //Repeticiones por semana
  2228. $weeks = intval($repeatEvery[0]);
  2229. $orderStartAux = new Carbon($orderStart->toDateTimeString());
  2230. $repeatOn = $customRepeat['repeatOn'];
  2231. while ($orderStart->lte($fecFinObj)){
  2232. $dayInd = $orderStartAux->dayOfWeek;
  2233. for($i = $dayInd; $i < 7; $i++){
  2234. $dayName = strtolower($orderStartAux->dayName);
  2235. $dayKey = substr($dayName, 0, 3);
  2236. $shouldRepeat = $repeatOn[$dayKey];
  2237. if($shouldRepeat && $orderStartAux->lte($fecFinObj) && $orderStartAux->gte($fecIniObj)){
  2238. $reg = DB::table('S002V01TBEOT')->where([
  2239. ['BEOT_NULI', '=', $line],
  2240. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2241. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2242. ])->first();
  2243. $programmedWorkOrders[] = [
  2244. "IDORDEN" => $order->OTPR_IDOT,
  2245. "EVENTCOLOR" => $repeatConfig['color'],
  2246. "DATE" => $orderStartAux->toDateString(),
  2247. "TYPE" => $order->ACTI_TIAC,
  2248. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2249. ];
  2250. }
  2251. $orderStartAux->addDay();
  2252. }
  2253. $orderStartAux->addWeeks($weeks);
  2254. $orderStart->addWeeks($weeks);
  2255. }
  2256. break;
  2257. case '2':
  2258. //Repeticiones por mes
  2259. $months = intval($repeatEvery[0]);
  2260. while ($orderStart->lte($fecFinObj)){
  2261. if($orderStart->gte($fecIniObj)){
  2262. $reg = DB::table('S002V01TBEOT')->where([
  2263. ['BEOT_NULI', '=', $line],
  2264. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2265. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2266. ])->first();
  2267. $programmedWorkOrders[] = [
  2268. "IDORDEN" => $order->OTPR_IDOT,
  2269. "EVENTCOLOR" => $repeatConfig['color'],
  2270. "DATE" => $orderStart->toDateString(),
  2271. "TYPE" => $order->ACTI_TIAC,
  2272. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2273. ];
  2274. }
  2275. $orderStart->addMonths($months);
  2276. }
  2277. break;
  2278. case '3':
  2279. //Repeticiones por año
  2280. $years = intval($repeatEvery[0]);
  2281. while ($orderStart->lte($fecFinObj)){
  2282. if($orderStart->gte($fecIniObj)){
  2283. $reg = DB::table('S002V01TBEOT')->where([
  2284. ['BEOT_NULI', '=', $line],
  2285. ['BEOT_IDOT', '=', $order->OTPR_IDOT],
  2286. ['BEOT_FEPR', '=', $orderStart->toDateString()]
  2287. ])->first();
  2288. $programmedWorkOrders[] = [
  2289. "IDORDEN" => $order->OTPR_IDOT,
  2290. "EVENTCOLOR" => $repeatConfig['color'],
  2291. "DATE" => $orderStart->toDateString(),
  2292. "TYPE" => $order->ACTI_TIAC,
  2293. "REGEST" => is_null($reg) ? 'Programada' : $reg->BEOT_TIAC,
  2294. ];
  2295. }
  2296. $orderStart->addYears($years);
  2297. }
  2298. break;
  2299. }
  2300. break;
  2301. }
  2302. }
  2303. }
  2304. $now = $this->functionsController->now();
  2305. $nowStr = $now->toDateTimeString();
  2306. $actions = DB::getQueryLog();
  2307. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2308. $idac = $this->functionsController->registerActivity(
  2309. $line,
  2310. 'S002V01M10GMPR',
  2311. 'S002V01F08VCPR',
  2312. '-',
  2313. 'Consulta',
  2314. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los eventos programados entre las fechas $fecIni y $fecFin.",
  2315. $idUser,
  2316. $nowStr,
  2317. 'S002V01S02AOTR'
  2318. );
  2319. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2320. return $this->responseController->makeResponse(false, 'EXITO.', $programmedWorkOrders);
  2321. }
  2322. public function newUnprogrammedOrder(Request $request){
  2323. DB::enableQueryLog();
  2324. $validator = Validator::make($request->all(), [
  2325. 'id_user' => 'required|string',
  2326. 'linea' => 'required|integer',
  2327. 'equipment' => 'required|string',
  2328. 'teams' => 'required|json',
  2329. 'resources' => 'required|json',
  2330. 'comments' => 'required|string|min:35',
  2331. ]);
  2332. if($validator->fails()){
  2333. return $this->responseController->makeResponse(
  2334. true,
  2335. "Se encontraron uno o más errores.",
  2336. $this->responseController->makeErrors(
  2337. $validator->errors()->messages()
  2338. ),
  2339. 401
  2340. );
  2341. }
  2342. $form = $request->all();
  2343. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2344. if(!$idUser){
  2345. return $this->responseController->makeResponse(true, 'El ID de usuario no fue encriptado correctamente.', [], 400);
  2346. }
  2347. $usr = DB::table('S002V01TUSUA')->where([
  2348. ['USUA_NULI', '=', $form['linea']],
  2349. ['USUA_IDUS', '=', $idUser]
  2350. ])->first();
  2351. if(is_null($usr)){
  2352. return $this->responseController->makeResponse(true, 'El usuario que realizó la petición no existe.', [], 404);
  2353. }
  2354. $now = $this->functionsController->now();
  2355. $nowStr = $now->toDateTimeString();
  2356. $teamsArr = json_decode($form['teams'], true);
  2357. if(empty($teamsArr)){
  2358. return $this->responseController->makeResponse(true, 'El JSON de equipos tiene un formato inválido.', [], 400);
  2359. }
  2360. $resources = json_decode($form['resources'], true);
  2361. if(empty($resources)){
  2362. return $this->responseController->makeResponse(true, 'El JSON de recursos tiene un formato inválido.', [], 400);
  2363. }
  2364. $commentsArr = [
  2365. 'CI' => $form['comments']
  2366. ];
  2367. $commentsStr = json_encode($commentsArr);
  2368. $idVisit = DB::table('S002V01TRVTN')->insertGetId([
  2369. 'RVTN_NULI' => $form['linea'],
  2370. 'RVTN_EQRE' => $form['equipment'],
  2371. 'RVTN_PEIN' => $form['teams'],
  2372. 'RVTN_MAUT' => $form['resources'],
  2373. 'RVTN_COME' => $commentsStr,
  2374. 'RVTN_USRE' => $idUser,
  2375. 'RVTN_FERE' => $nowStr,
  2376. ]);
  2377. $actions = DB::getQueryLog();
  2378. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2379. $idac = $this->functionsController->registerActivity(
  2380. $form['linea'],
  2381. 'S002V01M10GMPR',
  2382. 'S002V01F11RVTP',
  2383. 'S002V01P01REVI',
  2384. 'Registro',
  2385. "El usuario $name (" . $usr->USUA_IDUS . ") registró la visita no programada #$idVisit.",
  2386. $idUser,
  2387. $nowStr,
  2388. 'S002V01S02AOTR'
  2389. );
  2390. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2391. return $this->responseController->makeResponse(false, 'EXITO.');
  2392. }
  2393. public function getUnprogrammedVisits($status, $idUser, $line){
  2394. DB::enableQueryLog();
  2395. $idUser = $this->encryptionController->decrypt($idUser);
  2396. if(!$idUser){
  2397. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2398. }
  2399. $usr = DB::table('S002V01TUSUA')->where([
  2400. ['USUA_NULI', '=', $line],
  2401. ['USUA_IDUS', '=', $idUser],
  2402. ])->first();
  2403. if(is_null($usr)){
  2404. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2405. }
  2406. $status = $this->encryptionController->decrypt($status);
  2407. if(!$status){
  2408. return $this->responseController->makeResponse(true, 'El arreglo de estados no está encriptado correctamente.', [], 400);
  2409. }
  2410. $statusArr = json_decode($status, true);
  2411. $whereArr = [
  2412. ['RVTN_NULI', '=', $line],
  2413. ];
  2414. foreach($statusArr as $k=>$v){
  2415. if(!$v){
  2416. $whereArr[] = ['RVTN_ESTA', '!=', $k];
  2417. }
  2418. }
  2419. $visits = DB::table('S002V01TRVTN')->select([
  2420. 'RVTN_IDVI AS IDVISITA',
  2421. 'RVTN_EQRE AS EQUIPAMIENTO',
  2422. 'RVTN_ESTA AS ESTATUS',
  2423. 'RVTN_USRE AS USRREG',
  2424. 'RVTN_FERE AS FECREG',
  2425. 'RVTN_UARE AS USAURE',
  2426. 'RVTN_FARE AS FEAURE',
  2427. 'RVTN_USCA AS USRCAN',
  2428. 'RVTN_FECA AS FECCAN',
  2429. 'RVTN_USFI AS USRFIN',
  2430. 'RVTN_FEFI AS FECFIN',
  2431. 'RVTN_USMO AS USRMOD',
  2432. 'RVTN_FEMO AS FECMOD',
  2433. ])->where($whereArr)->get()->all();
  2434. foreach($visits as $visit){
  2435. $usrReg = DB::table('S002V01TUSUA')->where([
  2436. ['USUA_NULI', '=', $line],
  2437. ['USUA_IDUS', '=', $visit->USRREG]
  2438. ])->first();
  2439. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA);
  2440. $nameReg .= " (" . $visit->USRREG . ")";
  2441. $visit->USRREG = $nameReg;
  2442. }
  2443. $now = $this->functionsController->now();
  2444. $nowStr = $now->toDateTimeString();
  2445. $actions = DB::getQueryLog();
  2446. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2447. $idac = $this->functionsController->registerActivity(
  2448. $line,
  2449. 'S002V01M10GMPR',
  2450. 'S002V01F11RVTP',
  2451. 'S002V01P02COVI',
  2452. 'Consulta',
  2453. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la lista de visitas no programadas.",
  2454. $idUser,
  2455. $nowStr,
  2456. 'S002V01S02AOTR'
  2457. );
  2458. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2459. return $this->responseController->makeResponse(false, 'EXITO.', $visits);
  2460. }
  2461. public function getUnprogrammedVisit($idVisit, $idUser, $line){
  2462. DB::enableQueryLog();
  2463. $idUser = $this->encryptionController->decrypt($idUser);
  2464. if(!$idUser){
  2465. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2466. }
  2467. $usr = DB::table('S002V01TUSUA')->where([
  2468. ['USUA_IDUS', '=', $idUser],
  2469. ['USUA_NULI', '=', $line]
  2470. ])->first();
  2471. if(is_null($usr)){
  2472. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2473. }
  2474. $idVisit = $this->encryptionController->decrypt($idVisit);
  2475. if(!$idVisit){
  2476. return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
  2477. }
  2478. $visit = DB::table('S002V01TRVTN')->select([
  2479. 'RVTN_IDVI AS IDVISITA',
  2480. 'RVTN_EQRE AS EQUIPAMIENTO',
  2481. 'RVTN_PEIN AS PERSONAL',
  2482. 'RVTN_MAUT AS MATERIAL',
  2483. 'RVTN_COME AS COMENTARIOS',
  2484. 'RVTN_ESTA AS ESTADO',
  2485. 'RVTN_USRE AS USRREG',
  2486. 'RVTN_FERE AS FECREG',
  2487. 'RVTN_UARE AS USAURE',
  2488. 'RVTN_FARE AS FEAURE',
  2489. 'RVTN_USCA AS USRCAN',
  2490. 'RVTN_FECA AS FECCAN',
  2491. 'RVTN_USFI AS USUFIN',
  2492. 'RVTN_FEFI AS FECFIN',
  2493. 'RVTN_USMO AS USRMOD',
  2494. 'RVTN_FEMO AS FECMOD',
  2495. ])->where([
  2496. ['RVTN_IDVI', '=', $idVisit],
  2497. ['RVTN_NULI', '=', $line]
  2498. ])->first();
  2499. if(is_null($visit)){
  2500. return $this->responseController->makeResponse(true, 'La visita consultada no existe.', [], 404);
  2501. }
  2502. $usrReg = DB::table('S002V01TUSUA')->where([
  2503. ['USUA_NULI', '=', $line],
  2504. ['USUA_IDUS', '=', $visit->USRREG],
  2505. ])->first();
  2506. $nameReg = $this->functionsController->joinName($usrReg->USUA_NOMB, $usrReg->USUA_APPA, $usrReg->USUA_APMA) . " (" . $visit->USRREG . ")";
  2507. $visit->USRREG = $nameReg;
  2508. if(!is_null($visit->USAURE)){
  2509. $usaure = DB::table('S002V01TUSUA')->where([
  2510. ['USUA_NULI', '=', $line],
  2511. ['USUA_IDUS', '=', $visit->USAURE],
  2512. ])->first();
  2513. $nameUre = $this->functionsController->joinName($usaure->USUA_NOMB, $usaure->USUA_APPA, $usaure->USUA_APMA) . " (" . $visit->USAURE . ")";
  2514. $visit->USAURE = $nameUre;
  2515. }
  2516. if(!is_null($visit->USRCAN)){
  2517. $usrCan = DB::table('S002V01TUSUA')->where([
  2518. ['USUA_NULI', '=', $line],
  2519. ['USUA_IDUS', '=', $visit->USRCAN],
  2520. ])->first();
  2521. $nameCan = $this->functionsController->joinName($usrCan->USUA_NOMB, $usrCan->USUA_APPA, $usrCan->USUA_APMA) . " (" . $visit->USRCAN . ")";
  2522. $visit->USRCAN = $nameCan;
  2523. }
  2524. if(!is_null($visit->USUFIN)){
  2525. $usrFin = DB::table('S002V01TUSUA')->where([
  2526. ['USUA_NULI', '=', $line],
  2527. ['USUA_IDUS', '=', $visit->USUFIN],
  2528. ])->first();
  2529. $nameFin = $this->functionsController->joinName($usrFin->USUA_NOMB, $usrFin->USUA_APPA, $usrFin->USUA_APMA) . " (" . $visit->USUFIN . ")";
  2530. $visit->USUFIN = $nameFin;
  2531. }
  2532. if(!is_null($visit->USRMOD)){
  2533. $usrMod = DB::table('S002V01TUSUA')->where([
  2534. ['USUA_NULI', '=', $line],
  2535. ['USUA_IDUS', '=', $visit->USRMOD],
  2536. ])->first();
  2537. $nameMod = $this->functionsController->joinName($usrMod->USUA_NOMB, $usrMod->USUA_APPA, $usrMod->USUA_APMA) . " (" . $visit->USRMOD . ")";
  2538. $visit->USRMOD = $nameMod;
  2539. }
  2540. $now = $this->functionsController->now();
  2541. $nowStr = $now->toDateTimeString();
  2542. $actions = DB::getQueryLog();
  2543. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2544. $idac = $this->functionsController->registerActivity(
  2545. $line,
  2546. 'S002V01M10GMPR',
  2547. 'S002V01F11RVTP',
  2548. 'S002V01P02COVI',
  2549. 'Consulta',
  2550. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la visita no programada #$idVisit.",
  2551. $idUser,
  2552. $nowStr,
  2553. 'S002V01S02AOTR'
  2554. );
  2555. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  2556. return $this->responseController->makeResponse(false, 'EXITO.', $visit);
  2557. }
  2558. public function updateVisitStatus(Request $request){
  2559. DB::enableQueryLog();
  2560. $validator = Validator::make($request->all(), [
  2561. 'id_user' => 'required|string',
  2562. 'linea' => 'required|integer',
  2563. 'id_visit' => 'required|string',
  2564. 'comments' => 'required|string|min:35',
  2565. 'status' => 'required|string|in:C,R,A,F'
  2566. ]);
  2567. if($validator->fails()){
  2568. return $this->responseController->makeResponse(
  2569. true,
  2570. "Se encontraron uno o más errores.",
  2571. $this->responseController->makeErrors(
  2572. $validator->errors()->messages()
  2573. ),
  2574. 401
  2575. );
  2576. }
  2577. $form = $request->all();
  2578. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2579. if(!$idUser){
  2580. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2581. }
  2582. $usr = DB::table('S002V01TUSUA')->where([
  2583. ['USUA_NULI', '=', $form['linea']],
  2584. ['USUA_IDUS', '=', $idUser],
  2585. ])->first();
  2586. if(is_null($usr)){
  2587. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2588. }
  2589. $idVisit = $this->encryptionController->decrypt($form['id_visit']);
  2590. if(!$idVisit){
  2591. return $this->responseController->makeResponse(true, 'El ID de la visita solicitada no está encriptado correctamente.', [], 400);
  2592. }
  2593. $visit = DB::table('S002V01TRVTN')->where([
  2594. ['RVTN_NULI', '=', $form['linea']],
  2595. ['RVTN_IDVI', '=', $idVisit],
  2596. ])->first();
  2597. $commentsArr = json_decode($visit->RVTN_COME, true);
  2598. $commentsArr["C$form[status]"] = $form['comments'];
  2599. $commentsStr = json_encode($commentsArr);
  2600. $now = $this->functionsController->now();
  2601. $nowStr = $now->toDateTimeString();
  2602. $updateArr = [
  2603. 'RVTN_ESTA' => $form['status'],
  2604. 'RVTN_COME' => $commentsStr,
  2605. 'RVTN_USMO' => $idUser,
  2606. 'RVTN_FEMO' => $nowStr,
  2607. ];
  2608. if($form['status'] == 'A' || $form['status'] == 'R'){
  2609. $updateArr['RVTN_UARE'] = $idUser;
  2610. $updateArr['RVTN_FARE'] = $nowStr;
  2611. }
  2612. if($form['status'] == 'F'){
  2613. $updateArr['RVTN_USFI'] = $idUser;
  2614. $updateArr['RVTN_FEFI'] = $nowStr;
  2615. }
  2616. if($form['status'] == 'C'){
  2617. $updateArr['RVTN_USCA'] = $idUser;
  2618. $updateArr['RVTN_FECA'] = $nowStr;
  2619. }
  2620. DB::table('S002V01TRVTN')->where([
  2621. ['RVTN_NULI', '=', $form['linea']],
  2622. ['RVTN_IDVI', '=', $idVisit],
  2623. ])->update($updateArr);
  2624. $actions = DB::getQueryLog();
  2625. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2626. $idac = $this->functionsController->registerActivity(
  2627. $form['linea'],
  2628. 'S002V01M10GMPR',
  2629. 'S002V01F11RVTP',
  2630. 'S002V01P01REVI',
  2631. 'Actualización',
  2632. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la visita no programada #$idVisit.",
  2633. $idUser,
  2634. $nowStr,
  2635. 'S002V01S02AOTR'
  2636. );
  2637. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2638. return $this->responseController->makeResponse(false, 'EXITO.');
  2639. }
  2640. public function updateOrderStatus(Request $request){
  2641. DB::enableQueryLog();
  2642. $validator = Validator::make($request->all(), [
  2643. 'id_user' => 'required|string',
  2644. 'linea' => 'required|integer',
  2645. 'id_order' => 'required|string',
  2646. 'status' => 'required|string|in:B,R,A,E'
  2647. ]);
  2648. if($validator->fails()){
  2649. return $this->responseController->makeResponse(
  2650. true,
  2651. "Se encontraron uno o más errores.",
  2652. $this->responseController->makeErrors(
  2653. $validator->errors()->messages()
  2654. ),
  2655. 401
  2656. );
  2657. }
  2658. $form = $request->all();
  2659. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2660. if(!$idUser){
  2661. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2662. }
  2663. $usr = DB::table('S002V01TUSUA')->where([
  2664. ['USUA_NULI', '=', $form['linea']],
  2665. ['USUA_IDUS', '=', $idUser],
  2666. ])->first();
  2667. if(is_null($usr)){
  2668. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2669. }
  2670. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  2671. if(!$idOrder){
  2672. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  2673. }
  2674. $order = DB::table('S002V01TOTPR')->where([
  2675. ['OTPR_NULI', '=', $form['linea']],
  2676. ['OTPR_IDOT', '=', $idOrder],
  2677. ])->first();
  2678. if(is_null($order)){
  2679. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  2680. }
  2681. if($form['status'] == 'A' && $order->OTPR_SEAN == null){
  2682. return $this->responseController->makeResponse(true, 'La orden no puede ser aprobada sin la asignación del análisis presupuestario.', [], 401);
  2683. }
  2684. $statusStr = '';
  2685. switch($form['status']){
  2686. case 'B': $statusStr = 'Borrador'; break;
  2687. case 'R': $statusStr = 'Revisión'; break;
  2688. case 'A': $statusStr = 'Aprobado'; break;
  2689. case 'E': $statusStr = 'Eliminado'; break;
  2690. }
  2691. $now = $this->functionsController->now();
  2692. $nowStr = $now->toDateTimeString();
  2693. DB::table('S002V01TOTPR')->where([
  2694. ['OTPR_NULI', '=', $form['linea']],
  2695. ['OTPR_IDOT', '=', $idOrder],
  2696. ])->update([
  2697. 'OTPR_ESTA' => $form['status'],
  2698. 'OTPR_USMO' => $idUser,
  2699. 'OTPR_FEMO' => $nowStr
  2700. ]);
  2701. $actions = DB::getQueryLog();
  2702. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2703. $idac = $this->functionsController->registerActivity(
  2704. $form['linea'],
  2705. 'S002V01M10GMPR',
  2706. 'S002V01F01COTP',
  2707. 'S002V01P01HOTP',
  2708. 'Actualización',
  2709. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó el estado de la orden #$idOrder a $statusStr.",
  2710. $idUser,
  2711. $nowStr,
  2712. 'S002V01S01ORTR'
  2713. );
  2714. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2715. return $this->responseController->makeResponse(false, 'EXITO.');
  2716. }
  2717. public function setBudgetAnalysis(Request $request){
  2718. DB::enableQueryLog();
  2719. $validator = Validator::make($request->all(), [
  2720. 'id_user' => 'required|string',
  2721. 'linea' => 'required|integer',
  2722. 'id_order' => 'required|string',
  2723. 'analysis' => 'required|json'
  2724. ]);
  2725. if($validator->fails()){
  2726. return $this->responseController->makeResponse(
  2727. true,
  2728. "Se encontraron uno o más errores.",
  2729. $this->responseController->makeErrors(
  2730. $validator->errors()->messages()
  2731. ),
  2732. 401
  2733. );
  2734. }
  2735. $form = $request->all();
  2736. $idUser = $this->encryptionController->decrypt($form['id_user']);
  2737. if(!$idUser){
  2738. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2739. }
  2740. $usr = DB::table('S002V01TUSUA')->where([
  2741. ['USUA_NULI', '=', $form['linea']],
  2742. ['USUA_IDUS', '=', $idUser],
  2743. ])->first();
  2744. if(is_null($usr)){
  2745. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2746. }
  2747. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  2748. if(!$idOrder){
  2749. return $this->responseController->makeResponse(true, 'El ID de la orden no está encriptado correctamente.', [], 400);
  2750. }
  2751. $order = DB::table('S002V01TOTPR')->where([
  2752. ['OTPR_NULI', '=', $form['linea']],
  2753. ['OTPR_IDOT', '=', $idOrder]
  2754. ])->first();
  2755. if(is_null($order)){
  2756. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  2757. }
  2758. $analysisArr = json_decode($form['analysis'], true);
  2759. if(empty($analysisArr)){
  2760. return $this->responseController->makeResponse(true, 'El JSON de análisis no contiene información.', [], 400);
  2761. }else if(!array_key_exists('teamsConf', $analysisArr)){
  2762. return $this->responseController->makeResponse(true, 'La información de la configuración de los equipos no se envió en el JSON.', [], 400);
  2763. }else if(!is_array($analysisArr['teamsConf'])){
  2764. return $this->responseController->makeResponse(true, 'La configuración de los equipos tiene un formato inválido.', [], 400);
  2765. }
  2766. $teamsConf = $analysisArr['teamsConf'];
  2767. $staffArr = [];
  2768. $contracts = [];
  2769. foreach($teamsConf as $conf){
  2770. $typeKey = substr($conf['TYPE'], 0, 2);
  2771. $idDec = $this->encryptionController->decrypt($conf['ID']);
  2772. if($typeKey == 'EM'){
  2773. $employee = DB::table('S002V01TPERS')->where([
  2774. ['PERS_NULI', '=', $form['linea']],
  2775. ['PERS_IDPE', '=', $idDec],
  2776. ])->first();
  2777. if(is_null($employee)){
  2778. return $this->responseController->makeResponse(true, "El empleado $idDec no existe.", [], 404);
  2779. }
  2780. }else if($typeKey == 'EQ'){
  2781. $workTeam = DB::table('S002V01TEQMA')->where([
  2782. ['EQMA_NULI', '=', $form['linea']],
  2783. ['EQMA_IDEQ', '=', $idDec],
  2784. ])->first();
  2785. if(is_null($workTeam)){
  2786. return $this->responseController->makeResponse(true, "El equipo de trabajo $idDec no existe.", [], 404);
  2787. }
  2788. if(!is_null($conf['ITEMS'])){
  2789. foreach($conf['ITEMS'] as $k=>$item){
  2790. $idEmpDec = $this->encryptionController->decrypt($item['ID']);
  2791. $employee = DB::table('S002V01TPERS')->where([
  2792. ['PERS_NULI', '=', $form['linea']],
  2793. ['PERS_IDPE', '=', $idEmpDec],
  2794. ])->first();
  2795. if(is_null($employee)){
  2796. return $this->responseController->makeResponse(true, "El empleado $idEmpDec no existe.", [], 404);
  2797. }
  2798. $item['ID'] = $idEmpDec;
  2799. $conf['ITEMS'][$k] = $item;
  2800. }
  2801. }
  2802. }else if($typeKey == 'SU'){
  2803. $subcontratist = DB::table('S002V01TPESU')->where([
  2804. ['PESU_NULI', '=', $form['linea']],
  2805. ['PESU_IDPS', '=', $idDec],
  2806. ])->first();
  2807. if(is_null($subcontratist)){
  2808. return $this->responseController->makeResponse(true, "El subcontratista $idDec no existe.", [], 404);
  2809. }
  2810. if(!is_null($conf['ITEMS'])){
  2811. foreach($conf['ITEMS'] as $k=>$item){
  2812. $idEmpDec = $this->encryptionController->decrypt($item['ID']);
  2813. $employee = DB::table('S002V01TPERS')->where([
  2814. ['PERS_NULI', '=', $form['linea']],
  2815. ['PERS_IDPE', '=', $idEmpDec],
  2816. ])->first();
  2817. if(is_null($employee)){
  2818. return $this->responseController->makeResponse(true, "El empleado $idEmpDec no existe.", [], 404);
  2819. }
  2820. $item['ID'] = $idEmpDec;
  2821. $conf['ITEMS'][$k] = $item;
  2822. }
  2823. }
  2824. }else{
  2825. return $this->responseController->makeResponse(true, "El tipo $conf[TYPE] es inválido.", [], 404);
  2826. }
  2827. $conf['ID'] = $idDec;
  2828. $conf['TYPE'] = $typeKey;
  2829. $staffArr[] = $conf;
  2830. }
  2831. $analysisArr['teamsConf'] = $staffArr;
  2832. $now = $this->functionsController->now();
  2833. $nowStr = $now->toDateTimeString();
  2834. $contractsStr = json_encode($contracts);
  2835. $sean = json_encode($analysisArr);
  2836. DB::table('S002V01TOTPR')->where([
  2837. ['OTPR_NULI', '=', $form['linea']],
  2838. ['OTPR_IDOT', '=', $idOrder],
  2839. ])->update([
  2840. 'OTPR_SEAN' => $sean,
  2841. 'OTPR_RECO' => $contractsStr,
  2842. 'OTPR_USMO' => $idUser,
  2843. 'OTPR_FEMO' => $nowStr
  2844. ]);
  2845. $actions = DB::getQueryLog();
  2846. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2847. $idac = $this->functionsController->registerActivity(
  2848. $form['linea'],
  2849. 'S002V01M10GMPR',
  2850. 'S002V01F01COTP',
  2851. 'S002V01P01HOTP',
  2852. 'Actualización',
  2853. "El usuario $name (" . $usr->USUA_IDUS . ") asignó el análisis presupuestario de la orden #$idOrder.",
  2854. $idUser,
  2855. $nowStr,
  2856. 'S002V01S01ORTR'
  2857. );
  2858. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  2859. return $this->responseController->makeResponse(false, 'EXITO.');
  2860. }
  2861. public function getMaintenanceSimulation($idOrder, $idUser, $line){
  2862. DB::enableQueryLog();
  2863. $idUser = $this->encryptionController->decrypt($idUser);
  2864. if(!$idUser){
  2865. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  2866. }
  2867. $usr = DB::table('S002V01TUSUA')->where([
  2868. ['USUA_NULI', '=', $line],
  2869. ['USUA_IDUS', '=', $idUser],
  2870. ])->first();
  2871. if(is_null($usr)){
  2872. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  2873. }
  2874. $idOrder = $this->encryptionController->decrypt($idOrder);
  2875. if(!$idOrder){
  2876. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  2877. }
  2878. $order = DB::table('S002V01TOTPR')->select([
  2879. 'OTPR_IDOT AS IDORDER',
  2880. 'OTPR_DEIN AS DESCRIPCION',
  2881. 'OTPR_ININ AS INSTRUCCIONES',
  2882. 'OTPR_EQIN AS EQUIPAMIENTO',
  2883. 'OTPR_FIAP AS FECHAINICIO',
  2884. 'OTPR_FTAP AS FECHAFINAL',
  2885. 'OTPR_SEAN AS ANALISIS',
  2886. 'OTPR_TIIN AS TIEINMEST',
  2887. 'OTPR_OPPR AS OPERARIOS',
  2888. 'OTPR_DTIN AS TIETOTEST',
  2889. 'OTPR_RHRE AS RECURSOS',
  2890. 'OTPR_ACAS AS ACTIVADOR',
  2891. 'OTPR_ESTA AS ESTADO',
  2892. 'ACTI_PRIO AS PRIORIDAD',
  2893. 'ACTI_TIAC AS TIPOACTIVADOR',
  2894. 'ACTI_COAC AS CONFIGACTI'
  2895. ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  2896. ['OTPR_NULI', '=', $line],
  2897. ['OTPR_IDOT', '=', $idOrder]
  2898. ])->first();
  2899. if(is_null($order)){
  2900. return $this->responseController->makeResponse(true, 'La orden solicitada no existe.', [], 404);
  2901. }else if($order->ESTADO == 'B'){
  2902. return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en borradores.', [], 401);
  2903. }else if($order->ESTADO == 'R'){
  2904. return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque se encuentra en revisión.', [], 401);
  2905. }else if($order->ESTADO == 'E'){
  2906. return $this->responseController->makeResponse(true, 'La orden solicitada no puede ejecutarse porque ha sido eliminado.', [], 401);
  2907. }
  2908. $analisisArr = json_decode($order->ANALISIS, true);
  2909. $teamsConf = $analisisArr['teamsConf'];
  2910. foreach($teamsConf as $key=>$val){
  2911. if($val['TYPE'] == 'EQ'){
  2912. //Obtener información del equipo de trabajo
  2913. $team = DB::table('S002V01TEQMA')->where([
  2914. ['EQMA_IDEQ', '=', $val['ID']],
  2915. ['EQMA_NULI', '=', $line]
  2916. ])->first();
  2917. $val['NAME'] = $team->EQMA_NOMB;
  2918. if($val['ITEMS'] != null){
  2919. foreach($val['ITEMS'] as $key0=>$emp){
  2920. $employee = DB::table('S002V01TPERS')->select([
  2921. 'PERS_IDPE AS IDEMPLEADO',
  2922. 'PERS_IDUS AS IDUSUARIO',
  2923. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'),
  2924. 'PERS_TICO AS TIPOCONTRATO',
  2925. 'PERS_IDPS AS IDSUBCONTRATISTA',
  2926. 'PESU_RASO AS RAZONSOCIAL',
  2927. 'PESU_REFI AS REGIMENFISCAL',
  2928. 'PERS_EQTR AS IDEQUIPO',
  2929. 'EQMA_NOMB AS NOMBREEQUIPO'
  2930. ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  2931. ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  2932. ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([
  2933. ['PERS_NULI', '=', $line],
  2934. ['PERS_IDPE', '=', $emp['ID']],
  2935. ])->first();
  2936. $emp['NAME'] = $employee->NOMBREUSUARIO;
  2937. $emp['IDUS'] = $employee->IDUSUARIO;
  2938. $val['ITEMS'][$key0] = $emp;
  2939. }
  2940. }
  2941. $teamsConf[$key] = $val;
  2942. }else if($val['TYPE'] == 'SU'){
  2943. $subcontratist = DB::table('S002V01TPESU')->where([
  2944. ['PESU_NULI', '=', $line],
  2945. ['PESU_IDPS', '=', $val['ID']],
  2946. ])->first();
  2947. $val['NAME'] = $subcontratist->PESU_RASO;
  2948. if($val['ITEMS'] != null){
  2949. foreach($val['ITEMS'] as $key0=>$emp){
  2950. $employee = DB::table('S002V01TPERS')->select([
  2951. 'PERS_IDPE AS IDEMPLEADO',
  2952. 'PERS_IDUS AS IDUSUARIO',
  2953. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'),
  2954. 'PERS_TICO AS TIPOCONTRATO',
  2955. 'PERS_IDPS AS IDSUBCONTRATISTA',
  2956. 'PESU_RASO AS RAZONSOCIAL',
  2957. 'PESU_REFI AS REGIMENFISCAL',
  2958. 'PERS_EQTR AS IDEQUIPO',
  2959. 'EQMA_NOMB AS NOMBREEQUIPO'
  2960. ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  2961. ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  2962. ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([
  2963. ['PERS_NULI', '=', $line],
  2964. ['PERS_IDPE', '=', $emp['ID']],
  2965. ])->first();
  2966. $emp['NAME'] = $employee->NOMBREUSUARIO;
  2967. $emp['IDUS'] = $employee->IDUSUARIO;
  2968. $val['ITEMS'][$key0] = $emp;
  2969. }
  2970. }
  2971. $teamsConf[$key] = $val;
  2972. }else{
  2973. $employee = DB::table('S002V01TPERS')->select([
  2974. 'PERS_IDPE AS IDEMPLEADO',
  2975. 'PERS_IDUS AS IDUSUARIO',
  2976. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'),
  2977. 'PERS_TICO AS TIPOCONTRATO',
  2978. 'PERS_IDPS AS IDSUBCONTRATISTA',
  2979. 'PESU_RASO AS RAZONSOCIAL',
  2980. 'PESU_REFI AS REGIMENFISCAL',
  2981. 'PERS_EQTR AS IDEQUIPO',
  2982. 'EQMA_NOMB AS NOMBREEQUIPO'
  2983. ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  2984. ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  2985. ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([
  2986. ['PERS_NULI', '=', $line],
  2987. ['PERS_IDPE', '=', $val['ID']],
  2988. ])->first();
  2989. $val['NAME'] = $employee->NOMBREUSUARIO;
  2990. $val['IDUS'] = $employee->IDUSUARIO;
  2991. $teamsConf[$key] = $val;
  2992. }
  2993. }
  2994. $analisisArr['teamsConf'] = $teamsConf;
  2995. $order->ANALISIS = json_encode($analisisArr);
  2996. $actions = DB::getQueryLog();
  2997. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  2998. $now = $this->functionsController->now();
  2999. $nowStr = $now->toDateTimeString();
  3000. $idac = $this->functionsController->registerActivity(
  3001. $line,
  3002. 'S002V01M10GMPR',
  3003. 'S002V01F06SPMA',
  3004. 'S002V01P02VSPM',
  3005. 'Consulta',
  3006. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la simulación de la orden #$idOrder.",
  3007. $idUser,
  3008. $nowStr,
  3009. 'S002V01S02AOTR'
  3010. );
  3011. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3012. return $this->responseController->makeResponse(false, 'EXITO.', $order);
  3013. }
  3014. public function getOrderWithActivator($idOrder, $idUser, $line){
  3015. DB::enableQueryLog();
  3016. $idUser = $this->encryptionController->decrypt($idUser);
  3017. if(!$idUser){
  3018. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3019. }
  3020. $usr = DB::table('S002V01TUSUA')->where([
  3021. ['USUA_NULI', '=', $line],
  3022. ['USUA_IDUS', '=', $idUser],
  3023. ])->first();
  3024. if(is_null($usr)){
  3025. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3026. }
  3027. $idOrder = $this->encryptionController->decrypt($idOrder);
  3028. if(!$idOrder){
  3029. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3030. }
  3031. $order = DB::table('S002V01TOTPR')->select([
  3032. 'OTPR_IDOT AS IDORDEN',
  3033. 'OTPR_DEIN AS DESCRIPCION',
  3034. 'OTPR_ININ AS INSTRUCCIONES',
  3035. 'OTPR_EQIN AS EQUIPAMIENTO',
  3036. 'OTPR_FIAP AS FECHAINICIO',
  3037. 'OTPR_FTAP AS FECHAFINAL',
  3038. 'OTPR_TIIN AS TIEINMEST',
  3039. 'OTPR_DTIN AS TIETOTEST',
  3040. 'OTPR_ACAS AS ACTIVADOR',
  3041. 'OTPR_CLAS AS CLASIFICACION',
  3042. 'OTPR_ESTA AS ESTADO',
  3043. 'ACTI_PRIO AS PRIORIDAD',
  3044. 'ACTI_TIAC AS TIPOACTIVADOR',
  3045. 'ACTI_COAC AS CONFIGACTIVADOR',
  3046. ])->join('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')->where([
  3047. ['OTPR_NULI', '=', $line],
  3048. ['OTPR_IDOT', '=', $idOrder],
  3049. ])->first();
  3050. if(is_null($order)){
  3051. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3052. }
  3053. $now = $this->functionsController->now();
  3054. $nowStr = $now->toDateTimeString();
  3055. $actions = DB::getQueryLog();
  3056. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3057. $idac = $this->functionsController->registerActivity(
  3058. $line,
  3059. 'S002V01M10GMPR',
  3060. 'S002V01F02AFDT',
  3061. 'S002V01P01OTAT',
  3062. 'Consulta',
  3063. "El usuario $name (" . $usr->USUA_IDUS . ") consultó la información de la orden #$idOrder.",
  3064. $idUser,
  3065. $nowStr,
  3066. 'S002V01S02AOTR'
  3067. );
  3068. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3069. return $this->responseController->makeResponse(false, 'EXITO.', $order);
  3070. }
  3071. public function updateOrderWithActivator(Request $request){
  3072. DB::enableQueryLog();
  3073. $validator = Validator::make($request->all(), [
  3074. 'id_user' => 'required|string',
  3075. 'linea' => 'required|integer',
  3076. 'id_order' => 'required|string',
  3077. 'id_activator' => 'required|string',
  3078. 'start_date' => 'required|date',
  3079. 'end_date' => 'required|date',
  3080. 'activator_type' => 'required|string|in:Calendario,Sintoma,Medida,Valor',
  3081. 'priority' => 'required|string|in:1,2,3,4',
  3082. 'config_activator' => 'required|json',
  3083. ]);
  3084. if($validator->fails()){
  3085. return $this->responseController->makeResponse(
  3086. true,
  3087. "Se encontraron uno o más errores.",
  3088. $this->responseController->makeErrors(
  3089. $validator->errors()->messages()
  3090. ),
  3091. 401
  3092. );
  3093. }
  3094. $form = $request->all();
  3095. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3096. if(!$idUser){
  3097. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3098. }
  3099. $usr = DB::table('S002V01TUSUA')->where([
  3100. ['USUA_IDUS', '=', $idUser],
  3101. ['USUA_NULI', '=', $form['linea']],
  3102. ])->first();
  3103. if(is_null($usr)){
  3104. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3105. }
  3106. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  3107. if(!$idOrder){
  3108. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3109. }
  3110. $order = DB::table('S002V01TOTPR')->where([
  3111. ['OTPR_NULI', '=', $form['linea']],
  3112. ['OTPR_IDOT', '=', $idOrder],
  3113. ])->first();
  3114. if(is_null($order)){
  3115. return $this->responseController->makeResponse(true, 'La orden de trabajo solicitada no existe.', [], 404);
  3116. }
  3117. $idActivator = $this->encryptionController->decrypt($form['id_activator']);
  3118. if(!$idActivator){
  3119. return $this->responseController->makeResponse(true, 'El ID del activador solicitado no está encriptado correctamente.', [], 400);
  3120. }
  3121. $activator = DB::table('S002V01TACTI')->where([
  3122. ['ACTI_IDAC', '=', $idActivator],
  3123. ['ACTI_NULI', '=', $form['linea']]
  3124. ])->first();
  3125. if(is_null($activator)){
  3126. return $this->responseController->makeResponse(true, 'El activador solicitado no existe.', [], 404);
  3127. }
  3128. $now = $this->functionsController->now();
  3129. $nowStr = $now->toDateTimeString();
  3130. DB::table('S002V01TOTPR')->where([
  3131. ['OTPR_NULI', '=', $form['linea']],
  3132. ['OTPR_IDOT', '=', $idOrder],
  3133. ])->update([
  3134. 'OTPR_ACAS' => $idActivator,
  3135. 'OTPR_FIAP' => $form['start_date'],
  3136. 'OTPR_FTAP' => $form['end_date'],
  3137. 'OTPR_USMO' => $idUser,
  3138. 'OTPR_FEMO' => $nowStr,
  3139. ]);
  3140. DB::table('S002V01TACTI')->where([
  3141. ['ACTI_IDAC', '=', $idActivator],
  3142. ['ACTI_NULI', '=', $form['linea']]
  3143. ])->update([
  3144. 'ACTI_PRIO' => $form['priority'],
  3145. 'ACTI_TIAC' => $form['activator_type'],
  3146. 'ACTI_COAC' => $form['config_activator'],
  3147. 'ACTI_USMO' => $idUser,
  3148. 'ACTI_FEMO' => $nowStr,
  3149. ]);
  3150. $actions = DB::getQueryLog();
  3151. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3152. $idac = $this->functionsController->registerActivity(
  3153. $form['linea'],
  3154. 'S002V01M10GMPR',
  3155. 'S002V01F02AFDT',
  3156. 'S002V01P02ACAC',
  3157. 'Actualización',
  3158. "El usuario $name (" . $usr->USUA_IDUS . ") actualizó la orden #$idOrder y el activador #$idActivator.",
  3159. $idUser,
  3160. $nowStr,
  3161. 'S002V01S02AOTR'
  3162. );
  3163. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3164. return $this->responseController->makeResponse(false, 'EXITO.');
  3165. }
  3166. public function printOrderSimulation($idOrder, $idUser, $line){
  3167. DB::enableQueryLog();
  3168. $idUser = $this->encryptionController->decrypt($idUser);
  3169. if(!$idUser){
  3170. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3171. }
  3172. $usr = DB::table('S002V01TUSUA')->where([
  3173. ['USUA_NULI', '=', $line],
  3174. ['USUA_IDUS', '=', $idUser],
  3175. ])->first();
  3176. if(is_null($usr)){
  3177. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3178. }
  3179. $idOrder = $this->encryptionController->decrypt($idOrder);
  3180. if(!$idOrder){
  3181. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3182. }
  3183. $order = DB::table('S002V01TOTPR')->where([
  3184. ['OTPR_NULI', '=', $line],
  3185. ['OTPR_IDOT', '=', $idOrder]
  3186. ])->first();
  3187. if(is_null($order)){
  3188. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3189. }
  3190. $simulation = DB::table('S002V01TRESI')->where([
  3191. ['RESI_NULI', '=', $line],
  3192. ['RESI_IDOT', '=', $idOrder]
  3193. ])->first();
  3194. if(is_null($simulation)){
  3195. return $this->responseController->makeResponse(true, "La orden #$idOrder aún no ha sido simulada.", [], 401);
  3196. }
  3197. $content = json_decode($simulation->RESI_CUSI, true);
  3198. $html = "
  3199. <html>
  3200. <head>
  3201. <link href=\"https://fonts.googleapis.com/icon?family=Material+Icons\" rel=\"stylesheet\">
  3202. <style>
  3203. .main-icon-cell{
  3204. width: 50px;
  3205. height: 50px;
  3206. }
  3207. .main-icon-container{
  3208. width: 50px;
  3209. height: 50px;
  3210. border-radius: 64px;
  3211. border-style: solid;
  3212. padding-left: 8px;
  3213. padding-top: 8px;
  3214. border-color: rgba(0, 0, 0, 0.8);
  3215. }
  3216. .icon-container{
  3217. padding-left: 8px;
  3218. width: 42px;
  3219. height: 42px;
  3220. }
  3221. .instruction-font{
  3222. color: rgba(0, 0, 0, 0.8);
  3223. font-size: 24px;
  3224. padding-left: 8px;
  3225. font-weight: 600;
  3226. }
  3227. .space-cell{
  3228. width: 50px;
  3229. }
  3230. </style>
  3231. </head>
  3232. <body>
  3233. <table width=\"100%\">
  3234. ";
  3235. foreach($content as $item){
  3236. $imgContent = file_get_contents("C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\files\\$item[icon].png");
  3237. $imgB64 = "data:image/png;base64, " . base64_encode($imgContent);
  3238. $html .= "
  3239. <tr>
  3240. ";
  3241. if(!$item['isMain']){
  3242. $html .= '<td class="space-cell"></td>';
  3243. }
  3244. $html .= "
  3245. <td class=\"main-icon-cell\">
  3246. <div class=\"
  3247. ";
  3248. if($item['isMain']){
  3249. $html .= 'main-icon-container">';
  3250. }else{
  3251. $html .= 'icon-container ">';
  3252. }
  3253. $html .= "
  3254. <img src=\"$imgB64\" width=\"42\" height=\"42\">
  3255. </div>
  3256. </td>
  3257. <td class=\"instruction-font\" colspan=\"
  3258. ";
  3259. if($item['isMain']){
  3260. $html .= '2';
  3261. }
  3262. $html .= "
  3263. \">$item[label]</td>
  3264. </tr>
  3265. ";
  3266. }
  3267. $html .= "
  3268. </table>
  3269. </body>
  3270. </html>";
  3271. $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\';
  3272. $noar = "simulacion_orden_$idOrder";
  3273. $exte = "pdf";
  3274. $line = intval($line);
  3275. $line = $line < 10 ? "0$line" : "$line";
  3276. $como = "GMPR";
  3277. $cldo = "OR";
  3278. $now = $this->functionsController->now();
  3279. $nowStr = $now->toDateTimeString();
  3280. $nowArr = explode(" ", $nowStr);
  3281. $dateArr = explode("-", $nowArr[0]);
  3282. $year = substr($dateArr[0], 2);
  3283. $fecr = $year . $dateArr[1] .$dateArr[2];
  3284. $sec = DB::table('S002V01TAFAL')->where([
  3285. ['AFAL_NULI', '=', $line],
  3286. ['AFAL_COMO', '=', $como],
  3287. ['AFAL_CLDO', '=', $cldo],
  3288. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3289. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  3290. for($i = strlen($nuse); $i < 6; $i++){
  3291. $nuse = "0$nuse";
  3292. }
  3293. $ver = DB::table('S002V01TAFAL')->where([
  3294. ['AFAL_NULI', '=', $line],
  3295. ['AFAL_COMO', '=', $como],
  3296. ['AFAL_CLDO', '=', $cldo],
  3297. ['AFAL_NOAR', '=', $noar],
  3298. ['AFAL_EXTE', '=', $exte],
  3299. ])->orderBy('AFAL_NUVE', 'desc')->first();
  3300. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  3301. for($i = strlen($nuve); $i < 2; $i++){
  3302. $nuve = "0$nuve";
  3303. }
  3304. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  3305. $dompdf = new Dompdf();
  3306. $dompdf ->loadHtml($html);
  3307. $dompdf->setPaper('A4', 'portrait');
  3308. $dompdf->render();
  3309. $output = $dompdf->output();
  3310. $tempFile = $filePath . $fileName;
  3311. if(!file_exists($tempFile)){
  3312. fopen($tempFile, 'w');
  3313. }
  3314. file_put_contents($tempFile, $output);
  3315. $ubic = Storage::putFile('files', new File($tempFile));
  3316. $ubic = str_replace("/", "\\", $ubic);
  3317. $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
  3318. $tama = filesize($ubic);
  3319. $usac = json_encode([$idUser]);
  3320. unlink($tempFile);
  3321. DB::table('S002V01TAFAL')->insert([
  3322. 'AFAL_NULI' => $line,
  3323. 'AFAL_COMO' => $como,
  3324. 'AFAL_CLDO' => $cldo,
  3325. 'AFAL_FECR' => $fecr,
  3326. 'AFAL_NUSE' => $nuse,
  3327. 'AFAL_NUVE' => $nuve,
  3328. 'AFAL_NOAR' => $noar,
  3329. 'AFAL_EXTE' => $exte,
  3330. 'AFAL_TAMA' => $tama,
  3331. 'AFAL_UBIC' => $ubic,
  3332. 'AFAL_USAC' => $usac,
  3333. 'AFAL_USRE' => $idUser,
  3334. 'AFAL_FERE' => $nowStr,
  3335. ]);
  3336. $filesArr = json_decode($order->OTPR_DONE, true);
  3337. $filesArr[] = $fileName;
  3338. $filesStr = json_encode($filesArr);
  3339. DB::table('S002V01TOTPR')->where([
  3340. ['OTPR_NULI', '=', $line],
  3341. ['OTPR_IDOT', '=', $idOrder]
  3342. ])->update([
  3343. 'OTPR_DONE' => $filesStr,
  3344. 'OTPR_USMO' => $idUser,
  3345. 'OTPR_FEMO' => $nowStr
  3346. ]);
  3347. $actions = DB::getQueryLog();
  3348. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3349. $idac = $this->functionsController->registerActivity(
  3350. $line,
  3351. 'S002V01M10GMPR',
  3352. 'S002V01F06SPMA',
  3353. 'S002V01P02VSPM',
  3354. 'Registro',
  3355. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.",
  3356. $idUser,
  3357. $nowStr,
  3358. 'S002V01S02AOTR'
  3359. );
  3360. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3361. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  3362. }
  3363. public function saveOrderSimulation(Request $request){
  3364. DB::enableQueryLog();
  3365. $validator = Validator::make($request->all(), [
  3366. 'id_user' => 'required|string',
  3367. 'linea' => 'required|integer',
  3368. 'id_order' => 'required|string',
  3369. 'content' => 'required|json',
  3370. ]);
  3371. if($validator->fails()){
  3372. return $this->responseController->makeResponse(
  3373. true,
  3374. "Se encontraron uno o más errores.",
  3375. $this->responseController->makeErrors(
  3376. $validator->errors()->messages()
  3377. ),
  3378. 401
  3379. );
  3380. }
  3381. $form = $request->all();
  3382. $idUser = $this->encryptionController->decrypt($form['id_user']);
  3383. if(!$idUser){
  3384. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3385. }
  3386. $usr = DB::table('S002V01TUSUA')->where([
  3387. ['USUA_NULI', '=', $form['linea']],
  3388. ['USUA_IDUS', '=', $idUser],
  3389. ])->first();
  3390. if(is_null($usr)){
  3391. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3392. }
  3393. $idOrder = $this->encryptionController->decrypt($form['id_order']);
  3394. if(!$idOrder){
  3395. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3396. }
  3397. $order = DB::table('S002V01TOTPR')->where([
  3398. ['OTPR_NULI', '=', $form['linea']],
  3399. ['OTPR_IDOT', '=', $idOrder],
  3400. ])->first();
  3401. if(is_null($order)){
  3402. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  3403. }
  3404. $simulation = DB::table('S002V01TRESI')->where([
  3405. ['RESI_NULI', '=', $form['linea']],
  3406. ['RESI_IDOT', '=', $idOrder],
  3407. ])->first();
  3408. $now = $this->functionsController->now();
  3409. $nowStr = $now->toDateTimeString();
  3410. if(is_null($simulation)){
  3411. DB::table('S002V01TRESI')->insert([
  3412. 'RESI_NULI' => $form['linea'],
  3413. 'RESI_IDOT' => $idOrder,
  3414. 'RESI_CUSI' => $form['content'],
  3415. 'RESI_FUSI' => $nowStr,
  3416. 'RESI_UUSI' => $idUser,
  3417. ]);
  3418. }else{
  3419. $timestamp = $now->timestamp;
  3420. $history = $simulation->RESI_HISI == null ? [] : json_decode($simulation->RESI_HISI, true);
  3421. $history[$timestamp] = [
  3422. 'USUARIO' => $simulation->RESI_UUSI,
  3423. 'FECHA' => $simulation->RESI_FUSI,
  3424. 'CONTENIDO' => $simulation->RESI_CUSI,
  3425. ];
  3426. $historyStr = json_encode($history);
  3427. DB::table('S002V01TRESI')->where([
  3428. ['RESI_NULI', '=', $form['linea']],
  3429. ['RESI_IDOT', '=', $idOrder],
  3430. ])->update([
  3431. 'RESI_CUSI' => $form['content'],
  3432. 'RESI_FUSI' => $nowStr,
  3433. 'RESI_UUSI' => $idUser,
  3434. 'RESI_HISI' => $historyStr,
  3435. ]);
  3436. }
  3437. $actions = DB::getQueryLog();
  3438. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3439. $idac = $this->functionsController->registerActivity(
  3440. $form['linea'],
  3441. 'S002V01M10GMPR',
  3442. 'S002V01F06SPMA',
  3443. 'S002V01P02VSPM',
  3444. 'Registro',
  3445. "El usuario $name (" . $usr->USUA_IDUS . ") registró una simulación para la orden #$idOrder.",
  3446. $idUser,
  3447. $nowStr,
  3448. 'S002V01S02AOTR'
  3449. );
  3450. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $form['linea']);
  3451. return $this->responseController->makeResponse(false, 'EXITO.');
  3452. }
  3453. public function printOrderDetails($idOrder, $idUser, $line){
  3454. DB::enableQueryLog();
  3455. $idUser = $this->encryptionController->decrypt($idUser);
  3456. if(!$idUser){
  3457. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3458. }
  3459. $usr = DB::table('S002V01TUSUA')->where([
  3460. ['USUA_NULI', '=', $line],
  3461. ['USUA_IDUS', '=', $idUser]
  3462. ])->first();
  3463. if(is_null($usr)){
  3464. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3465. }
  3466. $idOrder = $this->encryptionController->decrypt($idOrder);
  3467. if(!$idOrder){
  3468. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3469. }
  3470. $order = DB::table('S002V01TOTPR')->join(
  3471. 'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC',
  3472. )->where([
  3473. ['OTPR_NULI', '=', $line],
  3474. ['OTPR_IDOT', '=', $idOrder]
  3475. ])->first();
  3476. if(is_null($order)){
  3477. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3478. }
  3479. $html = "
  3480. <html>
  3481. <head>
  3482. <style>
  3483. table{
  3484. border-collapse: separate;
  3485. border-spacing: 0;
  3486. width: 100%;
  3487. }
  3488. .cell-title{
  3489. font-size: 12px;
  3490. font-weight: bold;
  3491. padding: 8px 8px 4px 8px;
  3492. }
  3493. .top-corners-radius{
  3494. border-radius: 4px 4px 0 0;
  3495. }
  3496. .left-bottom-corner-radius{
  3497. border-radius: 0 0 0 4px;
  3498. }
  3499. .right-bottom-corner-radius{
  3500. border-radius: 0 0 4px 0;
  3501. }
  3502. .cell-content{
  3503. padding: 4px 8px 8px 8px;
  3504. font-size: 16px;
  3505. color: rgba(0, 0, 0, 0.7);
  3506. }
  3507. .border-top{ border-top: 1px solid #dddddd; }
  3508. .border-left{ border-left: 1px solid #dddddd; }
  3509. .border-right{ border-right: 1px solid #dddddd; }
  3510. .border-bottom{ border-bottom: 1px solid #dddddd; }
  3511. </style>
  3512. </head>
  3513. <body>
  3514. <table>
  3515. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title top-corners-radius border-top border-left border-right\">Descripción</td></tr>
  3516. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">" . $order->OTPR_DEIN . "</td></tr>
  3517. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Instrucciones</td></tr>
  3518. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">
  3519. ";
  3520. $instructions = json_decode($order->OTPR_ININ, true);
  3521. $cont = 1;
  3522. foreach($instructions as $instruction){
  3523. $html .= $cont . ".- " . $instruction['INSTRUCCION'] . "<br>";
  3524. $cont++;
  3525. }
  3526. $startDate = $this->functionsController->formatDateTime($order->OTPR_FIAP);
  3527. $endDate = $this->functionsController->formatDateTime($order->OTPR_FTAP);
  3528. $html .= "
  3529. </td></tr>
  3530. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Equipamiento relacionado</td></tr>
  3531. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">" . $order->OTPR_EQIN . "</td></tr>
  3532. <tr>
  3533. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Fecha y hora de inicio</td>
  3534. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha y hora final</td>
  3535. </tr>
  3536. <tr>
  3537. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right\">$startDate</td>
  3538. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right\">$endDate</td>
  3539. </tr>
  3540. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Análisis presupuestario</td></tr>
  3541. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">
  3542. ";
  3543. $analisis = $order->OTPR_SEAN == null ? 'Sin configuración' : json_decode($order->OTPR_SEAN, true);
  3544. if(gettype($analisis) == 'array'){
  3545. //PENDIENTE
  3546. $teamsConf = $analisis['teamsConf'];
  3547. foreach($teamsConf as $key=>$team){
  3548. /*var_dump($key);
  3549. echo "<br>";*/
  3550. }
  3551. $html .= "
  3552. PENDIENTE
  3553. </td></tr>
  3554. ";
  3555. }else{
  3556. $html .= "
  3557. $analisis
  3558. </td></tr>
  3559. ";
  3560. }
  3561. $html .= "
  3562. <tr>
  3563. <td width=\"33%\" colspan=\"2\" class=\"cell-title border-top border-left border-right\">Clasificación</td>
  3564. <td width=\"34%\" colspan=\"2\" class=\"cell-title border-top border-right\">Duración total estimada</td>
  3565. <td width=\"33%\" colspan=\"2\" class=\"cell-title border-top border-right\">Tiempo de inmovilización estimado</td>
  3566. </tr>
  3567. <tr>
  3568. <td width=\"33%\" colspan=\"2\" class=\"cell-content border-left border-right\">" . $order->OTPR_CLAS . "</td>
  3569. <td width=\"34%\" colspan=\"2\" class=\"cell-content border-right\">" . $order->OTPR_DTIN . " hora(s)</td>
  3570. <td width=\"33%\" colspan=\"2\" class=\"cell-content border-right\">" . $order->OTPR_TIIN . " hora(s)</td>
  3571. </tr>
  3572. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Personal involucrado</td></tr>
  3573. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3574. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Recursos requerido</td></tr>
  3575. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3576. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Documentos requeridos</td></tr>
  3577. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3578. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Contratos requeridos</td></tr>
  3579. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3580. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-title border-top border-left border-right\">Información del activador</td></tr>
  3581. <tr><td width=\"100%\" colspan=\"6\" class=\"cell-content border-left border-right\">PENDIENTE</td></tr>
  3582. <tr>
  3583. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Usuario que registró</td>
  3584. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha de registro</td>
  3585. </tr>
  3586. <tr>
  3587. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right\">PENDIENTE</td>
  3588. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right\">PENDIENTE</td>
  3589. </tr>
  3590. <tr>
  3591. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-left border-right\">Usuario de la última modificación</td>
  3592. <td width=\"50%\" colspan=\"3\" class=\"cell-title border-top border-right\">Fecha de la última modificación</td>
  3593. </tr>
  3594. <tr>
  3595. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-left border-right border-bottom left-bottom-corner-radius\">PENDIENTE</td>
  3596. <td width=\"50%\" colspan=\"3\" class=\"cell-content border-right border-bottom right-bottom-corner-radius\">PENDIENTE</td>
  3597. </tr>
  3598. </table>
  3599. </body>
  3600. </html>
  3601. ";
  3602. $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\';
  3603. $noar = "detalles_orden_$idOrder";
  3604. $exte = "pdf";
  3605. $line = intval($line);
  3606. $line = $line < 10 ? "0$line" : "$line";
  3607. $como = "GMPR";
  3608. $cldo = "OR";
  3609. $now = $this->functionsController->now();
  3610. $nowStr = $now->toDateTimeString();
  3611. $nowArr = explode(" ", $nowStr);
  3612. $dateArr = explode("-", $nowArr[0]);
  3613. $year = substr($dateArr[0], 2);
  3614. $fecr = $year . $dateArr[1] .$dateArr[2];
  3615. $sec = DB::table('S002V01TAFAL')->where([
  3616. ['AFAL_NULI', '=', $line],
  3617. ['AFAL_COMO', '=', $como],
  3618. ['AFAL_CLDO', '=', $cldo],
  3619. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3620. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  3621. for($i = strlen($nuse); $i < 6; $i++){
  3622. $nuse = "0$nuse";
  3623. }
  3624. $ver = DB::table('S002V01TAFAL')->where([
  3625. ['AFAL_NULI', '=', $line],
  3626. ['AFAL_COMO', '=', $como],
  3627. ['AFAL_CLDO', '=', $cldo],
  3628. ['AFAL_NOAR', '=', $noar],
  3629. ['AFAL_EXTE', '=', $exte],
  3630. ])->orderBy('AFAL_NUVE', 'desc')->first();
  3631. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  3632. for($i = strlen($nuve); $i < 2; $i++){
  3633. $nuve = "0$nuve";
  3634. }
  3635. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  3636. $dompdf = new Dompdf();
  3637. $dompdf->loadHtml($html);
  3638. $dompdf->setPaper('A4', 'portrait');
  3639. $dompdf->render();
  3640. $output = $dompdf->output();
  3641. $tempFile = $filePath . $fileName;
  3642. if(!file_exists($tempFile)){
  3643. fopen($tempFile, 'w');
  3644. }
  3645. file_put_contents($tempFile, $output);
  3646. $ubic = Storage::putFile('files', new File($tempFile));
  3647. $ubic = str_replace("/", "\\", $ubic);
  3648. $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
  3649. $tama = filesize($ubic);
  3650. $usac = json_encode([$idUser]);
  3651. unlink($tempFile);
  3652. DB::table('S002V01TAFAL')->insert([
  3653. 'AFAL_NULI' => $line,
  3654. 'AFAL_COMO' => $como,
  3655. 'AFAL_CLDO' => $cldo,
  3656. 'AFAL_FECR' => $fecr,
  3657. 'AFAL_NUSE' => $nuse,
  3658. 'AFAL_NUVE' => $nuve,
  3659. 'AFAL_NOAR' => $noar,
  3660. 'AFAL_EXTE' => $exte,
  3661. 'AFAL_TAMA' => $tama,
  3662. 'AFAL_UBIC' => $ubic,
  3663. 'AFAL_USAC' => $usac,
  3664. 'AFAL_USRE' => $idUser,
  3665. 'AFAL_FERE' => $nowStr,
  3666. ]);
  3667. $filesArr = json_decode($order->OTPR_DONE, true);
  3668. $filesArr[] = $fileName;
  3669. $filesStr = json_encode($filesArr);
  3670. DB::table('S002V01TOTPR')->where([
  3671. ['OTPR_NULI', '=', $line],
  3672. ['OTPR_IDOT', '=', $idOrder]
  3673. ])->update([
  3674. 'OTPR_DONE' => $filesStr,
  3675. 'OTPR_USMO' => $idUser,
  3676. 'OTPR_FEMO' => $nowStr
  3677. ]);
  3678. $actions = DB::getQueryLog();
  3679. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3680. $idac = $this->functionsController->registerActivity(
  3681. $line,
  3682. 'S002V01M10GMPR',
  3683. 'S002V01F06SPMA',
  3684. 'S002V01P02VSPM',
  3685. 'Registro',
  3686. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de simulación de la orden #$idOrder.",
  3687. $idUser,
  3688. $nowStr,
  3689. 'S002V01S02AOTR'
  3690. );
  3691. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3692. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  3693. }
  3694. public function extractMaintenancePlan($idOrder, $idUser, $line) {
  3695. DB::enableQueryLog();
  3696. $idUser = $this->encryptionController->decrypt($idUser);
  3697. if(!$idUser){
  3698. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3699. }
  3700. $usr = DB::table('S002V01TUSUA')->where([
  3701. ['USUA_NULI', '=', $line],
  3702. ['USUA_IDUS', '=', $idUser],
  3703. ])->first();
  3704. if(is_null($usr)){
  3705. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3706. }
  3707. $idOrder = $this->encryptionController->decrypt($idOrder);
  3708. if(!$idOrder){
  3709. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  3710. }
  3711. $order = DB::table('S002V01TOTPR')->join(
  3712. 'S002V01TACTI', 'OTPR_ACAS', '=', 'ACTI_IDAC',
  3713. )->where([
  3714. ['OTPR_NULI', '=', $line],
  3715. ['OTPR_IDOT', '=', $idOrder]
  3716. ])->first();
  3717. if(is_null($order)){
  3718. return $this->responseController->makeResponse(true, 'La orden solicitada no está registrada.', [], 404);
  3719. }
  3720. $html = file_get_contents($this->templatesUbic . "01-GMPR-PL-010101-000003=01=PDF_PLAN_MANTENIMIENTO.html");
  3721. $logo = file_get_contents("C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\public\global_resources\sam-short-logo.png");
  3722. $logoStr = "data:image/svg+xml;base64," . base64_encode($logo);
  3723. $html = str_replace("%stcImage%", $logoStr, $html);
  3724. $now = $this->functionsController->now();
  3725. $nowStr = $now->toDateTimeString();
  3726. $currentDate = $this->functionsController->buildHumanCurrentDate($nowStr);
  3727. $html = str_replace("%currentDate%", $currentDate, $html);
  3728. $html = str_replace("%idOrder%", $order->OTPR_IDOT, $html);
  3729. $startDateTimeArr = explode(" ", $order->OTPR_FIAP);
  3730. $startTimeArr = explode(":", $startDateTimeArr[1]);
  3731. $startHour = intval($startTimeArr[0]);
  3732. $startPeriod = $startHour < 12 ? 'AM' : 'PM';
  3733. $startHour = $startHour > 12 ? $startHour - 12 : $startHour;
  3734. $startTimeStr = "$startHour:$startTimeArr[1] $startPeriod";
  3735. $html = str_replace("%startTime%", $startTimeStr, $html);
  3736. $startDateTimeObj = new Carbon($order->OTPR_FIAP);
  3737. $totalDuration = floatval($order->OTPR_DTIN);
  3738. $totalDurationHours = intval($totalDuration);
  3739. $startDateTimeObj->addHours($totalDuration);
  3740. $totalDurationFloatMinutes = $this->functionsController->floatSub($totalDuration, $totalDurationHours);
  3741. $totalDurationFloatMinutes = $this->functionsController->floatMul($totalDurationFloatMinutes, 60);
  3742. $totalDurationMinutes = ceil($totalDurationFloatMinutes);
  3743. $startDateTimeObj->addMinutes($totalDurationMinutes);
  3744. $endDateTimeArr = explode(" ", $startDateTimeObj->toDateTimeString());
  3745. $endTimeArr = explode(":", $endDateTimeArr[1]);
  3746. $endHour = intval($endTimeArr[0]);
  3747. $endPeriod = $startHour < 12 ? 'AM' : 'PM';
  3748. $endHour = $endHour > 12 ? $endHour - 12 : $endHour;
  3749. $endTimeStr = "$endHour:$endTimeArr[1] $endPeriod";
  3750. $html = str_replace("%endTime%", $endTimeStr, $html);
  3751. $html = str_replace("%inmTime%", $order->OTPR_TIIN . " h", $html);
  3752. $html = str_replace("%totalTime%", $order->OTPR_DTIN . " h", $html);
  3753. $html = str_replace("%equipment%", $order->OTPR_EQIN, $html);
  3754. $html = str_replace("%description%", $order->OTPR_DEIN, $html);
  3755. $instructions = json_decode($order->OTPR_ININ, true);
  3756. $activitiesTableBody = "";
  3757. foreach($instructions as $k=>$v){
  3758. $key = $k + 1;
  3759. $activitiesTableBody .= "<tr>";
  3760. $activitiesTableBody .= "<td>$key</td>";
  3761. $activitiesTableBody .= "<td>$v[INSTRUCCION]</td>";
  3762. $activitiesTableBody .= "<td>";
  3763. /*foreach($v['ESPECIALIDADES'] as $v0){
  3764. /*$team = array_filter($teams, function($v1) use ($v0) {
  3765. return ($v1['ID'] == $v0);
  3766. });
  3767. $activitiesTableBody .= /*end($team)['ESP'] '--' . "<br>";
  3768. }*/
  3769. $activitiesTableBody .= "</td>";
  3770. $activitiesTableBody .= "</tr>";
  3771. }
  3772. $html = str_replace("%activitiesTableBody%", $activitiesTableBody, $html);
  3773. $personalArr = json_decode($order->OTPR_OPPR, true);
  3774. $constConf = json_decode($order->OTPR_SEAN, true);
  3775. $cont = 1;
  3776. $specialtiesTableBody = "";
  3777. foreach($personalArr as $k=>$v){
  3778. /*$team = array_filter($teams, function($v1) use ($k) {
  3779. return ($v1['ID'] == $k);
  3780. });*/
  3781. $specialtiesTableBody .= "<tr>";
  3782. $specialtiesTableBody .= "<td>$cont</td>";
  3783. $specialtiesTableBody .= "<td>" . /*end($team)['ESP']*/ '--' . "</td>";
  3784. $specialtiesTableBody .= "<td>";
  3785. foreach($constConf['teamsConf'][$k] as $v0){
  3786. $usrID = '-';//$v0['USER'];
  3787. $usrInv = DB::table('S002V01TUSUA')->where([
  3788. ['USUA_NULI', '=', $line],
  3789. ['USUA_IDUS', '=', $usrID],
  3790. ])->first();
  3791. $invName = /*$this->functionsController->joinName($usrInv->USUA_NOMB, $usrInv->USUA_APPA, $usrInv->USUA_APMA) . " ($usrID)"*/ '-';
  3792. $specialtiesTableBody .= $invName . "<br>";
  3793. }
  3794. $specialtiesTableBody .= "</td>";
  3795. $specialtiesTableBody .= "</tr>";
  3796. $cont++;
  3797. }
  3798. $html = str_replace("%specialtiesTableBody%", $specialtiesTableBody, $html);
  3799. $como = 'GMPR';
  3800. $cldo = 'OR';
  3801. $noar = "plan_de_mantenimiento_preventivo_orden_$idOrder";
  3802. $exte = "pdf";
  3803. $line = $line < 10 ? "0$line" : "$line";
  3804. $nowArr = explode(" ", $nowStr);
  3805. $dateArr = explode("-", $nowArr[0]);
  3806. $year = substr($dateArr[0], 2);
  3807. $fecr = $year . $dateArr[1] .$dateArr[2];
  3808. $sec = DB::table('S002V01TAFAL')->where([
  3809. ['AFAL_NULI', '=', $line],
  3810. ['AFAL_COMO', '=', $como],
  3811. ['AFAL_CLDO', '=', $cldo],
  3812. ])->orderBy('AFAL_NUSE', 'desc')->first();
  3813. $nuse = is_null($sec) ? "1" : "" . intval($sec->AFAL_NUSE) + 1 . "";
  3814. for($i = strlen($nuse); $i < 6; $i++){
  3815. $nuse = "0$nuse";
  3816. }
  3817. $ver = DB::table('S002V01TAFAL')->where([
  3818. ['AFAL_NULI', '=', $line],
  3819. ['AFAL_COMO', '=', $como],
  3820. ['AFAL_CLDO', '=', $cldo],
  3821. ['AFAL_NOAR', '=', $noar],
  3822. ['AFAL_EXTE', '=', $exte],
  3823. ])->orderBy('AFAL_NUVE', 'desc')->first();
  3824. $nuve = is_null($ver) ? "1" : "" . intval($ver->AFAL_NUVE) + 1 . "";
  3825. for($i = strlen($nuve); $i < 2; $i++){
  3826. $nuve = "0$nuve";
  3827. }
  3828. $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\';
  3829. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  3830. $dompdf = new Dompdf();
  3831. $dompdf->loadHtml($html);
  3832. $dompdf->setPaper('A4', 'portrait');
  3833. $dompdf->render();
  3834. $output = $dompdf->output();
  3835. $tempFile = $filePath . $fileName;
  3836. if(!file_exists($tempFile)){
  3837. fopen($tempFile, 'w');
  3838. }
  3839. file_put_contents($tempFile, $output);
  3840. $ubic = Storage::putFile('files', new File($tempFile));
  3841. $ubic = str_replace("/", "\\", $ubic);
  3842. $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
  3843. $tama = filesize($ubic);
  3844. $usac = json_encode([$idUser]);
  3845. unlink($tempFile);
  3846. DB::table('S002V01TAFAL')->insert([
  3847. 'AFAL_NULI' => $line,
  3848. 'AFAL_COMO' => $como,
  3849. 'AFAL_CLDO' => $cldo,
  3850. 'AFAL_FECR' => $fecr,
  3851. 'AFAL_NUSE' => $nuse,
  3852. 'AFAL_NUVE' => $nuve,
  3853. 'AFAL_NOAR' => $noar,
  3854. 'AFAL_EXTE' => $exte,
  3855. 'AFAL_TAMA' => $tama,
  3856. 'AFAL_UBIC' => $ubic,
  3857. 'AFAL_USAC' => $usac,
  3858. 'AFAL_USRE' => $idUser,
  3859. 'AFAL_FERE' => $nowStr,
  3860. ]);
  3861. $filesArr = json_decode($order->OTPR_DONE, true);
  3862. $filesArr[] = $fileName;
  3863. $filesStr = json_encode($filesArr);
  3864. DB::table('S002V01TOTPR')->where([
  3865. ['OTPR_NULI', '=', $line],
  3866. ['OTPR_IDOT', '=', $idOrder]
  3867. ])->update([
  3868. 'OTPR_DONE' => $filesStr,
  3869. 'OTPR_USMO' => $idUser,
  3870. 'OTPR_FEMO' => $nowStr
  3871. ]);
  3872. $actions = DB::getQueryLog();
  3873. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3874. $idac = $this->functionsController->registerActivity(
  3875. $line,
  3876. 'S002V01M10GMPR',
  3877. 'S002V01F07EPMA',
  3878. 'S002V01P02DPMA',
  3879. 'Registro',
  3880. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento de la orden #$idOrder.",
  3881. $idUser,
  3882. $nowStr,
  3883. 'S002V01S02AOTR'
  3884. );
  3885. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  3886. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  3887. }
  3888. public function getMaintenancePlanAnalysis($idFile, $idUser, $line) {
  3889. DB::enableQueryLog();
  3890. $idUser = $this->encryptionController->decrypt($idUser);
  3891. if(!$idUser){
  3892. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  3893. }
  3894. $usr = DB::table('S002V01TUSUA')->where([
  3895. ['USUA_IDUS', '=', $idUser],
  3896. ['USUA_NULI', '=', $line]
  3897. ])->first();
  3898. if(is_null($usr)){
  3899. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  3900. }
  3901. $idFile = $this->encryptionController->decrypt($idFile);
  3902. if(!$idFile){
  3903. return $this->responseController->makeResponse(true, 'El ID del archivo solicitado no está encriptado correctamente.', [], 400);
  3904. }
  3905. $tempFile = DB::table('S002V01TARTE')->where([
  3906. ['ARTE_NULI', '=', $line],
  3907. ['ARTE_IDAR', '=', $idFile]
  3908. ])->first();
  3909. if(is_null($tempFile)){
  3910. return $this->responseController->makeResponse(true, 'El archivo solicitado no está registrado.', [], 404);
  3911. }
  3912. $fileColumns = ['Id', 'Activo', 'Modo de tarea', 'Nombre', 'Duración', 'Comienzo', 'Fin', 'Trabajo_Programado', 'Costo', 'Duración de línea base estimada',
  3913. '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'];
  3914. $MONTHS = ['enero' => '01', 'febrero' => '02', 'marzo' => '03', 'abril' => '04', 'mayo' => '05', 'junio' => '06', 'julio' => '07', 'agosto' => '08',
  3915. 'septiembre' => '09', 'octubre' => '10', 'noviembre' => '11', 'diciembre' => '12'];
  3916. $spreadsheet = IOFactory::load($tempFile->ARTE_UBTE);
  3917. $workSheet = $spreadsheet->getActiveSheet();
  3918. $maxColStr = $workSheet->getHighestColumn();
  3919. $maxCol = Coordinate::columnIndexFromString($maxColStr);
  3920. for($i = 1; $i <= $maxCol; $i++){
  3921. $colStr = Coordinate::stringFromColumnIndex($i);
  3922. $cell = $workSheet->getCell($colStr . "1");
  3923. $val = $cell->getValue();
  3924. if(!in_array($val, $fileColumns)){
  3925. return $this->responseController->makeResponse(true, 'El archivo tiene un formato inválido.', [], 400);
  3926. }
  3927. }
  3928. $instructions = [];
  3929. $maxRow = $workSheet->getHighestRow();
  3930. for($row = 2; $row <= $maxRow; $row++){
  3931. $activo = $workSheet->getCell("B$row")->getValue();
  3932. if($activo == 'Sí' || $activo == 'Si'){
  3933. $durationStr = $workSheet->getCell("E$row")->getValue();
  3934. $durationArr = explode(" ", $durationStr);
  3935. $duration = 0;
  3936. if($durationArr[1] == 'días' || $durationArr[1] == 'dias' || $durationArr[1] == 'día' || $durationArr[1] == 'dia'){
  3937. $daysFloat = floatval($durationArr[0]);
  3938. $daysInt = intval($daysFloat);
  3939. $duration += $daysInt * 24;
  3940. $hoursDec = $this->functionsController->floatSub($daysFloat, $daysInt);
  3941. $hoursFloat = $this->functionsController->floatMul($hoursDec, 24);
  3942. $duration = $this->functionsController->floatAdd($duration, $hoursFloat);
  3943. }
  3944. if($durationArr[1] == 'mins' || $durationArr[1] == 'min'){
  3945. $minsFloat = floatval($durationArr[0]);
  3946. $hoursFloat = $this->functionsController->floatDiv($minsFloat, 60);
  3947. $duration = $this->functionsController->floatAdd($duration, $hoursFloat);
  3948. }
  3949. $duration = round($duration, 5);
  3950. $startDateStr = $workSheet->getCell("F$row")->getValue();
  3951. $startDateArr = explode(" ", $startDateStr);
  3952. $startMonth = $MONTHS[$startDateArr[1]];
  3953. $startPeriod = $startDateArr[4] . $startDateArr[5];
  3954. $startPeriod = str_replace('.', '', $startPeriod);
  3955. $startHourArr = explode(":", $startDateArr[3]);
  3956. $startHour = intval($startHourArr[0]);
  3957. $startHour = $startPeriod == 'pm' && $startHour < 12 ? $startHour + 12 : $startHour;
  3958. $startHourStr = $startHour < 10 ? "0$startHour" : "$startHour";
  3959. $startDateTime = "$startDateArr[2]-$startMonth-$startDateArr[0] $startHourStr:$startHourArr[1]:00";
  3960. $startDateTimeObj = new Carbon($startDateTime);
  3961. $startTimestamp = $startDateTimeObj->timestamp;
  3962. $endDateStr = $workSheet->getCell("G$row")->getValue();
  3963. $endDateArr = explode(" ", $endDateStr);
  3964. $endMonth = $MONTHS[$endDateArr[1]];
  3965. $endPeriod = $endDateArr[4] . $endDateArr[5];
  3966. $endPeriod = str_replace('.', '', $endPeriod);
  3967. $endHourArr = explode(":", $endDateArr[3]);
  3968. $endHour = intval($endHourArr[0]);
  3969. $endHour = $endPeriod == 'pm' && $endHour < 12 ? $endHour + 12 : $endHour;
  3970. $endHourStr = $endHour < 10 ? "0$endHour" : "$endHour";
  3971. $endDateTime = "$endDateArr[2]-$endMonth-$endDateArr[0] $endHourStr:$endHourArr[1]:00";
  3972. $endDateTimeObj = new Carbon($endDateTime);
  3973. $endTimestamp = $endDateTimeObj->timestamp;
  3974. $difference = $endTimestamp - $startTimestamp;
  3975. $minutes = $this->functionsController->floatDiv($difference, 60);
  3976. $hours = $this->functionsController->floatDiv($minutes, 60);
  3977. $duration = round($hours, 5);
  3978. $instructions[] = [
  3979. "INSTRUCTION" => $workSheet->getCell("D$row")->getValue(),
  3980. "DURATION" => $duration,
  3981. "START" => $startDateTime,
  3982. "END" => $endDateTime,
  3983. "COST" => $workSheet->getCell("I$row")->getValue(),
  3984. ];
  3985. }
  3986. }
  3987. $now = $this->functionsController->now();
  3988. $nowStr = $now->toDateTimeString();
  3989. $actions = DB::getQueryLog();
  3990. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  3991. $idac = $this->functionsController->registerActivity(
  3992. $line,
  3993. 'S002V01M10GMPR',
  3994. 'S002V01F10DIBI',
  3995. '-',
  3996. 'Consulta',
  3997. "El usuario $name (" . $usr->USUA_IDUS . ") consultó el plan de mantenimiento para una nueva orden desde MS Project.",
  3998. $idUser,
  3999. $nowStr,
  4000. 'S002V01S02AOTR'
  4001. );
  4002. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4003. return $this->responseController->makeResponse(false, 'EXITO.', $instructions);
  4004. }
  4005. public function getFileToMSProject($idOrder, $idUser, $line) {
  4006. DB::enableQueryLog();
  4007. $idUser = $this->encryptionController->decrypt($idUser);
  4008. if(!$idUser){
  4009. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4010. }
  4011. $usr = DB::table('S002V01TUSUA')->where([
  4012. ['USUA_NULI', '=', $line],
  4013. ['USUA_IDUS', '=', $idUser],
  4014. ])->first();
  4015. if(is_null($usr)){
  4016. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4017. }
  4018. $idOrder = $this->encryptionController->decrypt($idOrder);
  4019. if(!$idOrder){
  4020. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  4021. }
  4022. $order = DB::table('S002V01TOTPR')->where([
  4023. ['OTPR_IDOT', '=', $idOrder],
  4024. ['OTPR_NULI', '=', $line]
  4025. ])->first();
  4026. if(is_null($order)){
  4027. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  4028. }
  4029. $cols = ['Id', 'Activo', 'Modo de tarea', 'Nombre', 'Duración', 'Comienzo', 'Fin', 'Trabajo_Programado', 'Costo', 'Duración de línea base estimada',
  4030. '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'];
  4031. $analysis = json_decode($order->OTPR_SEAN, true);
  4032. $instructionsConf = /*$analysis['instructionsConf']*/ '{}';
  4033. $instructions = json_decode($order->OTPR_ININ, true);
  4034. $arrCols = [];
  4035. $cont = 1;
  4036. foreach($instructions as $instruction){
  4037. $projectDuration = "";
  4038. if($instruction['DURACION'] < 24){
  4039. $duration = $instruction['DURACION'] * 60;
  4040. $projectDuration = "$duration min";
  4041. if($duration > 1){
  4042. $projectDuration .= "s";
  4043. }
  4044. }else{
  4045. $duration = $this->functionsController->floatDiv($instruction['DURACION'], 24);
  4046. $duration = round($duration, 2);
  4047. $projectDuration = "$duration día";
  4048. if($duration > 1){
  4049. $projectDuration .= "s";
  4050. }
  4051. }
  4052. $projectStartDate = $this->functionsController->buildProjectDate($instruction['INICIO']);
  4053. $projectEndDate = $this->functionsController->buildProjectDate($instruction['FIN']);
  4054. $cost = /*$instruction['ISFROMFILE'] ? $instruction['COSTO'] : $instructionsConf[$instruction['ID']]*/ '0';
  4055. $arrCol = [
  4056. "A" => $cont,
  4057. "B" => 'Sí',
  4058. "C" => 'Programada manualmente',
  4059. "D" => $instruction['INSTRUCCION'],
  4060. "E" => $projectDuration,
  4061. "F" => $projectStartDate,
  4062. "G" => $projectEndDate,
  4063. "H" => "0h",
  4064. "I" => $cost,
  4065. "J" => "0d",
  4066. "K" => "NOD",
  4067. "L" => "NOD",
  4068. "M" => "0h",
  4069. "N" => "0",
  4070. "O" => $projectDuration,
  4071. "P" => "0h",
  4072. "Q" => "0",
  4073. ];
  4074. $arrCols[] = $arrCol;
  4075. $cont++;
  4076. }
  4077. $now = $this->functionsController->now();
  4078. $nowStr = $now->toDateTimeString();
  4079. $dateTimeArr = explode(" ", $nowStr);
  4080. $dateArr = explode("-", $dateTimeArr[0]);
  4081. $year = substr($dateArr[0], 2);
  4082. $como = 'GMPR';
  4083. $cldo = 'OR';
  4084. $fecr = $year . $dateArr[1] . $dateArr[2];
  4085. $sec = DB::table('S002V01TAFAL')->where([
  4086. ['AFAL_NULI', '=', $line],
  4087. ['AFAL_COMO', '=', $como],
  4088. ['AFAL_CLDO', '=', $cldo],
  4089. ])->orderBy('AFAL_NUSE', 'desc')->first();
  4090. $nuse = "";
  4091. if(is_null($sec)){
  4092. $nuse = '000001';
  4093. }else{
  4094. $secu = "" . intval($sec->AFAL_NUSE) + 1 . "";
  4095. $nuse = "";
  4096. for($i = strlen($secu); $i < 6; $i++){
  4097. $nuse .= "0";
  4098. }
  4099. $nuse = $nuse . $secu;
  4100. }
  4101. $noar = "plan_de_mantenimiento_preventivo_ms_project_orden_$idOrder";
  4102. $exte = "xlsx";
  4103. $ver = DB::table('S002V01TAFAL')->where([
  4104. ['AFAL_NULI', '=', $line],
  4105. ['AFAL_COMO', '=', $como],
  4106. ['AFAL_CLDO', '=', $cldo],
  4107. ['AFAL_NOAR', '=', $noar],
  4108. ['AFAL_EXTE', '=', $exte],
  4109. ])->orderBy('AFAL_NUVE', 'desc')->first();
  4110. $nuve = "";
  4111. if(is_null($ver)){
  4112. $nuve = "01";
  4113. }else{
  4114. $vers = intval($ver->AFAL_NUVE) + 1;
  4115. $nuve = $vers < 10 ? "0$vers" : "$vers";
  4116. }
  4117. $line = $line < 10 ? "0$line" : "$line";
  4118. $filePath = 'C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\public_files\\';
  4119. $fileName = "$line-$como-$cldo-$fecr-$nuse=$nuve=$noar.$exte";
  4120. $tempFile = $filePath . $fileName;
  4121. if(file_exists($tempFile)){
  4122. unlink($tempFile);
  4123. }
  4124. $spreadsheet = new Spreadsheet();
  4125. $workSheet = $spreadsheet->getActiveSheet();
  4126. $colInd = 1;
  4127. foreach($cols as $colName){
  4128. $colStr = Coordinate::stringFromColumnIndex($colInd);
  4129. $workSheet->setCellValue($colStr . "1", $colName);
  4130. $workSheet->getColumnDimension($colStr)->setAutoSize(true);
  4131. $colInd++;
  4132. }
  4133. $row = 2;
  4134. foreach($arrCols as $col){
  4135. foreach($col as $k=>$v){
  4136. $workSheet->setCellValue($k . $row, $v);
  4137. }
  4138. $row++;
  4139. }
  4140. $writer = new Xlsx($spreadsheet);
  4141. $writer->save($tempFile);
  4142. $ubic = Storage::putFile('files', new File($tempFile));
  4143. $ubic = str_replace("/", "\\", $ubic);
  4144. $ubic = "C:\ITTEC\SAM\Dev\SistemaMantenimiento\sistema-mantenimiento-back\storage\app\\" . $ubic;
  4145. $tama = filesize($ubic);
  4146. $usac = json_encode([$idUser]);
  4147. unlink($tempFile);
  4148. DB::table('S002V01TAFAL')->insert([
  4149. 'AFAL_NULI' => $line,
  4150. 'AFAL_COMO' => $como,
  4151. 'AFAL_CLDO' => $cldo,
  4152. 'AFAL_FECR' => $fecr,
  4153. 'AFAL_NUSE' => $nuse,
  4154. 'AFAL_NUVE' => $nuve,
  4155. 'AFAL_NOAR' => $noar,
  4156. 'AFAL_EXTE' => $exte,
  4157. 'AFAL_TAMA' => $tama,
  4158. 'AFAL_UBIC' => $ubic,
  4159. 'AFAL_USAC' => $usac,
  4160. 'AFAL_USRE' => $idUser,
  4161. 'AFAL_FERE' => $nowStr,
  4162. ]);
  4163. $filesArr = json_decode($order->OTPR_DONE, true);
  4164. $filesArr[] = $fileName;
  4165. $filesStr = json_encode($filesArr);
  4166. DB::table('S002V01TOTPR')->where([
  4167. ['OTPR_NULI', '=', $line],
  4168. ['OTPR_IDOT', '=', $idOrder]
  4169. ])->update([
  4170. 'OTPR_DONE' => $filesStr,
  4171. 'OTPR_USMO' => $idUser,
  4172. 'OTPR_FEMO' => $nowStr
  4173. ]);
  4174. $actions = DB::getQueryLog();
  4175. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4176. $idac = $this->functionsController->registerActivity(
  4177. $line,
  4178. 'S002V01M10GMPR',
  4179. 'S002V01F10DIBI',
  4180. '-',
  4181. 'Registro',
  4182. "El usuario $name (" . $usr->USUA_IDUS . ") generó el archivo de plan de mantenimiento para MS Project de la orden #$idOrder.",
  4183. $idUser,
  4184. $nowStr,
  4185. 'S002V01S02AOTR'
  4186. );
  4187. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4188. return $this->responseController->makeResponse(false, 'EXITO.', ['fileID' => $fileName]);
  4189. }
  4190. public function getOrderStaff($idOrder, $idUser, $line) {
  4191. DB::enableQueryLog();
  4192. $idUser = $this->encryptionController->decrypt($idUser);
  4193. if(!$idUser){
  4194. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4195. }
  4196. $usr = DB::table('S002V01TUSUA')->where([
  4197. ['USUA_NULI', '=', $line],
  4198. ['USUA_IDUS', '=', $idUser],
  4199. ])->first();
  4200. if(is_null($usr)){
  4201. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4202. }
  4203. $idOrder = $this->encryptionController->decrypt($idOrder);
  4204. if(!$idOrder){
  4205. return $this->responseController->makeResponse(true, 'El ID de la orden solicitada no está encriptado correctamente.', [], 400);
  4206. }
  4207. $order = DB::table('S002V01TOTPR')->where([
  4208. ['OTPR_IDOT', '=', $idOrder],
  4209. ['OTPR_NULI', '=', $line]
  4210. ])->first();
  4211. if(is_null($order)){
  4212. return $this->responseController->makeResponse(true, 'La orden consultada no está registrada.', [], 404);
  4213. }
  4214. $staffArr = json_decode($order->OTPR_OPPR, true);
  4215. $staffTmp = [];
  4216. foreach($staffArr as $val){
  4217. if($val['TYPE'] == 'EQ'){
  4218. $employees = DB::table('S002V01TPERS')->where([
  4219. ['PERS_NULI', '=', $line],
  4220. ['PERS_EQTR', '=', $val['ID']],
  4221. ])->get()->all();
  4222. foreach($employees as $employee){
  4223. if(!in_array($employee->PERS_IDPE, $staffTmp)){
  4224. $staffTmp[] = $employee->PERS_IDPE;
  4225. }
  4226. }
  4227. }else if($val['TYPE'] == 'SU'){
  4228. $employees = DB::table('S002V01TPERS')->where([
  4229. ['PERS_NULI', '=', $line],
  4230. ['PERS_IDPS', '=', $val['ID']],
  4231. ])->get()->all();
  4232. foreach($employees as $employee){
  4233. if(!in_array($employee->PERS_IDPE, $staffTmp)){
  4234. $staffTmp[] = $employee->PERS_IDPE;
  4235. }
  4236. }
  4237. }else{
  4238. $id = intval($val['ID']);
  4239. if(!in_array($id, $staffTmp)){
  4240. $staffTmp[] = $id;
  4241. }
  4242. }
  4243. }
  4244. $staffFn = [];
  4245. foreach($staffTmp as $empID){
  4246. $employee = DB::table('S002V01TPERS')->select([
  4247. 'PERS_IDPE AS IDEMPLEADO',
  4248. 'PERS_IDUS AS IDUSUARIO',
  4249. DB::raw('TRIM(CONCAT(USUA_NOMB, " " , USUA_APPA, " ", COALESCE(USUA_APMA,""))) AS NOMBREUSUARIO'),
  4250. 'PERS_TICO AS TIPOCONTRATO',
  4251. 'PERS_IDPS AS IDSUBCONTRATISTA',
  4252. 'PESU_RASO AS RAZONSOCIAL',
  4253. 'PESU_REFI AS REGIMENFISCAL',
  4254. 'PERS_EQTR AS IDEQUIPO',
  4255. 'EQMA_NOMB AS NOMBREEQUIPO'
  4256. ])->join('S002V01TUSUA', 'USUA_IDUS', '=', 'PERS_IDUS')
  4257. ->leftJoin('S002V01TPESU', 'PESU_IDPS', '=', 'PERS_IDPS')
  4258. ->leftJoin('S002V01TEQMA', 'EQMA_IDEQ', '=', 'PERS_EQTR')->where([
  4259. ['PERS_NULI', '=', $line],
  4260. ['PERS_IDPE', '=', $empID],
  4261. ])->first();
  4262. if(!is_null($employee)){
  4263. $staffFn[] = $employee;
  4264. }
  4265. }
  4266. $now = $this->functionsController->now();
  4267. $nowStr = $now->toDateTimeString();
  4268. $actions = DB::getQueryLog();
  4269. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4270. $idac = $this->functionsController->registerActivity(
  4271. $line,
  4272. 'S002V01M10GMPR',
  4273. 'S002V01F01COTP',
  4274. 'S002V01P03COTP',
  4275. 'Consulta',
  4276. "El usuario $name (" . $usr->USUA_IDUS . ") consultó los empleados de la orden #$idOrder.",
  4277. $idUser,
  4278. $nowStr,
  4279. 'S002V01S01ORTR'
  4280. );
  4281. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4282. return $this->responseController->makeResponse(false, 'EXITO.', $staffFn);
  4283. }
  4284. public function getOrderExecutionDetails($idExecution, $idUser, $line) {
  4285. DB::enableQueryLog();
  4286. $idUser = $this->encryptionController->decrypt($idUser);
  4287. if(!$idUser){
  4288. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4289. }
  4290. $usr = DB::table('S002V01TUSUA')->where([
  4291. ['USUA_NULI', '=', $line],
  4292. ['USUA_IDUS', '=', $idUser],
  4293. ])->first();
  4294. if(is_null($usr)){
  4295. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4296. }
  4297. $idExecution = $this->encryptionController->decrypt($idExecution);
  4298. if(!$idExecution){
  4299. return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada no está encriptado correctamente.', [], 400);
  4300. }
  4301. $idExecArr = explode('|', $idExecution);
  4302. if(count($idExecArr) < 4){
  4303. return $this->responseController->makeResponse(true, 'El ID de la ejecución solicitada tiene un formato inválido.', [], 400);
  4304. }
  4305. $execution = DB::table('S002V01TBEOT')->select([
  4306. 'BEOT_IDRE AS IDREGISTRO',
  4307. 'BEOT_IDOT AS IDORDEN',
  4308. 'BEOT_FEPR AS FECHAPROGRAMACION',
  4309. 'BEOT_TIAC AS TIPOACCION',
  4310. 'BEOT_TIOR AS TIPOORDEN',
  4311. 'BEOT_DTEJ AS TIEMPOEJECUCION',
  4312. 'BEOT_OBSE AS OBSERVACIONES',
  4313. 'BEOT_FEEJ AS FECHAEJECUCION',
  4314. 'BEOT_USEJ AS USUARIOEJECUCION',
  4315. 'BEOT_FEFI AS FECHAFINALIZACION',
  4316. 'BEOT_USFI AS USUARIOFINALIZO'
  4317. ])->where([
  4318. ['BEOT_IDRE', '=', $idExecArr[0]],
  4319. ['BEOT_NULI', '=', $line],
  4320. ['BEOT_IDOT', '=', $idExecArr[2]],
  4321. ['BEOT_FEPR', '=', $idExecArr[3]],
  4322. ])->first();
  4323. if(is_null($execution)){
  4324. return $this->responseController->makeResponse(true, 'El registro de la ejecución solicitada no existe.', [], 404);
  4325. }
  4326. $execution->IDREGISTRO = $this->encryptionController->encrypt($execution->IDREGISTRO);
  4327. $execution->IDORDEN = $this->encryptionController->encrypt($execution->IDORDEN);
  4328. $execUsr = DB::table('S002V01TUSUA')->where([
  4329. ['USUA_IDUS', '=', $execution->USUARIOEJECUCION],
  4330. ['USUA_NULI', '=', $line]
  4331. ])->first();
  4332. $execName = $this->functionsController->joinName($execUsr->USUA_NOMB, $execUsr->USUA_APPA, $execUsr->USUA_APMA);
  4333. $execution->USUARIOEJECUCION = $execName . " (" . $execution->USUARIOEJECUCION . ")";
  4334. if(!is_null($execution->USUARIOFINALIZO)){
  4335. $finUsr = DB::table('S002V01TUSUA')->where([
  4336. ['USUA_IDUS', '=', $execution->USUARIOFINALIZO],
  4337. ['USUA_NULI', '=', $line]
  4338. ])->first();
  4339. $finName = $this->functionsController->joinName($finUsr->USUA_NOMB, $finUsr->USUA_APPA, $finUsr->USUA_APMA);
  4340. $execution->USUARIOFINALIZO = $finName . " (" . $execution->USUARIOFINALIZO . ")";
  4341. }
  4342. $now = $this->functionsController->now();
  4343. $nowStr = $now->toDateTimeString();
  4344. $actions = DB::getQueryLog();
  4345. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4346. $idac = $this->functionsController->registerActivity(
  4347. $line,
  4348. 'S002V01M10GMPR',
  4349. 'S002V01F01COTP',
  4350. 'S002V01P03COTP',
  4351. 'Consulta',
  4352. "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].",
  4353. $idUser,
  4354. $nowStr,
  4355. 'S002V01S01ORTR'
  4356. );
  4357. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4358. return $this->responseController->makeResponse(false, 'EXITO.', $execution);
  4359. }
  4360. public function getWorkOrdersByEquipment($equipmentCode, $idUser, $line) {
  4361. DB::enableQueryLog();
  4362. $idUser = $this->encryptionController->decrypt($idUser);
  4363. if(!$idUser){
  4364. return $this->responseController->makeResponse(true, 'El ID del usuario que realizó la solicitud no está encriptado correctamente.', [], 400);
  4365. }
  4366. $usr = DB::table('S002V01TUSUA')->where([
  4367. ['USUA_NULI', '=', $line],
  4368. ['USUA_IDUS', '=', $idUser],
  4369. ])->first();
  4370. if(is_null($usr)){
  4371. return $this->responseController->makeResponse(true, 'El usuario que realizó la consulta no está registrado.', [], 404);
  4372. }
  4373. $equipmentCode = $this->encryptionController->decrypt($equipmentCode);
  4374. if(!$equipmentCode){
  4375. return $this->responseController->makeResponse(true, 'El código del equipamiento relacionado no está encriptado correctamente.', [], 400);
  4376. }
  4377. $equipment = DB::table('S002V01TEQUI')->where([
  4378. ['EQUI_NULI', '=', $line],
  4379. ['EQUI_COEQ', '=', $equipmentCode]
  4380. ])->first();
  4381. if(is_null($equipment)){
  4382. return $this->responseController->makeResponse(true, 'El equipamiento relacionado no está registrado.', [], 404);
  4383. }
  4384. $workOrders = DB::table('S002V01TOTPR')->select([
  4385. 'OTPR_IDOT AS IDORDEN',
  4386. 'OTPR_EQIN AS EQUIPO',
  4387. 'OTPR_FIAP AS FECHAINICIO',
  4388. 'OTPR_FTAP AS FECHAFINAL',
  4389. 'OTPR_ACAS AS ACTIVADOR',
  4390. 'ACTI_TIAC AS TIPOACTIVADOR',
  4391. 'ACTI_PRIO AS PRIORIDAD',
  4392. 'OTPR_ESTA AS ESTATUS'
  4393. ])->where([
  4394. ['OTPR_NULI', '=', $line],
  4395. ['OTPR_EQIN', '=', $equipmentCode],
  4396. ['OTPR_ESTA', '!=', 'E'],
  4397. ])->leftJoin('S002V01TACTI', 'ACTI_IDAC', '=', 'OTPR_ACAS')
  4398. ->orderBy('OTPR_IDOT', 'desc')->get()->all();
  4399. foreach($workOrders as $key=>$order){
  4400. $order->IDORDEN = $this->encryptionController->encrypt($order->IDORDEN);
  4401. $order->EQUIPO = $this->encryptionController->encrypt($order->EQUIPO);
  4402. $order->ACTIVADOR = $this->encryptionController->encrypt($order->ACTIVADOR);
  4403. if(!is_null($order->PRIORIDAD)){
  4404. $order->PRIORIDAD = $this->encryptionController->encrypt($order->PRIORIDAD);
  4405. }
  4406. if($order->FECHAFINAL == '0001-01-01 00:00:00') $order->FECHAFINAL = null;
  4407. if($order->FECHAINICIO == '0001-01-01 00:00:00') $order->FECHAINICIO = null;
  4408. $workOrders[$key] = $order;
  4409. }
  4410. $now = $this->functionsController->now();
  4411. $nowStr = $now->toDateTimeString();
  4412. $actions = DB::getQueryLog();
  4413. $name = $this->functionsController->joinName($usr->USUA_NOMB, $usr->USUA_APPA, $usr->USUA_APMA);
  4414. $idac = $this->functionsController->registerActivity(
  4415. $line,
  4416. 'S002V01M10GMPR',
  4417. 'S002V01F01COTP',
  4418. 'S002V01P01HOTP',
  4419. 'Consulta',
  4420. "El usuario $name (" . $usr->USUA_IDUS . ") consultó las órdenes de trabajo relacionadas al equipamient $equipmentCode.",
  4421. $idUser,
  4422. $nowStr,
  4423. 'S002V01S01ORTR'
  4424. );
  4425. $this->functionsController->registerLog($actions, $idUser, $nowStr, $idac, $line);
  4426. return $this->responseController->makeResponse(false, 'EXITO.', $workOrders);
  4427. }
  4428. }