PreventiveMaintenanceController.php 193 KB

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