PreventiveMaintenanceController.php 183 KB

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