PreventiveMaintenanceController.php 209 KB

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