PreventiveMaintenanceController.php 218 KB

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