PreventiveMaintenanceController.php 208 KB

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