PreventiveMaintenanceController.php 218 KB

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