StockController.php 292 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539
  1. <?php
  2. /*
  3. Desarrollador: Ing. Jean Jairo Benitez Meza
  4. Ultima Modificación: 29/02/2023
  5. Módulo: Gestión de Inventario y/o Stock
  6. */
  7. namespace App\Http\Controllers;
  8. use App\Http\Controllers\Controller;
  9. use App\Http\Controllers\ResourcesController;
  10. use App\Http\Controllers\ResponseController;
  11. use App\Http\Controllers\EncryptionController;
  12. use App\Http\Controllers\DocumentManagementController;
  13. use Illuminate\Http\Request;
  14. use Illuminate\Support\Facades\DB;
  15. use Illuminate\Support\Facades\Validator;
  16. use App\Http\Controllers\FunctionsController;
  17. use Illuminate\Support\Facades\Storage;
  18. use Illuminate\Http\File;
  19. use Illuminate\Support\Carbon;
  20. use PhpOffice\PhpSpreadsheet\Spreadsheet;
  21. use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
  22. use Dompdf\Dompdf;
  23. class StockController extends Controller
  24. {
  25. private $responseController;
  26. private $encController;
  27. private $resourcesController;
  28. private $documentManagementController;
  29. private $functionsController;
  30. private $processManagementController;
  31. public function __construct(){
  32. $this->responseController = new ResponseController();
  33. $this->encController = new EncryptionController();
  34. $this->resourcesController = new ResourcesController();
  35. $this->documentManagementController = new DocumentManagementController();
  36. $this->functionsController = new FunctionsController();
  37. $this->processManagementController = new ProcessManagementController();
  38. }
  39. // Crear Artículo en Stock
  40. public function createArtitleWithoutOrder(Request $request) {
  41. $validator = Validator::make($request->all(), [
  42. 'ARTICULO' => 'required',
  43. 'MODELO' => 'required',
  44. 'CODIGO_MODELO' => 'required',
  45. 'FAMILIA' => 'required',
  46. 'SUBFAMILIA' => 'required',
  47. 'UNIDAD' => 'required',
  48. 'CODIGO_BARRAS' => 'required',
  49. 'CANTIDAD' => 'required',
  50. 'STOCK_MINIMO' => 'required',
  51. 'STOCK_MAXIMO' => 'required',
  52. 'REPARACION' => 'required|boolean',
  53. 'CONSUMIBLE' => 'required|boolean',
  54. 'PELIGROSO' => 'required|boolean',
  55. // 'FECHA_VENCIMIENTO' => '',
  56. // 'PROVEEDOR' => 'required',
  57. 'IMAGEN' => 'required',
  58. 'NUMERO_LINEA' => 'required',
  59. 'USUARIO' => 'required',
  60. ]);
  61. if ($validator->fails()) {
  62. return $this->responseController->makeResponse(
  63. true,
  64. "ERR_STOCK_REG000: Se encontraron uno o más errores.",
  65. $this->responseController->makeErrors($validator->errors()->messages()),
  66. 401
  67. );
  68. }
  69. DB::beginTransaction();
  70. $requestData = $request->all();
  71. try {
  72. $user = $this->encController->decrypt($requestData['USUARIO']);
  73. } catch (\Throwable $th) {
  74. DB::rollBack();
  75. return $this->responseController->makeResponse(true, "ERR_STOCK_REG001: Ocurrió un error al obtener el usuario.", $th->getMessage(), 500);
  76. }
  77. try {
  78. $validateFamily = DB::table('S002V01TFAMI')
  79. ->where('FAMI_COFA','=', $requestData['FAMILIA'])
  80. ->where('FAMI_NULI','=', $requestData['NUMERO_LINEA'])
  81. ->where('FAMI_ESTA','=','Activo')
  82. ->exists();
  83. } catch (\Throwable $th) {
  84. DB::rollBack();
  85. return $this->responseController->makeResponse(true, "ERR_STOCK_REG002: Ocurrió un error al validar la familia.", $th->getMessage(), 500);
  86. }
  87. if (!$validateFamily) {
  88. DB::rollBack();
  89. return $this->responseController->makeResponse(true, "ERR_STOCK_REG003: La familia no existe.", [], 500);
  90. }
  91. try {
  92. $validateSubfamily = DB::table('S002V01TSUBF')
  93. ->where('SUBF_COSU','=', $requestData['SUBFAMILIA'])
  94. ->where('SUBF_NULI','=', $requestData['NUMERO_LINEA'])
  95. ->where('SUBF_ESTA','=','Activo')
  96. ->exists();
  97. } catch (\Throwable $th) {
  98. DB::rollBack();
  99. return $this->responseController->makeResponse(true, "ERR_STOCK_REG004: Ocurrió un error al validar la subfamilia.", $th->getMessage(), 500);
  100. }
  101. if (!$validateSubfamily) {
  102. DB::rollBack();
  103. return $this->responseController->makeResponse(true, "ERR_STOCK_REG005: La subfamilia no existe.", [], 500);
  104. }
  105. try {
  106. $validateUnit = DB::table('S002V01TUNID')
  107. ->where('UNID_IDUN','=', $requestData['UNIDAD'])
  108. ->where('UNID_NULI','=', $requestData['NUMERO_LINEA'])
  109. ->where('UNID_ESTA','=','Activo')
  110. ->exists();
  111. } catch (\Throwable $th) {
  112. DB::rollBack();
  113. return $this->responseController->makeResponse(true, "ERR_STOCK_REG006: Ocurrió un error al validar la unidad.", $th->getMessage(), 500);
  114. }
  115. if (!$validateUnit) {
  116. DB::rollBack();
  117. return $this->responseController->makeResponse(true, "ERR_STOCK_REG007: La unidad no existe.", [], 500);
  118. }
  119. $requestData['PROVEEDOR'] = $requestData['PROVEEDOR'] === '' ? null : $requestData['PROVEEDOR'];
  120. if (!is_null($requestData['PROVEEDOR'])) {
  121. try {
  122. $validateUnit = DB::table('S002V01TPROV')
  123. ->where('PROV_NUPR','=', $requestData['PROVEEDOR'])
  124. ->where('PROV_NULI','=', $requestData['NUMERO_LINEA'])
  125. ->where('PROV_ESTA','=','Activo')
  126. ->exists();
  127. } catch (\Throwable $th) {
  128. DB::rollBack();
  129. return $this->responseController->makeResponse(true, "ERR_STOCK_REG008: Ocurrió un error al validar el proveedor.", $th->getMessage(), 500);
  130. }
  131. if (!$validateUnit) {
  132. DB::rollBack();
  133. return $this->responseController->makeResponse(true, "ERR_STOCK_REG009: El proveedor no existe.", [], 500);
  134. }
  135. }
  136. $arrCodeImages = array();
  137. foreach ($requestData['IMAGEN'] as $key => $encIdFile) {
  138. $idFile = $this->encController->decrypt($encIdFile);
  139. $tempFile = DB::table('S002V01TARTE')->where([
  140. ['ARTE_NULI', '=', $requestData['NUMERO_LINEA']],
  141. ['ARTE_IDAR', '=', $idFile],
  142. ])->first();
  143. if(is_null($tempFile)){
  144. return $this->responseController->makeResponse(true, 'ERR_ARTITLE_REG006: El archivo consultado no está registrado', [], 404);
  145. }else if($tempFile->ARTE_ESTA == 'Eliminado'){
  146. return $this->responseController->makeResponse(true, 'ERR_ARTITLE_REG007: El archivo consultado está eliminado', [], 404);
  147. }
  148. $fileResponse = $this->documentManagementController->moveFinalFile(
  149. intval($requestData['NUMERO_LINEA']),
  150. 'GIST',
  151. 'FO',
  152. $tempFile,
  153. $user,
  154. );
  155. if(!$fileResponse[0]){
  156. return $this->responseController->makeResponse(true, 'ERR_ARTITLE_REG008: '.$fileResponse[1], [], 400);
  157. }
  158. $arrCodeImages[] = $this->encController->encrypt($fileResponse[1]);
  159. }
  160. $jsonImages = json_encode($arrCodeImages);
  161. $now = $this->functionsController->now();
  162. $currentDate = $now->toDateTimeString();
  163. try {
  164. $validateRegister = DB::table('S002V01TSTAR')->insert([
  165. // 'STAR_CODI' => $requestData['CODIGO_STOCK'],
  166. 'STAR_ARTI' => $requestData['ARTICULO'],
  167. 'STAR_MODE' => $requestData['MODELO'],
  168. 'STAR_COMO' => $requestData['CODIGO_MODELO'],
  169. 'STAR_IDFA' => $requestData['FAMILIA'],
  170. 'STAR_IDSU' => $requestData['SUBFAMILIA'],
  171. 'STAR_NUPR' => $requestData['PROVEEDOR'],
  172. 'STAR_IDUN' => $requestData['UNIDAD'],
  173. 'STAR_COBA' => $requestData['CODIGO_BARRAS'],
  174. 'STAR_CANT' => $requestData['CANTIDAD'],
  175. 'STAR_STMI' => $requestData['STOCK_MINIMO'],
  176. 'STAR_STMA' => $requestData['STOCK_MAXIMO'],
  177. 'STAR_REPA' => $requestData['REPARACION'],
  178. 'STAR_CONS' => $requestData['CONSUMIBLE'],
  179. 'STAR_PELI' => $requestData['PELIGROSO'],
  180. 'STAR_FEVE' => $requestData['FECHA_VENCIMIENTO'],
  181. 'STAR_IMAG' => $jsonImages,
  182. 'STAR_TIAD' => 'Sin Pedido',
  183. 'STAR_NULI' => $requestData['NUMERO_LINEA'],
  184. 'STAR_USRE' => $user,
  185. 'STAR_FERE' => $currentDate,
  186. 'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  187. ]);
  188. } catch (\Throwable $th) {
  189. DB::rollBack();
  190. return $this->responseController->makeResponse(true, "ERR_STOCK_REG011: Ocurrió un error al registrar el artículo.", $th->getMessage(), 500);
  191. }
  192. if (!$validateRegister) {
  193. DB::rollBack();
  194. return $this->responseController->makeResponse(true, "ERR_STOCK_REG012: No se pudo registrar el artículo.", [], 500);
  195. }
  196. DB::commit();
  197. return $this->responseController->makeResponse(false, "EXITO: Registro Exitoso");
  198. }
  199. // FUNCIÓN GESTIÓN DE ALMACENES
  200. public function getWarehouse( $user, $line ) {
  201. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  202. if ($arrResponseCheckUser['error']) {
  203. DB::rollBack();
  204. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000:'.$arrResponseCheckUser['msg'], [], 401);
  205. }
  206. try {
  207. $arrWarehouse = DB::table('S002V01TALMA')
  208. ->where('ALMA_NULI', '=', $line)
  209. ->get([
  210. 'ALMA_COAL AS CODIGO_ALMACEN',
  211. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  212. 'ALMA_NORE AS NOMBRE_RESPONSABLE',
  213. 'ALMA_APRE AS APELLIDO_PATERNO_RESPONSABLE',
  214. 'ALMA_AMRE AS APELLIDO_MATERNO_RESPONSABLE',
  215. 'ALMA_COR1 AS CORREO1',
  216. 'ALMA_COR2 AS CORREO2',
  217. 'ALMA_LAD1 AS LADA1',
  218. 'ALMA_TEL1 AS TELEFONO1',
  219. 'ALMA_LAD2 AS LADA2',
  220. 'ALMA_TEL2 AS TELEFONO2',
  221. 'ALMA_CALL AS CALLE',
  222. 'ALMA_NUEX AS NUMERO_EXTERIOR',
  223. 'ALMA_NUIN AS NUMERO_INTERIOR',
  224. 'ALMA_COPO AS CODIGO_POSTAL',
  225. 'ALMA_COLO AS COLONIA',
  226. 'ALMA_LOCA AS LOCALIDAD',
  227. 'ALMA_MUNI AS MUNICIPIO',
  228. 'ALMA_ENTI AS ENTIDAD_FEDERATIVA',
  229. 'ALMA_PAIS AS PAIS',
  230. 'ALMA_ESTA AS ESTADO',
  231. 'ALMA_USRE AS USUARIO_REGISTRA',
  232. 'ALMA_FERE AS FECHA_REGISTRA',
  233. 'ALMA_USMO AS USUARIO_MODIFICA',
  234. 'ALMA_FEMO AS FECHA_MODIFICA',
  235. ]);
  236. $arrWarehouse = json_decode( json_encode($arrWarehouse), true );
  237. } catch (\Throwable $th) {
  238. DB::rollBack();
  239. return $this->responseController->makeResponse(
  240. true,
  241. "ERR_WAREHOUSE_GET001: Ocurrió un error al obtener los almacenes.",
  242. $th->getMessage(),
  243. 500
  244. );
  245. }
  246. foreach ($arrWarehouse as $keyWarehouse => $warehouse) {
  247. $arrResponseGetAddress = $this->resourcesController->getAddress(
  248. $warehouse['CODIGO_POSTAL'],
  249. $warehouse['COLONIA'],
  250. $warehouse['MUNICIPIO'],
  251. $warehouse['LOCALIDAD'],
  252. $warehouse['ENTIDAD_FEDERATIVA'],
  253. $warehouse['PAIS'],
  254. $line
  255. );
  256. if ($arrResponseGetAddress['error']) {
  257. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GET002: '.$arrResponseGetAddress['msg'], $arrResponseGetAddress['response'], 401);
  258. }
  259. $warehouse['CODIGO_POSTAL'] = $arrResponseGetAddress['response']['CODIGO_POSTAL'];
  260. $warehouse['COLONIA'] = $arrResponseGetAddress['response']['COLONIA'];
  261. $warehouse['MUNICIPIO'] = $arrResponseGetAddress['response']['MUNICIPIO'];
  262. $warehouse['LOCALIDAD'] = $arrResponseGetAddress['response']['LOCALIDAD'];
  263. $warehouse['ENTIDAD_FEDERATIVA'] = $arrResponseGetAddress['response']['ENTIDAD_FEDERATIVA'];
  264. $warehouse['PAIS'] = $arrResponseGetAddress['response']['PAIS'];
  265. try {
  266. $countStock = DB::table('S002V01TUBAR')
  267. ->where('UBAR_NULI', '=', $line)
  268. ->where('UBAR_ESTA', '=', 'Activo')
  269. ->where('UBAR_COAL', '=', $warehouse['CODIGO_ALMACEN'])
  270. ->count();
  271. } catch (\Throwable $th) {
  272. DB::rollBack();
  273. return $this->responseController->makeResponse(
  274. true,
  275. "ERR_WAREHOUSE_GET003: Ocurrió un error al obtener los almacenes.",
  276. $th->getMessage(),
  277. 500
  278. );
  279. }
  280. $warehouse['CANTIDAD_STOCK'] = $countStock;
  281. $arrWarehouse[$keyWarehouse] = $warehouse;
  282. }
  283. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrWarehouse, $line);
  284. if ($responseCheckLatestUpdate['error']) {
  285. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  286. }
  287. $arrWarehouse = $responseCheckLatestUpdate['response'];
  288. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrWarehouse);
  289. }
  290. public function getWarehouseById( $idWarehouse, $user, $line ) {
  291. try {
  292. $idWarehouse = $this->encController->decrypt($idWarehouse);
  293. } catch (\Throwable $th) {
  294. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  295. }
  296. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  297. if ($arrResponseCheckUser['error']) {
  298. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000:'.$arrResponseCheckUser['msg'], [], 401);
  299. }
  300. try {
  301. $arrWarehouse = (array) DB::table('S002V01TALMA')
  302. ->where('ALMA_COAL', '=', $idWarehouse)
  303. ->where('ALMA_NULI', '=', $line)
  304. ->first([
  305. 'ALMA_COAL AS CODIGO_ALMACEN',
  306. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  307. 'ALMA_NORE AS NOMBRE_RESPONSABLE',
  308. 'ALMA_APRE AS APELLIDO_PATERNO_RESPONSABLE',
  309. 'ALMA_AMRE AS APELLIDO_MATERNO_RESPONSABLE',
  310. 'ALMA_COR1 AS CORREO1',
  311. 'ALMA_COR2 AS CORREO2',
  312. 'ALMA_LAD1 AS LADA1',
  313. 'ALMA_TEL1 AS TELEFONO1',
  314. 'ALMA_LAD2 AS LADA2',
  315. 'ALMA_TEL2 AS TELEFONO2',
  316. 'ALMA_CALL AS CALLE',
  317. 'ALMA_NUEX AS NUMERO_EXTERIOR',
  318. 'ALMA_NUIN AS NUMERO_INTERIOR',
  319. 'ALMA_COPO AS CODIGO_POSTAL',
  320. 'ALMA_COLO AS COLONIA',
  321. 'ALMA_LOCA AS LOCALIDAD',
  322. 'ALMA_MUNI AS MUNICIPIO',
  323. 'ALMA_ENTI AS ENTIDAD_FEDERATIVA',
  324. 'ALMA_PAIS AS PAIS',
  325. 'ALMA_ESTA AS ESTADO',
  326. 'ALMA_USRE AS USUARIO_REGISTRA',
  327. 'ALMA_FERE AS FECHA_REGISTRA',
  328. 'ALMA_USMO AS USUARIO_MODIFICA',
  329. 'ALMA_FEMO AS FECHA_MODIFICA',
  330. ]);
  331. $arrWarehouse = json_decode( json_encode($arrWarehouse), true );
  332. } catch (\Throwable $th) {
  333. DB::rollBack();
  334. return $this->responseController->makeResponse(
  335. true,
  336. "ERR_WAREHOUSE_GETBY001: Ocurrió un error al obtener los almacenes.",
  337. $th->getMessage(),
  338. 500
  339. );
  340. }
  341. if (!empty($arrWarehouse)) {
  342. $arrResponseGetAddress = $this->resourcesController->getAddress(
  343. $arrWarehouse['CODIGO_POSTAL'],
  344. $arrWarehouse['COLONIA'],
  345. $arrWarehouse['MUNICIPIO'],
  346. $arrWarehouse['LOCALIDAD'],
  347. $arrWarehouse['ENTIDAD_FEDERATIVA'],
  348. $arrWarehouse['PAIS'],
  349. $line
  350. );
  351. if ($arrResponseGetAddress['error']) {
  352. return $this->responseController->makeResponse(true, 'ERR_arrWarehouse_GETBY002: '.$arrResponseGetAddress['msg'], $arrResponseGetAddress['response'], 406);
  353. }
  354. $arrWarehouse['CODIGO_POSTAL'] = $arrResponseGetAddress['response']['CODIGO_POSTAL'];
  355. $arrWarehouse['COLONIA'] = $arrResponseGetAddress['response']['COLONIA'];
  356. $arrWarehouse['MUNICIPIO'] = $arrResponseGetAddress['response']['MUNICIPIO'];
  357. $arrWarehouse['LOCALIDAD'] = $arrResponseGetAddress['response']['LOCALIDAD'];
  358. $arrWarehouse['ENTIDAD_FEDERATIVA'] = $arrResponseGetAddress['response']['ENTIDAD_FEDERATIVA'];
  359. $arrWarehouse['PAIS'] = $arrResponseGetAddress['response']['PAIS'];
  360. }
  361. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrWarehouse);
  362. }
  363. public function getWarehouseActives($user, $line) {
  364. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  365. if ($arrResponseCheckUser['error']) {
  366. DB::rollBack();
  367. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000:'.$arrResponseCheckUser['msg'], [], 401);
  368. }
  369. try {
  370. $arrWarehouse = DB::table('S002V01TALMA')
  371. ->where('ALMA_NULI', '=', $line)
  372. ->where('ALMA_ESTA', '=', 'Activo')
  373. ->get([
  374. 'ALMA_COAL AS CODIGO_ALMACEN',
  375. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  376. 'ALMA_NORE AS NOMBRE_RESPONSABLE',
  377. 'ALMA_APRE AS APELLIDO_PATERNO_RESPONSABLE',
  378. 'ALMA_AMRE AS APELLIDO_MATERNO_RESPONSABLE',
  379. 'ALMA_COR1 AS CORREO1',
  380. 'ALMA_LAD1 AS LADA1',
  381. 'ALMA_TEL1 AS TELEFONO1',
  382. ]);
  383. $arrWarehouse = json_decode( json_encode($arrWarehouse), true );
  384. } catch (\Throwable $th) {
  385. DB::rollBack();
  386. return $this->responseController->makeResponse(
  387. true,
  388. "ERR_WAREHOUSE_GET001: Ocurrió un error al obtener los almacenes.",
  389. $th->getMessage(),
  390. 500
  391. );
  392. }
  393. foreach ($arrWarehouse as $key => $warehouse) {
  394. try {
  395. $countStock = DB::table('S002V01TUBAR')
  396. ->where('UBAR_NULI', '=', $line)
  397. ->where('UBAR_ESTA', '=', 'Activo')
  398. ->where('UBAR_COAL', '=', $warehouse['CODIGO_ALMACEN'])
  399. ->count();
  400. } catch (\Throwable $th) {
  401. DB::rollBack();
  402. return $this->responseController->makeResponse(
  403. true,
  404. "ERR_WAREHOUSE_GET003: Ocurrió un error al obtener los almacenes.",
  405. $th->getMessage(),
  406. 500
  407. );
  408. }
  409. $warehouse['CODIGO_ALMACEN'] = $this->encController->encrypt($warehouse['CODIGO_ALMACEN'] );
  410. $warehouse['CANTIDAD_STOCK'] = $countStock;
  411. $arrWarehouse[$key] = $warehouse;
  412. }
  413. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrWarehouse);
  414. }
  415. public function createWarehouse( Request $request ) {
  416. $validator = Validator::make($request->all(), [
  417. 'CODIGO_ALMACEN' => 'required|string',
  418. 'NOMBRE_ALMACEN' => 'required|string',
  419. 'NOMBRE_RESPONSABLE' => 'required|string',
  420. 'APELLIDO_PATERNO_RESPONSABLE' => 'required|string',
  421. 'APELLIDO_MATERNO_RESPONSABLE' => 'nullable|string',
  422. 'CORREO1' => 'required|string',
  423. 'CORREO2' => 'nullable|string',
  424. 'LADA1' => 'required|string',
  425. 'TELEFONO1' => 'required|string',
  426. 'LADA2' => 'nullable|string',
  427. 'TELEFONO2' => 'nullable|string',
  428. 'CALLE' => 'required|string',
  429. 'NUMERO_EXTERIOR' => 'required|string',
  430. 'NUMERO_INTERIOR' => 'nullable|string',
  431. 'CODIGO_POSTAL' => 'required|string',
  432. 'COLONIA' => 'required|string',
  433. 'LOCALIDAD' => 'nullable|string',
  434. 'MUNICIPIO' => 'required|string',
  435. 'ENTIDAD_FEDERATIVA' => 'required|string',
  436. 'PAIS' => 'required|string',
  437. 'USUARIO' => 'required|string',
  438. 'NUMERO_LINEA' => 'required|integer',
  439. ]);
  440. if ($validator->fails()) {
  441. return $this->responseController->makeResponse(
  442. true,
  443. "ERR_WAREHOUSE_REG000: Se encontraron uno o más errores.",
  444. $this->responseController->makeErrors($validator->errors()->messages()),
  445. 401
  446. );
  447. }
  448. DB::beginTransaction();
  449. $requestData = $request->all();
  450. // Se valida y se obtiene el usuario
  451. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  452. if ($arrResponseCheckUser['error']) {
  453. DB::rollBack();
  454. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_REG001:'.$arrResponseCheckUser['msg'], [], 401);
  455. }
  456. $user = $arrResponseCheckUser['response'];
  457. // Se vallidan los campos de dirección
  458. $arrResponseCheckAddress = $this->resourcesController->validateAddress(
  459. $requestData['CODIGO_POSTAL'],
  460. $requestData['COLONIA'],
  461. $requestData['MUNICIPIO'],
  462. $requestData['LOCALIDAD'],
  463. $requestData['ENTIDAD_FEDERATIVA'],
  464. $requestData['PAIS'],
  465. $requestData['NUMERO_LINEA'],
  466. );
  467. if ($arrResponseCheckAddress['error']) {
  468. DB::rollBack();
  469. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_REG002: '.$arrResponseCheckAddress['msg'], $arrResponseCheckAddress['response'], 401);
  470. }
  471. $now = $this->functionsController->now();
  472. $currentDate = $now->toDateTimeString();
  473. try {
  474. $validateInsert = DB::table('S002V01TALMA')->insert([
  475. 'ALMA_NULI' => $requestData['NUMERO_LINEA'],
  476. 'ALMA_COAL' => $requestData['CODIGO_ALMACEN'],
  477. 'ALMA_NOAL' => $requestData['NOMBRE_ALMACEN'],
  478. 'ALMA_NORE' => $requestData['NOMBRE_RESPONSABLE'],
  479. 'ALMA_APRE' => $requestData['APELLIDO_PATERNO_RESPONSABLE'],
  480. 'ALMA_AMRE' => $requestData['APELLIDO_MATERNO_RESPONSABLE'],
  481. 'ALMA_COR1' => $requestData['CORREO1'],
  482. 'ALMA_COR2' => $requestData['CORREO2'],
  483. 'ALMA_LAD1' => $requestData['LADA1'],
  484. 'ALMA_TEL1' => $requestData['TELEFONO1'],
  485. 'ALMA_LAD2' => $requestData['LADA2'],
  486. 'ALMA_TEL2' => $requestData['TELEFONO2'],
  487. 'ALMA_CALL' => $requestData['CALLE'],
  488. 'ALMA_NUEX' => $requestData['NUMERO_EXTERIOR'],
  489. 'ALMA_NUIN' => $requestData['NUMERO_INTERIOR'],
  490. 'ALMA_COPO' => $requestData['CODIGO_POSTAL'],
  491. 'ALMA_COLO' => $requestData['COLONIA'],
  492. 'ALMA_LOCA' => $requestData['LOCALIDAD'],
  493. 'ALMA_MUNI' => $requestData['MUNICIPIO'],
  494. 'ALMA_ENTI' => $requestData['ENTIDAD_FEDERATIVA'],
  495. 'ALMA_PAIS' => $requestData['PAIS'],
  496. 'ALMA_USRE' => $user,
  497. 'ALMA_FERE' => $currentDate,
  498. 'ALMA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  499. ]);
  500. } catch (\Throwable $th) {
  501. DB::rollBack();
  502. return $this->responseController->makeResponse(
  503. true,
  504. "ERR_WAREHOUSE_REG003: Ocurrió un error al insertar el registro del almacen.",
  505. $th->getMessage(),
  506. 500
  507. );
  508. }
  509. if (!$validateInsert) {
  510. DB::rollBack();
  511. return $this->responseController->makeResponse(
  512. true,
  513. "ERR_WAREHOUSE_REG004: No se pudo insertar el registro del almacen.",
  514. [],
  515. 500
  516. );
  517. }
  518. DB::commit();
  519. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  520. }
  521. public function updateWarehouse( Request $request, $idWarehouse ) {
  522. $validator = Validator::make($request->all(), [
  523. 'CODIGO_ALMACEN' => 'required|string',
  524. 'NOMBRE_ALMACEN' => 'required|string',
  525. 'NOMBRE_RESPONSABLE' => 'required|string',
  526. 'APELLIDO_PATERNO_RESPONSABLE' => 'required|string',
  527. 'APELLIDO_MATERNO_RESPONSABLE' => 'nullable|string',
  528. 'CORREO1' => 'required|string',
  529. 'CORREO2' => 'nullable|string',
  530. 'LADA1' => 'required|string',
  531. 'TELEFONO1' => 'required|string',
  532. 'LADA2' => 'nullable|string',
  533. 'TELEFONO2' => 'nullable|string',
  534. 'CALLE' => 'required|string',
  535. 'NUMERO_EXTERIOR' => 'required|string',
  536. 'NUMERO_INTERIOR' => 'nullable|string',
  537. 'CODIGO_POSTAL' => 'required|string',
  538. 'COLONIA' => 'required|string',
  539. 'LOCALIDAD' => 'nullable|string',
  540. 'MUNICIPIO' => 'required|string',
  541. 'ENTIDAD_FEDERATIVA' => 'required|string',
  542. 'PAIS' => 'required|string',
  543. 'USUARIO' => 'required|string',
  544. 'NUMERO_LINEA' => 'required|integer',
  545. ]);
  546. if ($validator->fails()) {
  547. return $this->responseController->makeResponse(
  548. true,
  549. "ERR_WAREHOUSE_UPD000: Se encontraron uno o más errores.",
  550. $this->responseController->makeErrors($validator->errors()->messages()),
  551. 401
  552. );
  553. }
  554. DB::beginTransaction();
  555. $requestData = $request->all();
  556. try {
  557. $idWarehouse = $this->encController->decrypt($idWarehouse);
  558. } catch (\Throwable $th) {
  559. return $this->responseController->makeResponse(true, "ERR_WAREHOUSE_UPD001: Ocurrió un error al desencriptar el ID del almacen.". $th->getMessage(), 406);
  560. }
  561. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  562. if ($arrResponseCheckUser['error']) {
  563. DB::rollBack();
  564. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_UPD002:'.$arrResponseCheckUser['msg'], [], 401);
  565. }
  566. $user = $arrResponseCheckUser['response'];
  567. $arrResponseCheckAddress = $this->resourcesController->validateAddress(
  568. $requestData['CODIGO_POSTAL'],
  569. $requestData['COLONIA'],
  570. $requestData['MUNICIPIO'],
  571. $requestData['LOCALIDAD'],
  572. $requestData['ENTIDAD_FEDERATIVA'],
  573. $requestData['PAIS'],
  574. $requestData['NUMERO_LINEA'],
  575. );
  576. if ($arrResponseCheckAddress['error']) {
  577. DB::rollBack();
  578. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_UPD003: '.$arrResponseCheckAddress['msg'], $arrResponseCheckAddress['response'], 401);
  579. }
  580. $now = $this->functionsController->now();
  581. $currentDate = $now->toDateTimeString();
  582. try {
  583. $validateUpdate = DB::table('S002V01TALMA')
  584. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  585. ->where('ALMA_COAL', '=', $idWarehouse)
  586. ->update([
  587. 'ALMA_COAL' => $requestData['CODIGO_ALMACEN'],
  588. 'ALMA_NOAL' => $requestData['NOMBRE_ALMACEN'],
  589. 'ALMA_NORE' => $requestData['NOMBRE_RESPONSABLE'],
  590. 'ALMA_APRE' => $requestData['APELLIDO_PATERNO_RESPONSABLE'],
  591. 'ALMA_AMRE' => $requestData['APELLIDO_MATERNO_RESPONSABLE'],
  592. 'ALMA_COR1' => $requestData['CORREO1'],
  593. 'ALMA_COR2' => $requestData['CORREO2'],
  594. 'ALMA_LAD1' => $requestData['LADA1'],
  595. 'ALMA_TEL1' => $requestData['TELEFONO1'],
  596. 'ALMA_LAD2' => $requestData['LADA2'],
  597. 'ALMA_TEL2' => $requestData['TELEFONO2'],
  598. 'ALMA_CALL' => $requestData['CALLE'],
  599. 'ALMA_NUEX' => $requestData['NUMERO_EXTERIOR'],
  600. 'ALMA_NUIN' => $requestData['NUMERO_INTERIOR'],
  601. 'ALMA_COPO' => $requestData['CODIGO_POSTAL'],
  602. 'ALMA_COLO' => $requestData['COLONIA'],
  603. 'ALMA_LOCA' => $requestData['LOCALIDAD'],
  604. 'ALMA_MUNI' => $requestData['MUNICIPIO'],
  605. 'ALMA_ENTI' => $requestData['ENTIDAD_FEDERATIVA'],
  606. 'ALMA_PAIS' => $requestData['PAIS'],
  607. 'ALMA_USMO' => $user,
  608. 'ALMA_FEMO' => $currentDate,
  609. 'ALMA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  610. ]);
  611. } catch (\Throwable $th) {
  612. DB::rollBack();
  613. return $this->responseController->makeResponse(
  614. true,
  615. "ERR_WAREHOUSE_UPD004: Ocurrió un error al insertar el registro del almacen.",
  616. $th->getMessage(),
  617. 500
  618. );
  619. }
  620. if (!$validateUpdate) {
  621. DB::rollBack();
  622. return $this->responseController->makeResponse(
  623. true,
  624. "ERR_WAREHOUSE_UPD005: No se pudo insertar el registro del almacen.",
  625. [],
  626. 500
  627. );
  628. }
  629. DB::commit();
  630. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  631. }
  632. public function deleteWarehouse( Request $request, $idWarehouse ) {
  633. $validator = Validator::make($request->all(), [
  634. 'USUARIO' => 'required|string',
  635. 'NUMERO_LINEA' => 'required|integer',
  636. ]);
  637. if ($validator->fails()) {
  638. return $this->responseController->makeResponse(
  639. true,
  640. "ERR_WAREHOUSE_DEL000: Se encontraron uno o más errores.",
  641. $this->responseController->makeErrors($validator->errors()->messages()),
  642. 401
  643. );
  644. }
  645. DB::beginTransaction();
  646. $requestData = $request->all();
  647. try {
  648. $idWarehouse = $this->encController->decrypt($idWarehouse);
  649. } catch (\Throwable $th) {
  650. DB::rollBack();
  651. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL001: Ocurrió un error al desencriptar el nivel.', $th->getMessage(), 500);
  652. }
  653. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  654. if ($arrResponseCheckUser['error']) {
  655. DB::rollBack();
  656. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL002:'.$arrResponseCheckUser['msg'], [], 401);
  657. }
  658. $user = $arrResponseCheckUser['response'];
  659. try {
  660. $validateExists = DB::table('S002V01TALMA')
  661. ->where('ALMA_COAL', '=', $idWarehouse)
  662. ->where('ALMA_ESTA', '=', 'Activo')
  663. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  664. ->exists();
  665. } catch (\Throwable $th) {
  666. DB::rollBack();
  667. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL003: Ocurrió un error al obtener la información del área.', $th->getMessage(), 500);
  668. }
  669. if (!$validateExists) {
  670. DB::rollBack();
  671. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL004: El almacen no existe.', [], 406);
  672. }
  673. try {
  674. $validateExists = DB::table('S002V01TUBAR')
  675. ->where('UBAR_COAL', '=', $idWarehouse)
  676. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  677. ->where('UBAR_ESTA', '=', 'Activo')
  678. ->exists();
  679. } catch (\Throwable $th) {
  680. DB::rollBack();
  681. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL005: Ocurrió un error al obtener las ubicaciones de los artículos.', $th->getMessage(), 500);
  682. }
  683. if($validateExists) {
  684. DB::rollBack();
  685. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL006: No se puede eliminar debido a que existen artículos ubicados en el almacen.', [], 406);
  686. }
  687. try {
  688. $countArea = DB::table('S002V01TAREA')
  689. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  690. ->where('AREA_COAL', '=', $idWarehouse)
  691. ->where('AREA_ESTA', '=', 'Activo')
  692. ->count();
  693. } catch (\Throwable $th) {
  694. DB::rollBack();
  695. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL007: Ocurrió un error al obtener la información del área.', $th->getMessage(), 500);
  696. }
  697. if ($countArea > 0) {
  698. DB::rollBack();
  699. $quantity = $countArea === 1 ? 'existe 1 área activa' : 'existen'.$countArea.' áreas activas';
  700. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL008: No se puede elminar debido a que '.$quantity.'.', [], 406);
  701. }
  702. try {
  703. $countLevel = DB::table('S002V01TNIVE')
  704. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  705. ->where('NIVE_COAL', '=', $idWarehouse)
  706. ->where('NIVE_ESTA', '=', 'Activo')
  707. ->count();
  708. } catch (\Throwable $th) {
  709. DB::rollBack();
  710. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL009: Ocurrió un error al obtener las zonas.', $th->getMessage(), 500);
  711. }
  712. if ($countLevel > 0) {
  713. DB::rollBack();
  714. $quantity = $countLevel === 1 ? 'existe 1 nivel activo' : 'existen '.$countLevel.' niveles activos';
  715. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL010: No se puede eliminar debido a que '.$quantity.'.', [], 406);
  716. }
  717. try {
  718. $countZones = DB::table('S002V01TZONA')
  719. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  720. ->where('ZONA_COAL', '=', $idWarehouse)
  721. ->where('ZONA_ESTA', '=', 'Activo')
  722. ->count();
  723. } catch (\Throwable $th) {
  724. DB::rollBack();
  725. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL011: Ocurrió un error al obtener las zonas.', $th->getMessage(), 500);
  726. }
  727. if ($countZones > 0) {
  728. DB::rollBack();
  729. $quantity = $countZones === 1 ? 'existe 1 zona activa' : 'existen '.$countZones.' zonas activas';
  730. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL012: No se puede eliminar debido a que '.$quantity.'.', [], 406);
  731. }
  732. $now = $this->functionsController->now();
  733. $currentDate = $now->toDateTimeString();
  734. try {
  735. $validateUpdate = DB::table('S002V01TALMA')
  736. ->where('ALMA_COAL', '=', $idWarehouse)
  737. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  738. ->update([
  739. 'ALMA_ESTA' => 'Eliminado',
  740. 'ALMA_USMO' => $user,
  741. 'ALMA_FEMO' => $currentDate,
  742. 'ALMA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  743. ]);
  744. } catch (\Throwable $th) {
  745. DB::rollBack();
  746. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL013: Ocurrió un error al eliminar el área.', $th->getMessage(), 500);
  747. }
  748. if (!$validateUpdate) {
  749. DB::rollBack();
  750. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_DEL014: No se pudo eliminar el área.', [], 406);
  751. }
  752. DB::commit();
  753. return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
  754. }
  755. public function getAreaByWarehouse($idWarehouse, $user, $line) {
  756. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  757. if ($arrResponseCheckUser['error']) {
  758. DB::rollBack();
  759. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000:'.$arrResponseCheckUser['msg'], [], 401);
  760. }
  761. try {
  762. $idWarehouse = $this->encController->decrypt($idWarehouse);
  763. } catch (\Throwable $th) {
  764. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  765. }
  766. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  767. if ($arrResponseCheckUser['error']) {
  768. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBY001:'.$arrResponseCheckUser['msg'], [], 401);
  769. }
  770. try {
  771. $getArea = DB::table('S002V01TAREA')
  772. ->where('AREA_COAL', '=', $idWarehouse)
  773. ->where('AREA_NULI', '=', $line)
  774. ->get([
  775. 'AREA_COAR AS CODIGO_AREA',
  776. 'AREA_NOAR AS NOMBRE_AREA',
  777. 'AREA_COME AS COMENTARIOS',
  778. 'AREA_ESTA AS ESTADO',
  779. 'AREA_USRE AS USUARIO_REGISTRA',
  780. 'AREA_FERE AS FECHA_REGISTRA',
  781. 'AREA_USMO AS USUARIO_MODIFICA',
  782. 'AREA_FEMO AS FECHA_MODIFICA',
  783. ]);
  784. $arrArea = json_decode(json_encode($getArea), true);
  785. } catch (\Throwable $th) {
  786. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBY002: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  787. }
  788. foreach ($arrArea as $key => $value) {
  789. try {
  790. $countStock = DB::table('S002V01TUBAR')
  791. ->where('UBAR_NULI', '=', $line)
  792. ->where('UBAR_ESTA', '=', 'Activo')
  793. ->where('UBAR_COAL', '=', $idWarehouse)
  794. ->where('UBAR_COAR', '=', $value['CODIGO_AREA'])
  795. ->count();
  796. } catch (\Throwable $th) {
  797. DB::rollBack();
  798. return $this->responseController->makeResponse(
  799. true,
  800. "ERR_WAREHOUSE_GET003: Ocurrió un error al obtener los almacenes.",
  801. $th->getMessage(),
  802. 500
  803. );
  804. }
  805. $value['CANTIDAD_STOCK'] = $countStock;
  806. $arrArea[$key] = $value;
  807. }
  808. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrArea, $line);
  809. if ($responseCheckLatestUpdate['error']) {
  810. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  811. }
  812. $arrArea = $responseCheckLatestUpdate['response'];
  813. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrArea);
  814. }
  815. public function getAreaById($idArea, $user, $line) {
  816. try {
  817. $idArea = $this->encController->decrypt($idArea);
  818. } catch (\Throwable $th) {
  819. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  820. }
  821. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  822. if ($arrResponseCheckUser['error']) {
  823. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBY001:'.$arrResponseCheckUser['msg'], [], 401);
  824. }
  825. try {
  826. $getArea = (array) DB::table('S002V01TAREA')
  827. ->where('AREA_COAR', '=', $idArea)
  828. ->where('AREA_NULI', '=', $line)
  829. ->first([
  830. 'AREA_NOAR AS NOMBRE_AREA',
  831. 'AREA_COME AS COMENTARIOS',
  832. 'AREA_ESTA AS ESTADO',
  833. 'AREA_USRE AS USUARIO_REGISTRA',
  834. 'AREA_FERE AS FECHA_REGISTRA',
  835. 'AREA_USMO AS USUARIO_MODIFICA',
  836. 'AREA_FEMO AS FECHA_MODIFICA',
  837. ]);
  838. $arrArea = json_decode(json_encode($getArea), true);
  839. } catch (\Throwable $th) {
  840. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBY002: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  841. }
  842. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrArea);
  843. }
  844. public function getAreaByWarehouseActives($idWarehouse, $user, $line) {
  845. try {
  846. $idWarehouse = $this->encController->decrypt($idWarehouse);
  847. } catch (\Throwable $th) {
  848. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBYACTIVE000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  849. }
  850. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  851. if ($arrResponseCheckUser['error']) {
  852. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBYACTIVE001:'.$arrResponseCheckUser['msg'], [], 401);
  853. }
  854. try {
  855. $validateExists = DB::table('S002V01TALMA')
  856. ->where('ALMA_NULI', '=', $line)
  857. ->where('ALMA_COAL', '=', $idWarehouse)
  858. ->exists();
  859. } catch (\Throwable $th) {
  860. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBYACTIVE002: Ocurrió un error al obtener el almacen.', $th->getMessage(), 406);
  861. }
  862. if (!$validateExists) {
  863. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBYACTIVE003: El almacen no existe.', [], 401);
  864. }
  865. try {
  866. $getArea = DB::table('S002V01TAREA')
  867. ->where('AREA_COAL', '=', $idWarehouse)
  868. ->where('AREA_NULI', '=', $line)
  869. ->where('AREA_ESTA', '=', 'Activo')
  870. ->get([
  871. 'AREA_COAR AS CODIGO_AREA',
  872. 'AREA_NOAR AS NOMBRE_AREA',
  873. 'AREA_COME AS COMENTARIOS',
  874. ]);
  875. $arrArea = json_decode(json_encode($getArea), true);
  876. } catch (\Throwable $th) {
  877. return $this->responseController->makeResponse(true, 'ERR_AREA_GETBYACTIVE004: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  878. }
  879. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrArea);
  880. }
  881. public function registerArea(Request $request) {
  882. $validator = Validator::make($request->all(), [
  883. 'CODIGO_ALMACEN' => 'required|string',
  884. 'CODIGO_AREA' => 'required|string',
  885. 'NOMBRE_AREA' => 'required|string',
  886. 'COMENTARIOS' => 'nullable|string',
  887. 'USUARIO' => 'required|string',
  888. 'NUMERO_LINEA' => 'required|integer',
  889. ]);
  890. if ($validator->fails()) {
  891. return $this->responseController->makeResponse(
  892. true,
  893. "ERR_AREA_REG000: Se encontraron uno o más errores.",
  894. $this->responseController->makeErrors($validator->errors()->messages()),
  895. 401
  896. );
  897. }
  898. DB::beginTransaction();
  899. $requestData = $request->all();
  900. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  901. if ($arrResponseCheckUser['error']) {
  902. return $this->responseController->makeResponse(true, 'ERR_AREA_REG001:'.$arrResponseCheckUser['msg'], [], 401);
  903. }
  904. $user = $arrResponseCheckUser['response'];
  905. try {
  906. $validateExistWarehouse = DB::table('S002V01TALMA')
  907. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  908. ->where('ALMA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  909. ->where('ALMA_ESTA', '=', 'Activo')
  910. ->exists();
  911. } catch (\Throwable $th) {
  912. DB::rollBack();
  913. return $this->responseController->makeResponse(true, 'ERR_AREA_REG002: Ocurrió un error al verificar el almacen.', $th->getMessage(), 500);
  914. }
  915. if (!$validateExistWarehouse) {
  916. DB::rollBack();
  917. return $this->responseController->makeResponse(true, 'ERR_AREA_REG003: El almacen no existe.', [], 406);
  918. }
  919. try {
  920. $validateExistCode = DB::table('S002V01TAREA')
  921. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  922. ->where('AREA_COAR', '=', $requestData['CODIGO_AREA'])
  923. ->where('AREA_ESTA', '=', 'Activo')
  924. ->exists();
  925. } catch (\Throwable $th) {
  926. DB::rollBack();
  927. return $this->responseController->makeResponse(true, 'ERR_AREA_REG004: Ocurrió un error al verificar el código del área.', $th->getMessage(), 500);
  928. }
  929. if ($validateExistCode) {
  930. DB::rollBack();
  931. return $this->responseController->makeResponse(true, 'ERR_AREA_REG005: El código del área ya se encuentra registrado.', [], 406);
  932. }
  933. $now = $this->functionsController->now();
  934. $currentDate = $now->toDateTimeString();
  935. try {
  936. $validateInsert = DB::table('S002V01TAREA')->insert([
  937. 'AREA_COAL' => $requestData['CODIGO_ALMACEN'],
  938. 'AREA_COAR' => $requestData['CODIGO_AREA'],
  939. 'AREA_NOAR' => $requestData['NOMBRE_AREA'],
  940. 'AREA_COME' => $requestData['COMENTARIOS'],
  941. 'AREA_NULI' => $requestData['NUMERO_LINEA'],
  942. 'AREA_USRE' => $user,
  943. 'AREA_FERE' => $currentDate,
  944. 'AREA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  945. ]);
  946. } catch (\Throwable $th) {
  947. DB::rollBack();
  948. return $this->responseController->makeResponse(true, 'ERR_AREA_REG006: Ocurrió un error al ingresar la información a la base de datos.', $th->getMessage(), 500);
  949. }
  950. if (!$validateInsert) {
  951. DB::rollBack();
  952. return $this->responseController->makeResponse(true, 'ERR_AREA_REG007: No se pudo guardar la información en la base de datos.', [], 406);
  953. }
  954. DB::commit();
  955. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  956. }
  957. public function updateArea(Request $request, $idArea) {
  958. $validator = Validator::make($request->all(), [
  959. 'CODIGO_ALMACEN' => 'required|string',
  960. 'NOMBRE_AREA' => 'required|string',
  961. 'COMENTARIOS' => 'nullable|string',
  962. 'USUARIO' => 'required|string',
  963. 'NUMERO_LINEA' => 'required|integer',
  964. ]);
  965. if ($validator->fails()) {
  966. return $this->responseController->makeResponse(
  967. true,
  968. "ERR_AREA_UPD000: Se encontraron uno o más errores.",
  969. $this->responseController->makeErrors($validator->errors()->messages()),
  970. 401
  971. );
  972. }
  973. DB::beginTransaction();
  974. $requestData = $request->all();
  975. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  976. if ($arrResponseCheckUser['error']) {
  977. DB::rollBack();
  978. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD001:'.$arrResponseCheckUser['msg'], $arrResponseCheckUser['response'], 401);
  979. }
  980. $user = $arrResponseCheckUser['response'];
  981. try {
  982. $idArea = $this->encController->decrypt($idArea);
  983. } catch (\Throwable $th) {
  984. DB::rollBack();
  985. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD002: Ocurrió un error al desencriptar el área.', $th->getMessage(), 500);
  986. }
  987. try {
  988. $validateExistArea = DB::table('S002V01TAREA')
  989. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  990. ->where('AREA_COAR', '=', $idArea)
  991. ->where('AREA_ESTA', '=', 'Activo')
  992. ->exists();
  993. } catch (\Throwable $th) {
  994. DB::rollBack();
  995. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD003: Ocurrió un error al verificar el código del área.', $th->getMessage(), 500);
  996. }
  997. if (!$validateExistArea) {
  998. DB::rollBack();
  999. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD004: El área no existe.', [], 406);
  1000. }
  1001. try {
  1002. $validateExistWarehouse = DB::table('S002V01TALMA')
  1003. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  1004. ->where('ALMA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1005. ->where('ALMA_ESTA', '=', 'Activo')
  1006. ->exists();
  1007. } catch (\Throwable $th) {
  1008. DB::rollBack();
  1009. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD005: Ocurrió un error al verificar el almacen.', $th->getMessage(), 500);
  1010. }
  1011. if (!$validateExistWarehouse) {
  1012. DB::rollBack();
  1013. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD006: El almacen no existe.', [], 406);
  1014. }
  1015. $now = $this->functionsController->now();
  1016. $currentDate = $now->toDateTimeString();
  1017. try {
  1018. $validateUpdate = DB::table('S002V01TAREA')
  1019. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1020. ->where('AREA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1021. ->where('AREA_COAR', '=', $idArea)
  1022. ->update([
  1023. 'AREA_NOAR' => $requestData['NOMBRE_AREA'],
  1024. 'AREA_COME' => $requestData['COMENTARIOS'],
  1025. 'AREA_USMO' => $user,
  1026. 'AREA_FEMO' => $currentDate,
  1027. 'AREA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1028. ]);
  1029. } catch (\Throwable $th) {
  1030. DB::rollBack();
  1031. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD009: Ocurrió un error al ingresar la información a la base de datos.', $th->getMessage(), 500);
  1032. }
  1033. if (!$validateUpdate) {
  1034. DB::rollBack();
  1035. return $this->responseController->makeResponse(true, 'ERR_AREA_UPD010: No se pudo guardar la información en la base de datos.', [], 406);
  1036. }
  1037. DB::commit();
  1038. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  1039. }
  1040. public function deleteArea(Request $request, $idArea) {
  1041. $validator = Validator::make($request->all(), [
  1042. 'USUARIO' => 'required|string',
  1043. 'NUMERO_LINEA' => 'required|integer',
  1044. ]);
  1045. if ($validator->fails()) {
  1046. return $this->responseController->makeResponse(
  1047. true,
  1048. "ERR_AREA_DEL000: Se encontraron uno o más errores.",
  1049. $this->responseController->makeErrors($validator->errors()->messages()),
  1050. 401
  1051. );
  1052. }
  1053. DB::beginTransaction();
  1054. $requestData = $request->all();
  1055. try {
  1056. $idArea = $this->encController->decrypt($idArea);
  1057. } catch (\Throwable $th) {
  1058. DB::rollBack();
  1059. return $this->responseController->makeResponse(true, 'ERR_AREA_DEL001: Ocurrió un error al desencriptar el nivel.', $th->getMessage(), 500);
  1060. }
  1061. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  1062. if ($arrResponseCheckUser['error']) {
  1063. DB::rollBack();
  1064. return $this->responseController->makeResponse(true, 'ERR_AREA_DEL002:'.$arrResponseCheckUser['msg'], [], 401);
  1065. }
  1066. $user = $arrResponseCheckUser['response'];
  1067. try {
  1068. $arrArea = (array) DB::table('S002V01TAREA')
  1069. ->where('AREA_COAR', '=', $idArea)
  1070. ->where('AREA_ESTA', '=', 'Activo')
  1071. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1072. ->first([
  1073. 'AREA_COAL',
  1074. ]);
  1075. } catch (\Throwable $th) {
  1076. DB::rollBack();
  1077. return $this->responseController->makeResponse(true, 'ERR_AREA_DEL003: Ocurrió un error al obtener la información del área.', $th->getMessage(), 500);
  1078. }
  1079. if (empty($arrArea)) {
  1080. DB::rollBack();
  1081. return $this->responseController->makeResponse(true, 'ERR_AREA_DEL004: El área no existe.', [], 406);
  1082. }
  1083. try {
  1084. $validateExists = DB::table('S002V01TUBAR')
  1085. ->where('UBAR_COAL', '=', $arrArea['AREA_COAL'])
  1086. ->where('UBAR_COZO', '=', $idArea)
  1087. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  1088. ->where('UBAR_ESTA', '=', 'Activo')
  1089. ->exists();
  1090. } catch (\Throwable $th) {
  1091. DB::rollBack();
  1092. return $this->responseController->makeResponse(true, 'ERR_AREA_DEL005: Ocurrió un error al obtener las ubicaciones de los artículos.', $th->getMessage(), 500);
  1093. }
  1094. if($validateExists) {
  1095. DB::rollBack();
  1096. return $this->responseController->makeResponse(true, 'ERR_AREA_DEL006: No se puede eliminar debido a que existen artículos ubicados en el área.', [], 406);
  1097. }
  1098. try {
  1099. $countLevel = DB::table('S002V01TNIVE')
  1100. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1101. ->where('NIVE_COAL', '=', $arrArea['AREA_COAL'])
  1102. ->where('NIVE_COAR', '=', $idArea)
  1103. ->where('NIVE_ESTA', '=', 'Activo')
  1104. ->count();
  1105. } catch (\Throwable $th) {
  1106. DB::rollBack();
  1107. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL007: Ocurrió un error al obtener las zonas.', $th->getMessage(), 500);
  1108. }
  1109. if ($countLevel > 0) {
  1110. DB::rollBack();
  1111. $quantity = $countLevel === 1 ? 'existe 1 nivel activo' : 'existen '.$countLevel.' niveles activos';
  1112. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL008: No se puede eliminar debido a que '.$quantity.'.', [], 406);
  1113. }
  1114. try {
  1115. $countZones = DB::table('S002V01TZONA')
  1116. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  1117. ->where('ZONA_COAL', '=', $arrArea['AREA_COAL'])
  1118. ->where('ZONA_COAR', '=', $idArea)
  1119. ->where('ZONA_ESTA', '=', 'Activo')
  1120. ->count();
  1121. } catch (\Throwable $th) {
  1122. DB::rollBack();
  1123. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL009: Ocurrió un error al obtener las zonas.', $th->getMessage(), 500);
  1124. }
  1125. if ($countZones > 0) {
  1126. DB::rollBack();
  1127. $quantity = $countZones === 1 ? 'existe 1 zona activa' : 'existen '.$countZones.' zonas activas';
  1128. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL010: No se puede eliminar debido a que '.$quantity.'.', [], 406);
  1129. }
  1130. $now = $this->functionsController->now();
  1131. $currentDate = $now->toDateTimeString();
  1132. try {
  1133. $validateUpdate = DB::table('S002V01TAREA')
  1134. ->where('AREA_COAR', '=', $idArea)
  1135. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1136. ->update([
  1137. 'AREA_ESTA' => 'Eliminado',
  1138. 'AREA_USMO' => $user,
  1139. 'AREA_FEMO' => $currentDate,
  1140. 'AREA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1141. ]);
  1142. } catch (\Throwable $th) {
  1143. DB::rollBack();
  1144. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL011: Ocurrió un error al eliminar el área.', $th->getMessage(), 500);
  1145. }
  1146. if (!$validateUpdate) {
  1147. DB::rollBack();
  1148. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL012: No se pudo eliminar el área.', [], 406);
  1149. }
  1150. DB::commit();
  1151. return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
  1152. }
  1153. public function getLevelByAreaWarehouse($idWarehouse, $idArea, $user, $line) {
  1154. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1155. if ($arrResponseCheckUser['error']) {
  1156. DB::rollBack();
  1157. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000:'.$arrResponseCheckUser['msg'], [], 401);
  1158. }
  1159. try {
  1160. $idWarehouse = $this->encController->decrypt($idWarehouse);
  1161. } catch (\Throwable $th) {
  1162. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  1163. }
  1164. try {
  1165. $idArea = $this->encController->decrypt($idArea);
  1166. } catch (\Throwable $th) {
  1167. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY001: Ocurrió un error al desencriptar el ID del área', $th->getMessage(), 406);
  1168. }
  1169. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1170. if ($arrResponseCheckUser['error']) {
  1171. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY002:'.$arrResponseCheckUser['msg'], [], 401);
  1172. }
  1173. try {
  1174. $getLevel = DB::table('S002V01TNIVE')
  1175. ->where('NIVE_COAL', '=', $idWarehouse)
  1176. ->where('NIVE_COAR', '=', $idArea)
  1177. ->where('NIVE_NULI', '=', $line)
  1178. ->get([
  1179. 'NIVE_CONI AS CODIGO_NIVEL',
  1180. 'NIVE_NONI AS NOMBRE_NIVEL',
  1181. 'NIVE_COME AS COMENTARIOS',
  1182. 'NIVE_ESTA AS ESTADO',
  1183. 'NIVE_USRE AS USUARIO_REGISTRA',
  1184. 'NIVE_FERE AS FECHA_REGISTRA',
  1185. 'NIVE_USMO AS USUARIO_MODIFICA',
  1186. 'NIVE_FEMO AS FECHA_MODIFICA',
  1187. ]);
  1188. $arrLevel = json_decode(json_encode($getLevel), true);
  1189. } catch (\Throwable $th) {
  1190. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY003: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  1191. }
  1192. foreach ($arrLevel as $key => $value) {
  1193. try {
  1194. $countStock = DB::table('S002V01TUBAR')
  1195. ->where('UBAR_NULI', '=', $line)
  1196. ->where('UBAR_ESTA', '=', 'Activo')
  1197. ->where('UBAR_COAL', '=', $idWarehouse)
  1198. ->where('UBAR_COAR', '=', $idArea)
  1199. ->where('UBAR_CONI', '=', $value['CODIGO_NIVEL'])
  1200. ->count();
  1201. } catch (\Throwable $th) {
  1202. DB::rollBack();
  1203. return $this->responseController->makeResponse(
  1204. true,
  1205. "ERR_WAREHOUSE_GET003: Ocurrió un error al obtener los almacenes.",
  1206. $th->getMessage(),
  1207. 500
  1208. );
  1209. }
  1210. $value['CANTIDAD_STOCK'] = $countStock;
  1211. $arrLevel[$key] = $value;
  1212. }
  1213. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrLevel, $line);
  1214. if ($responseCheckLatestUpdate['error']) {
  1215. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  1216. }
  1217. $arrLevel = $responseCheckLatestUpdate['response'];
  1218. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrLevel);
  1219. }
  1220. public function getLevelById( $idLevel, $user, $line ) {
  1221. try {
  1222. $idLevel = $this->encController->decrypt($idLevel);
  1223. } catch (\Throwable $th) {
  1224. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  1225. }
  1226. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1227. if ($arrResponseCheckUser['error']) {
  1228. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY001:'.$arrResponseCheckUser['msg'], [], 401);
  1229. }
  1230. try {
  1231. $getLevel = (array) DB::table('S002V01TNIVE')
  1232. ->where('NIVE_CONI', '=', $idLevel)
  1233. ->where('NIVE_NULI', '=', $line)
  1234. ->first([
  1235. 'NIVE_NONI AS NOMBRE_NIVEL',
  1236. 'NIVE_COME AS COMENTARIOS',
  1237. 'NIVE_ESTA AS ESTADO',
  1238. 'NIVE_USRE AS USUARIO_REGISTRA',
  1239. 'NIVE_FERE AS FECHA_REGISTRA',
  1240. 'NIVE_USMO AS USUARIO_MODIFICA',
  1241. 'NIVE_FEMO AS FECHA_MODIFICA',
  1242. ]);
  1243. $arrLevel = json_decode(json_encode($getLevel), true);
  1244. } catch (\Throwable $th) {
  1245. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBY002: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  1246. }
  1247. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrLevel);
  1248. }
  1249. public function getLevelByAreaWarehouseActives($idWarehouse, $idArea, $user, $line) {
  1250. try {
  1251. $idWarehouse = $this->encController->decrypt($idWarehouse);
  1252. } catch (\Throwable $th) {
  1253. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  1254. }
  1255. try {
  1256. $idArea = $this->encController->decrypt($idArea);
  1257. } catch (\Throwable $th) {
  1258. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE001: Ocurrió un error al desencriptar el ID del área', $th->getMessage(), 406);
  1259. }
  1260. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1261. if ($arrResponseCheckUser['error']) {
  1262. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE002:'.$arrResponseCheckUser['msg'], [], 401);
  1263. }
  1264. try {
  1265. $validateExists = DB::table('S002V01TALMA')
  1266. ->where('ALMA_NULI', '=', $line)
  1267. ->where('ALMA_COAL', '=', $idWarehouse)
  1268. ->exists();
  1269. } catch (\Throwable $th) {
  1270. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE003: Ocurrió un error al obtener el almacen.', $th->getMessage(), 406);
  1271. }
  1272. if (!$validateExists) {
  1273. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE004: El almacen no existe.', [], 401);
  1274. }
  1275. try {
  1276. $validateExists = DB::table('S002V01TAREA')
  1277. ->where('AREA_NULI', '=', $line)
  1278. ->where('AREA_COAL', '=', $idWarehouse)
  1279. ->where('AREA_COAR', '=', $idArea)
  1280. ->exists();
  1281. } catch (\Throwable $th) {
  1282. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE005: Ocurrió un error al obtener el área.', $th->getMessage(), 406);
  1283. }
  1284. if (!$validateExists) {
  1285. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE006: El área no existe.', [], 401);
  1286. }
  1287. try {
  1288. $getLevel = DB::table('S002V01TNIVE')
  1289. ->where('NIVE_COAL', '=', $idWarehouse)
  1290. ->where('NIVE_COAR', '=', $idArea)
  1291. ->where('NIVE_NULI', '=', $line)
  1292. ->where('NIVE_ESTA', '=', 'Activo')
  1293. ->get([
  1294. 'NIVE_CONI AS CODIGO_NIVEL',
  1295. 'NIVE_NONI AS NOMBRE_NIVEL',
  1296. 'NIVE_COME AS COMENTARIOS',
  1297. ]);
  1298. $arrLevel = json_decode(json_encode($getLevel), true);
  1299. } catch (\Throwable $th) {
  1300. return $this->responseController->makeResponse(true, 'ERR_LEVEL_GETBYACTIVE007: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  1301. }
  1302. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrLevel);
  1303. }
  1304. public function registerLevel(Request $request) {
  1305. $validator = Validator::make($request->all(), [
  1306. 'CODIGO_ALMACEN' => 'required|string',
  1307. 'CODIGO_AREA' => 'required|string',
  1308. 'CODIGO_NIVEL' => 'required|string',
  1309. 'NOMBRE_NIVEL' => 'required|string',
  1310. 'COMENTARIOS' => 'nullable|string',
  1311. 'USUARIO' => 'required|string',
  1312. 'NUMERO_LINEA' => 'required|integer',
  1313. ]);
  1314. if ($validator->fails()) {
  1315. return $this->responseController->makeResponse(
  1316. true,
  1317. "ERR_LEVEL_REG000: Se encontraron uno o más errores.",
  1318. $this->responseController->makeErrors($validator->errors()->messages()),
  1319. 401
  1320. );
  1321. }
  1322. DB::beginTransaction();
  1323. $requestData = $request->all();
  1324. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  1325. if ($arrResponseCheckUser['error']) {
  1326. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG001:'.$arrResponseCheckUser['msg'], [], 401);
  1327. }
  1328. $user = $arrResponseCheckUser['response'];
  1329. try {
  1330. $validateExistWarehouse = DB::table('S002V01TALMA')
  1331. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  1332. ->where('ALMA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1333. ->where('ALMA_ESTA', '=', 'Activo')
  1334. ->exists();
  1335. } catch (\Throwable $th) {
  1336. DB::rollBack();
  1337. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG002: Ocurrió un error al verificar el almacen.', $th->getMessage(), 500);
  1338. }
  1339. if (!$validateExistWarehouse) {
  1340. DB::rollBack();
  1341. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG003: El almacen no existe.', [], 406);
  1342. }
  1343. try {
  1344. $validateExistArea = DB::table('S002V01TAREA')
  1345. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1346. ->where('AREA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1347. ->where('AREA_COAR', '=', $requestData['CODIGO_AREA'])
  1348. ->where('AREA_ESTA', '=', 'Activo')
  1349. ->exists();
  1350. } catch (\Throwable $th) {
  1351. DB::rollBack();
  1352. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG004: Ocurrió un error al verificar el área.', $th->getMessage(), 500);
  1353. }
  1354. if (!$validateExistArea) {
  1355. DB::rollBack();
  1356. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG005: El área no existe.', [], 406);
  1357. }
  1358. try {
  1359. $validateExistLevel = DB::table('S002V01TNIVE')
  1360. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1361. ->where('NIVE_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1362. ->where('NIVE_COAR', '=', $requestData['CODIGO_AREA'])
  1363. ->where('NIVE_CONI', '=', $requestData['CODIGO_NIVEL'])
  1364. ->exists();
  1365. } catch (\Throwable $th) {
  1366. DB::rollBack();
  1367. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG006: Ocurrió un error al verificar el código del nivel.', $th->getMessage(), 406);
  1368. }
  1369. if ($validateExistLevel) {
  1370. DB::rollBack();
  1371. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG007: El código del nivel ya existe.', [], 406);
  1372. }
  1373. $now = $this->functionsController->now();
  1374. $currentDate = $now->toDateTimeString();
  1375. try {
  1376. $validateInsert = DB::table('S002V01TNIVE')->insert([
  1377. 'NIVE_NULI' => $requestData['NUMERO_LINEA'],
  1378. 'NIVE_COAL' => $requestData['CODIGO_ALMACEN'],
  1379. 'NIVE_COAR' => $requestData['CODIGO_AREA'],
  1380. 'NIVE_CONI' => $requestData['CODIGO_NIVEL'],
  1381. 'NIVE_NONI' => $requestData['NOMBRE_NIVEL'],
  1382. 'NIVE_COME' => $requestData['COMENTARIOS'],
  1383. 'NIVE_USRE' => $user,
  1384. 'NIVE_FERE' => $currentDate,
  1385. 'NIVE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  1386. ]);
  1387. } catch (\Throwable $th) {
  1388. DB::rollBack();
  1389. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG008: Ocurrió un error al ingresar la información a la base de datos.', $th->getMessage(), 500);
  1390. }
  1391. if (!$validateInsert) {
  1392. DB::rollBack();
  1393. return $this->responseController->makeResponse(true, 'ERR_LEVEL_REG009: No se pudo guardar la información en la base de datos.', [], 406);
  1394. }
  1395. DB::commit();
  1396. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  1397. }
  1398. public function updateLevel(Request $request, $idLevel) {
  1399. $validator = Validator::make($request->all(), [
  1400. 'CODIGO_ALMACEN' => 'required|string',
  1401. 'NOMBRE_NIVEL' => 'required|string',
  1402. 'COMENTARIOS' => 'nullable|string',
  1403. 'USUARIO' => 'required|string',
  1404. 'NUMERO_LINEA' => 'required|integer',
  1405. ]);
  1406. if ($validator->fails()) {
  1407. return $this->responseController->makeResponse(
  1408. true,
  1409. "ERR_LEVEL_UPD000: Se encontraron uno o más errores.",
  1410. $this->responseController->makeErrors($validator->errors()->messages()),
  1411. 401
  1412. );
  1413. }
  1414. DB::beginTransaction();
  1415. $requestData = $request->all();
  1416. try {
  1417. $idLevel = $this->encController->decrypt($idLevel);
  1418. } catch (\Throwable $th) {
  1419. DB::rollBack();
  1420. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD001: Ocurrió un error al desencriptar el área.', $th->getMessage(), 500);
  1421. }
  1422. try {
  1423. $validateExistLevel = DB::table('S002V01TNIVE')
  1424. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1425. ->where('NIVE_CONI', '=', $idLevel)
  1426. ->where('NIVE_ESTA', '=', 'Activo')
  1427. ->exists();
  1428. } catch (\Throwable $th) {
  1429. DB::rollBack();
  1430. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD002: Ocurrió un error al verificar el código del área.', $th->getMessage(), 500);
  1431. }
  1432. if (!$validateExistLevel) {
  1433. DB::rollBack();
  1434. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD003: El área no existe.', [], 406);
  1435. }
  1436. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  1437. if ($arrResponseCheckUser['error']) {
  1438. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD004:'.$arrResponseCheckUser['msg'], [], 401);
  1439. }
  1440. $user = $arrResponseCheckUser['response'];
  1441. try {
  1442. $validateExistWarehouse = DB::table('S002V01TALMA')
  1443. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  1444. ->where('ALMA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1445. ->where('ALMA_ESTA', '=', 'Activo')
  1446. ->exists();
  1447. } catch (\Throwable $th) {
  1448. DB::rollBack();
  1449. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD005: Ocurrió un error al verificar el almacen.', $th->getMessage(), 500);
  1450. }
  1451. if (!$validateExistWarehouse) {
  1452. DB::rollBack();
  1453. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD006: El almacen no existe.', [], 406);
  1454. }
  1455. try {
  1456. $validateExistArea = DB::table('S002V01TAREA')
  1457. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1458. ->where('AREA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1459. ->where('AREA_COAR', '=', $requestData['CODIGO_AREA'])
  1460. ->where('AREA_ESTA', '=', 'Activo')
  1461. ->exists();
  1462. } catch (\Throwable $th) {
  1463. DB::rollBack();
  1464. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD007: Ocurrió un error al verificar el área.', $th->getMessage(), 500);
  1465. }
  1466. if (!$validateExistArea) {
  1467. DB::rollBack();
  1468. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD008: El área no existe.', [], 406);
  1469. }
  1470. try {
  1471. $validateExistLevel = DB::table('S002V01TNIVE')
  1472. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1473. ->where('NIVE_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1474. ->where('NIVE_COAR', '=', $requestData['CODIGO_AREA'])
  1475. ->where('NIVE_CONI', '=', $requestData['CODIGO_NIVEL'])
  1476. ->exists();
  1477. } catch (\Throwable $th) {
  1478. DB::rollBack();
  1479. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD009: Ocurrió un error al verificar el código del nivel.', $th->getMessage(), 406);
  1480. }
  1481. if ($validateExistLevel) {
  1482. DB::rollBack();
  1483. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD010: El código del nivel ya existe.', [], 406);
  1484. }
  1485. $now = $this->functionsController->now();
  1486. $currentDate = $now->toDateTimeString();
  1487. try {
  1488. $validateUpdate = DB::table('S002V01TNIVE')
  1489. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1490. ->where('NIVE_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1491. ->where('NIVE_COAR', '=', $requestData['CODIGO_AREA'])
  1492. ->where('NIVE_CONI', '=', $idLevel)
  1493. ->update([
  1494. 'NIVE_NONI' => $requestData['NOMBRE_NIVEL'],
  1495. 'NIVE_COME' => $requestData['COMENTARIOS'],
  1496. 'NIVE_USMO' => $user,
  1497. 'NIVE_FEMO' => $currentDate,
  1498. 'NIVE_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  1499. ]);
  1500. } catch (\Throwable $th) {
  1501. DB::rollBack();
  1502. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD011: Ocurrió un error al ingresar la información a la base de datos.', $th->getMessage(), 500);
  1503. }
  1504. if (!$validateUpdate) {
  1505. DB::rollBack();
  1506. return $this->responseController->makeResponse(true, 'ERR_LEVEL_UPD012: No se pudo guardar la información en la base de datos.', [], 406);
  1507. }
  1508. DB::commit();
  1509. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  1510. }
  1511. public function deleteLevel(Request $request, $idLevel) {
  1512. $validator = Validator::make($request->all(), [
  1513. 'USUARIO' => 'required|string',
  1514. 'NUMERO_LINEA' => 'required|integer',
  1515. ]);
  1516. if ($validator->fails()) {
  1517. return $this->responseController->makeResponse(
  1518. true,
  1519. "ERR_LEVEL_DEL000: Se encontraron uno o más errores.",
  1520. $this->responseController->makeErrors($validator->errors()->messages()),
  1521. 401
  1522. );
  1523. }
  1524. DB::beginTransaction();
  1525. $requestData = $request->all();
  1526. try {
  1527. $idLevel = $this->encController->decrypt($idLevel);
  1528. } catch (\Throwable $th) {
  1529. DB::rollBack();
  1530. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL001: Ocurrió un error al desencriptar el nivel.', $th->getMessage(), 500);
  1531. }
  1532. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  1533. if ($arrResponseCheckUser['error']) {
  1534. DB::rollBack();
  1535. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL002:'.$arrResponseCheckUser['msg'], [], 401);
  1536. }
  1537. $user = $arrResponseCheckUser['response'];
  1538. try {
  1539. $arrLevel = (array) DB::table('S002V01TNIVE')
  1540. ->where('NIVE_CONI', '=', $idLevel)
  1541. ->where('NIVE_ESTA', '=', 'Activo')
  1542. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1543. ->first([
  1544. 'NIVE_COAL',
  1545. 'NIVE_COAR'
  1546. ]);
  1547. } catch (\Throwable $th) {
  1548. DB::rollBack();
  1549. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL003: Ocurrió un error al obtener la información del nivel.', $th->getMessage(), 500);
  1550. }
  1551. if (empty($arrLevel)) {
  1552. DB::rollBack();
  1553. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL004: El nivel no existe.', [], 406);
  1554. }
  1555. try {
  1556. $validateExists = DB::table('S002V01TUBAR')
  1557. ->where('UBAR_COAL', '=', $arrLevel['NIVE_COAL'])
  1558. ->where('UBAR_COAR', '=', $arrLevel['NIVE_COAR'])
  1559. ->where('UBAR_COZO', '=', $idLevel)
  1560. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  1561. ->where('UBAR_ESTA', '=', 'Activo')
  1562. ->exists();
  1563. } catch (\Throwable $th) {
  1564. DB::rollBack();
  1565. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL005: Ocurrió un error al obtener las ubicaciones de los artículos.', $th->getMessage(), 500);
  1566. }
  1567. if($validateExists) {
  1568. DB::rollBack();
  1569. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL006: No se puede eliminar debido a que existen artículos ubicados en el nivel.', [], 406);
  1570. }
  1571. try {
  1572. $countZones = DB::table('S002V01TZONA')
  1573. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  1574. ->where('ZONA_COAL', '=', $arrLevel['NIVE_COAL'])
  1575. ->where('ZONA_COAR', '=', $arrLevel['NIVE_COAR'])
  1576. ->where('ZONA_CONI', '=', $idLevel)
  1577. ->where('ZONA_ESTA', '=', 'Activo')
  1578. ->count();
  1579. } catch (\Throwable $th) {
  1580. DB::rollBack();
  1581. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL007: Ocurrió un error al obtener las zonas.', $th->getMessage(), 500);
  1582. }
  1583. if ($countZones > 0) {
  1584. DB::rollBack();
  1585. $quantity = $countZones === 1 ? 'existe 1 zona activa' : 'existen '.$countZones.' zonas activas';
  1586. return $this->responseController->makeResponse(true, 'ERR_LEVEL_DEL008: No se puede eliminar debido a que '.$quantity.'.', [], 406);
  1587. }
  1588. $now = $this->functionsController->now();
  1589. $currentDate = $now->toDateTimeString();
  1590. try {
  1591. $validateUpdate = DB::table('S002V01TNIVE')
  1592. ->where('NIVE_CONI', '=', $idLevel)
  1593. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1594. ->update([
  1595. 'NIVE_ESTA' => 'Eliminado',
  1596. 'NIVE_USMO' => $user,
  1597. 'NIVE_FEMO' => $currentDate,
  1598. 'NIVE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1599. ]);
  1600. } catch (\Throwable $th) {
  1601. DB::rollBack();
  1602. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL009: Ocurrió un error al eliminar el nivel.', $th->getMessage(), 500);
  1603. }
  1604. if (!$validateUpdate) {
  1605. DB::rollBack();
  1606. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL010: No se pudo eliminar el nivel.', [], 406);
  1607. }
  1608. DB::commit();
  1609. return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
  1610. }
  1611. public function getZoneByLevelAreaWarehouse($idWarehouse, $idArea, $idLevel, $user, $line) {
  1612. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1613. if ($arrResponseCheckUser['error']) {
  1614. DB::rollBack();
  1615. return $this->responseController->makeResponse(true, 'ERR_WAREHOUSE_GETBY000:'.$arrResponseCheckUser['msg'], [], 401);
  1616. }
  1617. try {
  1618. $idWarehouse = $this->encController->decrypt($idWarehouse);
  1619. } catch (\Throwable $th) {
  1620. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  1621. }
  1622. try {
  1623. $idArea = $this->encController->decrypt($idArea);
  1624. } catch (\Throwable $th) {
  1625. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY001: Ocurrió un error al desencriptar el ID del área', $th->getMessage(), 406);
  1626. }
  1627. try {
  1628. $idLevel = $this->encController->decrypt($idLevel);
  1629. } catch (\Throwable $th) {
  1630. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY002: Ocurrió un error al desencriptar el ID del nivel', $th->getMessage(), 406);
  1631. }
  1632. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1633. if ($arrResponseCheckUser['error']) {
  1634. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY003:'.$arrResponseCheckUser['msg'], [], 401);
  1635. }
  1636. try {
  1637. $getZone = DB::table('S002V01TZONA')
  1638. ->where('ZONA_COAL', '=', $idWarehouse)
  1639. ->where('ZONA_COAR', '=', $idArea)
  1640. ->where('ZONA_CONI', '=', $idLevel)
  1641. ->where('ZONA_NULI', '=', $line)
  1642. ->get([
  1643. 'ZONA_COZO AS CODIGO_ZONA',
  1644. 'ZONA_NOZO AS NOMBRE_ZONA',
  1645. 'ZONA_COME AS COMENTARIOS',
  1646. 'ZONA_ESTA AS ESTADO',
  1647. 'ZONA_USRE AS USUARIO_REGISTRA',
  1648. 'ZONA_FERE AS FECHA_REGISTRA',
  1649. 'ZONA_USMO AS USUARIO_MODIFICA',
  1650. 'ZONA_FEMO AS FECHA_MODIFICA',
  1651. ]);
  1652. $arrZone = json_decode(json_encode($getZone), true);
  1653. } catch (\Throwable $th) {
  1654. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY004: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  1655. }
  1656. foreach ($arrZone as $key => $value) {
  1657. try {
  1658. $countStock = DB::table('S002V01TUBAR')
  1659. ->where('UBAR_NULI', '=', $line)
  1660. ->where('UBAR_ESTA', '=', 'Activo')
  1661. ->where('UBAR_COAL', '=', $idWarehouse)
  1662. ->where('UBAR_COAR', '=', $idArea)
  1663. ->where('UBAR_CONI', '=', $idLevel)
  1664. ->where('UBAR_COZO', '=', $value['CODIGO_ZONA'])
  1665. ->count();
  1666. } catch (\Throwable $th) {
  1667. DB::rollBack();
  1668. return $this->responseController->makeResponse(
  1669. true,
  1670. "ERR_WAREHOUSE_GET003: Ocurrió un error al obtener los almacenes.",
  1671. $th->getMessage(),
  1672. 500
  1673. );
  1674. }
  1675. $value['CANTIDAD_STOCK'] = $countStock;
  1676. $arrZone[$key] = $value;
  1677. }
  1678. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrZone, $line);
  1679. if ($responseCheckLatestUpdate['error']) {
  1680. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  1681. }
  1682. $arrZone = $responseCheckLatestUpdate['response'];
  1683. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrZone);
  1684. }
  1685. public function getZoneById($idZone, $user, $line) {
  1686. try {
  1687. $idZone = $this->encController->decrypt($idZone);
  1688. } catch (\Throwable $th) {
  1689. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  1690. }
  1691. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1692. if ($arrResponseCheckUser['error']) {
  1693. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY001:'.$arrResponseCheckUser['msg'], [], 401);
  1694. }
  1695. try {
  1696. $getZone = (array) DB::table('S002V01TZONA')
  1697. ->where('ZONA_COZO', '=', $idZone)
  1698. ->where('ZONA_NULI', '=', $line)
  1699. ->first([
  1700. 'ZONA_NOZO AS NOMBRE_ZONA',
  1701. 'ZONA_COME AS COMENTARIOS',
  1702. 'ZONA_ESTA AS ESTADO',
  1703. 'ZONA_USRE AS USUARIO_REGISTRA',
  1704. 'ZONA_FERE AS FECHA_REGISTRA',
  1705. 'ZONA_USMO AS USUARIO_MODIFICA',
  1706. 'ZONA_FEMO AS FECHA_MODIFICA',
  1707. ]);
  1708. $arrZone = json_decode(json_encode($getZone), true);
  1709. } catch (\Throwable $th) {
  1710. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBY002: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  1711. }
  1712. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrZone);
  1713. }
  1714. public function getZoneByLevelAreaWarehouseActive($idWarehouse, $idArea, $idLevel, $user, $line) {
  1715. try {
  1716. $idWarehouse = $this->encController->decrypt($idWarehouse);
  1717. } catch (\Throwable $th) {
  1718. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE000: Ocurrió un error al desencriptar el ID del almacen', $th->getMessage(), 406);
  1719. }
  1720. try {
  1721. $idArea = $this->encController->decrypt($idArea);
  1722. } catch (\Throwable $th) {
  1723. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE001: Ocurrió un error al desencriptar el ID del área', $th->getMessage(), 406);
  1724. }
  1725. try {
  1726. $idLevel = $this->encController->decrypt($idLevel);
  1727. } catch (\Throwable $th) {
  1728. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE002: Ocurrió un error al desencriptar el ID del nivel', $th->getMessage(), 406);
  1729. }
  1730. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  1731. if ($arrResponseCheckUser['error']) {
  1732. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE003:'.$arrResponseCheckUser['msg'], [], 401);
  1733. }
  1734. try {
  1735. $validateExists = DB::table('S002V01TALMA')
  1736. ->where('ALMA_NULI', '=', $line)
  1737. ->where('ALMA_COAL', '=', $idWarehouse)
  1738. ->exists();
  1739. } catch (\Throwable $th) {
  1740. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE004: Ocurrió un error al obtener el almacen.', $th->getMessage(), 406);
  1741. }
  1742. if (!$validateExists) {
  1743. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE005: El almacen no existe.', [], 401);
  1744. }
  1745. try {
  1746. $validateExists = DB::table('S002V01TAREA')
  1747. ->where('AREA_NULI', '=', $line)
  1748. ->where('AREA_COAL', '=', $idWarehouse)
  1749. ->where('AREA_COAR', '=', $idArea)
  1750. ->exists();
  1751. } catch (\Throwable $th) {
  1752. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE006: Ocurrió un error al obtener el área.', $th->getMessage(), 406);
  1753. }
  1754. if (!$validateExists) {
  1755. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE007: El área no existe.', [], 401);
  1756. }
  1757. try {
  1758. $validateExists = DB::table('S002V01TNIVE')
  1759. ->where('NIVE_NULI', '=', $line)
  1760. ->where('NIVE_COAL', '=', $idWarehouse)
  1761. ->where('NIVE_COAR', '=', $idArea)
  1762. ->where('NIVE_CONI', '=', $idLevel)
  1763. ->exists();
  1764. } catch (\Throwable $th) {
  1765. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE008: Ocurrió un error al obtener el nivel.', $th->getMessage(), 406);
  1766. }
  1767. if (!$validateExists) {
  1768. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE009: El nivel no existe.', [], 401);
  1769. }
  1770. try {
  1771. $getZone = DB::table('S002V01TZONA')
  1772. ->where('ZONA_COAL', '=', $idWarehouse)
  1773. ->where('ZONA_COAR', '=', $idArea)
  1774. ->where('ZONA_CONI', '=', $idLevel)
  1775. ->where('ZONA_NULI', '=', $line)
  1776. ->where('ZONA_ESTA', '=', 'Activo')
  1777. ->get([
  1778. 'ZONA_COZO AS CODIGO_ZONA',
  1779. 'ZONA_NOZO AS NOMBRE_ZONA',
  1780. 'ZONA_COME AS COMENTARIOS',
  1781. ]);
  1782. $arrZone = json_decode(json_encode($getZone), true);
  1783. } catch (\Throwable $th) {
  1784. return $this->responseController->makeResponse(true, 'ERR_ZONE_GETBYACTIVE010: Ocurrió un error al obtener los registros del área.', $th->getMessage(), 406);
  1785. }
  1786. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrZone);
  1787. }
  1788. public function registerZone(Request $request) {
  1789. $validator = Validator::make($request->all(), [
  1790. 'CODIGO_ALMACEN' => 'required|string',
  1791. 'CODIGO_AREA' => 'required|string',
  1792. 'CODIGO_NIVEL' => 'required|string',
  1793. 'CODIGO_ZONA' => 'required|string',
  1794. 'NOMBRE_ZONA' => 'required|string',
  1795. 'COMENTARIOS' => 'nullable|string',
  1796. 'USUARIO' => 'required|string',
  1797. 'NUMERO_LINEA' => 'required|integer',
  1798. ]);
  1799. if ($validator->fails()) {
  1800. return $this->responseController->makeResponse(
  1801. true,
  1802. "ERR_ZONE_REG000: Se encontraron uno o más errores.",
  1803. $this->responseController->makeErrors($validator->errors()->messages()),
  1804. 401
  1805. );
  1806. }
  1807. DB::beginTransaction();
  1808. $requestData = $request->all();
  1809. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  1810. if ($arrResponseCheckUser['error']) {
  1811. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG001:'.$arrResponseCheckUser['msg'], [], 401);
  1812. }
  1813. $user = $arrResponseCheckUser['response'];
  1814. try {
  1815. $validateExistWarehouse = DB::table('S002V01TALMA')
  1816. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  1817. ->where('ALMA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1818. ->where('ALMA_ESTA', '=', 'Activo')
  1819. ->exists();
  1820. } catch (\Throwable $th) {
  1821. DB::rollBack();
  1822. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG002: Ocurrió un error al verificar el almacen.', $th->getMessage(), 500);
  1823. }
  1824. if (!$validateExistWarehouse) {
  1825. DB::rollBack();
  1826. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG003: El almacen no existe.', [], 406);
  1827. }
  1828. try {
  1829. $validateExistArea = DB::table('S002V01TAREA')
  1830. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1831. ->where('AREA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1832. ->where('AREA_COAR', '=', $requestData['CODIGO_AREA'])
  1833. ->where('AREA_ESTA', '=', 'Activo')
  1834. ->exists();
  1835. } catch (\Throwable $th) {
  1836. DB::rollBack();
  1837. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG004: Ocurrió un error al verificar el área.', $th->getMessage(), 500);
  1838. }
  1839. if (!$validateExistArea) {
  1840. DB::rollBack();
  1841. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG005: El área no existe.', [], 406);
  1842. }
  1843. try {
  1844. $validateExistNivel = DB::table('S002V01TNIVE')
  1845. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1846. ->where('NIVE_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1847. ->where('NIVE_COAR', '=', $requestData['CODIGO_AREA'])
  1848. ->where('NIVE_CONI', '=', $requestData['CODIGO_NIVEL'])
  1849. ->where('NIVE_ESTA', '=', 'Activo')
  1850. ->exists();
  1851. } catch (\Throwable $th) {
  1852. DB::rollBack();
  1853. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG006: Ocurrió un error al verificar el nivel.', $th->getMessage(), 500);
  1854. }
  1855. if (!$validateExistNivel) {
  1856. DB::rollBack();
  1857. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG007: El nivel no existe.', [], 406);
  1858. }
  1859. try {
  1860. $validateExistZone = DB::table('S002V01TZONA')
  1861. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  1862. ->where('ZONA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1863. ->where('ZONA_COAR', '=', $requestData['CODIGO_AREA'])
  1864. ->where('ZONA_CONI', '=', $requestData['CODIGO_NIVEL'])
  1865. ->where('ZONA_COZO', '=', $requestData['CODIGO_ZONA'])
  1866. ->exists();
  1867. } catch (\Throwable $th) {
  1868. DB::rollBack();
  1869. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG008: Ocurrió un error al verificar el código de la zona.', $th->getMessage(), 406);
  1870. }
  1871. if ($validateExistZone) {
  1872. DB::rollBack();
  1873. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG009: El código de la zona ya existe.', [], 406);
  1874. }
  1875. $now = $this->functionsController->now();
  1876. $currentDate = $now->toDateTimeString();
  1877. try {
  1878. $validateInsert = DB::table('S002V01TZONA')->insert([
  1879. 'ZONA_NULI' => $requestData['NUMERO_LINEA'],
  1880. 'ZONA_COAL' => $requestData['CODIGO_ALMACEN'],
  1881. 'ZONA_COAR' => $requestData['CODIGO_AREA'],
  1882. 'ZONA_CONI' => $requestData['CODIGO_NIVEL'],
  1883. 'ZONA_COZO' => $requestData['CODIGO_ZONA'],
  1884. 'ZONA_NOZO' => $requestData['NOMBRE_ZONA'],
  1885. 'ZONA_COME' => $requestData['COMENTARIOS'],
  1886. 'ZONA_USRE' => $user,
  1887. 'ZONA_FERE' => $currentDate,
  1888. 'ZONA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  1889. ]);
  1890. } catch (\Throwable $th) {
  1891. DB::rollBack();
  1892. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG010: Ocurrió un error al ingresar la información a la base de datos.', $th->getMessage(), 500);
  1893. }
  1894. if (!$validateInsert) {
  1895. DB::rollBack();
  1896. return $this->responseController->makeResponse(true, 'ERR_ZONE_REG011: No se pudo guardar la información en la base de datos.', [], 406);
  1897. }
  1898. DB::commit();
  1899. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  1900. }
  1901. public function updateZone(Request $request, $idZone) {
  1902. $validator = Validator::make($request->all(), [
  1903. 'CODIGO_ALMACEN' => 'required|string',
  1904. 'CODIGO_AREA' => 'required|string',
  1905. 'CODIGO_NIVEL' => 'required|string',
  1906. 'NOMBRE_ZONA' => 'required|string',
  1907. 'COMENTARIOS' => 'nullable|string',
  1908. 'USUARIO' => 'required|string',
  1909. 'NUMERO_LINEA' => 'required|integer',
  1910. ]);
  1911. if ($validator->fails()) {
  1912. return $this->responseController->makeResponse(
  1913. true,
  1914. "ERR_ZONE_UPD000: Se encontraron uno o más errores.",
  1915. $this->responseController->makeErrors($validator->errors()->messages()),
  1916. 401
  1917. );
  1918. }
  1919. DB::beginTransaction();
  1920. $requestData = $request->all();
  1921. try {
  1922. $idZone = $this->encController->decrypt($idZone);
  1923. } catch (\Throwable $th) {
  1924. DB::rollBack();
  1925. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD001: Ocurrió un error al desencriptar la zona.', $th->getMessage(), 500);
  1926. }
  1927. try {
  1928. $validateExistLevel = DB::table('S002V01TZONA')
  1929. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  1930. ->where('ZONA_COZO', '=', $idZone)
  1931. ->where('ZONA_ESTA', '=', 'Activo')
  1932. ->exists();
  1933. } catch (\Throwable $th) {
  1934. DB::rollBack();
  1935. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD002: Ocurrió un error al verificar el código de la zona.', $th->getMessage(), 500);
  1936. }
  1937. if (!$validateExistLevel) {
  1938. DB::rollBack();
  1939. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD003: El área no existe.', [], 406);
  1940. }
  1941. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  1942. if ($arrResponseCheckUser['error']) {
  1943. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD004:'.$arrResponseCheckUser['msg'], [], 401);
  1944. }
  1945. $user = $arrResponseCheckUser['response'];
  1946. try {
  1947. $validateExistWarehouse = DB::table('S002V01TALMA')
  1948. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  1949. ->where('ALMA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1950. ->where('ALMA_ESTA', '=', 'Activo')
  1951. ->exists();
  1952. } catch (\Throwable $th) {
  1953. DB::rollBack();
  1954. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD005: Ocurrió un error al verificar el almacen.', $th->getMessage(), 500);
  1955. }
  1956. if (!$validateExistWarehouse) {
  1957. DB::rollBack();
  1958. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD006: El almacen no existe.', [], 406);
  1959. }
  1960. try {
  1961. $validateExistArea = DB::table('S002V01TAREA')
  1962. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  1963. ->where('AREA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1964. ->where('AREA_COAR', '=', $requestData['CODIGO_AREA'])
  1965. ->where('AREA_ESTA', '=', 'Activo')
  1966. ->exists();
  1967. } catch (\Throwable $th) {
  1968. DB::rollBack();
  1969. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD007: Ocurrió un error al verificar el área.', $th->getMessage(), 500);
  1970. }
  1971. if (!$validateExistArea) {
  1972. DB::rollBack();
  1973. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD008: El área no existe.', [], 406);
  1974. }
  1975. try {
  1976. $validateExistNivel = DB::table('S002V01TNIVE')
  1977. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  1978. ->where('NIVE_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1979. ->where('NIVE_COAR', '=', $requestData['CODIGO_AREA'])
  1980. ->where('NIVE_CONI', '=', $requestData['CODIGO_NIVEL'])
  1981. ->where('NIVE_ESTA', '=', 'Activo')
  1982. ->exists();
  1983. } catch (\Throwable $th) {
  1984. DB::rollBack();
  1985. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD009: Ocurrió un error al verificar el nivel.', $th->getMessage(), 500);
  1986. }
  1987. if (!$validateExistNivel) {
  1988. DB::rollBack();
  1989. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD010: El nivel no existe.', [], 406);
  1990. }
  1991. try {
  1992. $validateExistZone = DB::table('S002V01TZONA')
  1993. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  1994. ->where('ZONA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  1995. ->where('ZONA_COAR', '=', $requestData['CODIGO_AREA'])
  1996. ->where('ZONA_CONI', '=', $requestData['CODIGO_NIVEL'])
  1997. ->where('ZONA_COZO', '=', $requestData['CODIGO_ZONA'])
  1998. ->exists();
  1999. } catch (\Throwable $th) {
  2000. DB::rollBack();
  2001. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD011: Ocurrió un error al verificar el código de la zona.', $th->getMessage(), 406);
  2002. }
  2003. if ($validateExistZone) {
  2004. DB::rollBack();
  2005. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD012: El código de la zona ya existe.', [], 406);
  2006. }
  2007. $now = $this->functionsController->now();
  2008. $currentDate = $now->toDateTimeString();
  2009. try {
  2010. $validateUpdate = DB::table('S002V01TZONA')
  2011. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  2012. ->where('ZONA_COAL', '=', $requestData['CODIGO_ALMACEN'])
  2013. ->where('ZONA_COAR', '=', $requestData['CODIGO_AREA'])
  2014. ->where('ZONA_CONI', '=', $requestData['CODIGO_NIVEL'])
  2015. ->where('ZONA_COZO', '=', $idZone)
  2016. ->update([
  2017. 'ZONA_NOZO' => $requestData['NOMBRE_ZONA'],
  2018. 'ZONA_COME' => $requestData['COMENTARIOS'],
  2019. 'ZONA_USMO' => $user,
  2020. 'ZONA_FEMO' => $currentDate,
  2021. 'ZONA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2022. ]);
  2023. } catch (\Throwable $th) {
  2024. DB::rollBack();
  2025. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD013: Ocurrió un error al ingresar la información a la base de datos.', $th->getMessage(), 500);
  2026. }
  2027. if (!$validateUpdate) {
  2028. DB::rollBack();
  2029. return $this->responseController->makeResponse(true, 'ERR_ZONE_UPD014: No se pudo guardar la información en la base de datos.', [], 406);
  2030. }
  2031. DB::commit();
  2032. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  2033. }
  2034. public function deleteZone(Request $request, $idZone) {
  2035. $validator = Validator::make($request->all(), [
  2036. 'USUARIO' => 'required|string',
  2037. 'NUMERO_LINEA' => 'required|integer',
  2038. ]);
  2039. if ($validator->fails()) {
  2040. return $this->responseController->makeResponse(
  2041. true,
  2042. "ERR_ZONE_DEL000: Se encontraron uno o más errores.",
  2043. $this->responseController->makeErrors($validator->errors()->messages()),
  2044. 401
  2045. );
  2046. }
  2047. DB::beginTransaction();
  2048. $requestData = $request->all();
  2049. try {
  2050. $idZone = $this->encController->decrypt($idZone);
  2051. } catch (\Throwable $th) {
  2052. DB::rollBack();
  2053. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL001: Ocurrió un error al desencriptar la zona.', $th->getMessage(), 500);
  2054. }
  2055. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  2056. if ($arrResponseCheckUser['error']) {
  2057. DB::rollBack();
  2058. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL002:'.$arrResponseCheckUser['msg'], [], 401);
  2059. }
  2060. $user = $arrResponseCheckUser['response'];
  2061. try {
  2062. $arrZone = (array) DB::table('S002V01TZONA')
  2063. ->where('ZONA_COZO', '=', $idZone)
  2064. ->where('ZONA_ESTA', '=', 'Activo')
  2065. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  2066. ->first([
  2067. 'ZONA_COAL',
  2068. 'ZONA_COAR',
  2069. 'ZONA_CONI',
  2070. ]);
  2071. } catch (\Throwable $th) {
  2072. DB::rollBack();
  2073. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL003: Ocurrió un error al obtener la información de la zona.', $th->getMessage(), 500);
  2074. }
  2075. if (empty($arrZone)) {
  2076. DB::rollBack();
  2077. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL004: La zona no existe.', [], 406);
  2078. }
  2079. try {
  2080. $validateExists = DB::table('S002V01TUBAR')
  2081. ->where('UBAR_COAL', '=', $arrZone['ZONA_COAL'])
  2082. ->where('UBAR_COAR', '=', $arrZone['ZONA_COAR'])
  2083. ->where('UBAR_CONI', '=', $arrZone['ZONA_CONI'])
  2084. ->where('UBAR_COZO', '=', $idZone)
  2085. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  2086. ->where('UBAR_ESTA', '=', 'Activo')
  2087. ->exists();
  2088. } catch (\Throwable $th) {
  2089. DB::rollBack();
  2090. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL005: Ocurrió un error al obtener las ubicaciones de los artículos.', $th->getMessage(), 500);
  2091. }
  2092. if($validateExists) {
  2093. DB::rollBack();
  2094. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL006: No se puede eliminar debido a que existen artículos ubicados en la zona.', [], 406);
  2095. }
  2096. $now = $this->functionsController->now();
  2097. $currentDate = $now->toDateTimeString();
  2098. try {
  2099. $validateUpdate = DB::table('S002V01TZONA')
  2100. ->where('ZONA_COZO', '=', $idZone)
  2101. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  2102. ->update([
  2103. 'ZONA_ESTA' => 'Eliminado',
  2104. 'ZONA_USMO' => $user,
  2105. 'ZONA_FEMO' => $currentDate,
  2106. 'ZONA_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2107. ]);
  2108. } catch (\Throwable $th) {
  2109. DB::rollBack();
  2110. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL007: Ocurrió un error al eliminar la zona.', $th->getMessage(), 500);
  2111. }
  2112. if (!$validateUpdate) {
  2113. DB::rollBack();
  2114. return $this->responseController->makeResponse(true, 'ERR_ZONE_DEL008: No se pudo eliminar la zona.', [], 406);
  2115. }
  2116. DB::commit();
  2117. return $this->responseController->makeResponse(false, "ÉXITO: Eliminación Exitosa");
  2118. }
  2119. // FUNCIÓN RECEPCIÓN DE ARTÍCULOS
  2120. public function registerToStock(Request $request) {
  2121. $validator = Validator::make($request->all(), [
  2122. 'WAREHOUSE' => 'required|string',
  2123. 'AREA' => 'required|string',
  2124. 'LEVEL' => 'required|string',
  2125. 'ZONE' => 'required|string',
  2126. 'ORDER' => 'required|string',
  2127. 'PRE_CODIFICATE' => 'required|array',
  2128. 'ID_INFORMATION' => 'required|integer',
  2129. 'FAMILIA' => 'required|string',
  2130. 'SUBFAMILIA' => 'required|string',
  2131. 'MODELO' => 'required|string',
  2132. 'CODIGO_MODELO' => 'required|string',
  2133. 'NUMBER_ITEMS' => 'required|integer',
  2134. 'CODIGO_BARRAS' => 'required|string',
  2135. 'FECHA_VENCIMIENTO' => 'nullable|string',
  2136. 'IMAGES' => 'required|json',
  2137. 'PRE_GENERATED_CODE' => 'required|string',
  2138. 'REPARABLE' => 'required|boolean',
  2139. 'CONSUMIBLE' => 'required|boolean',
  2140. 'USUARIO' => 'required|string',
  2141. 'NUMERO_LINEA' => 'required|integer',
  2142. ]);
  2143. if($validator->fails()){
  2144. return $this->responseController->makeResponse(
  2145. true,
  2146. "Se encontraron uno o más errores.",
  2147. $this->responseController->makeErrors(
  2148. $validator->errors()->messages()
  2149. ),
  2150. 401
  2151. );
  2152. }
  2153. DB::beginTransaction();
  2154. $requestData = $request->all();
  2155. // Se desencripta y se verifica si el usuario existe
  2156. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  2157. if ($arrResponseCheckUser['error']) {
  2158. DB::rollBack();
  2159. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  2160. }
  2161. $user = $arrResponseCheckUser['response'];
  2162. $idInformation = intval($requestData['ID_INFORMATION']);
  2163. if($idInformation <= 0){
  2164. goto noDescription;
  2165. }
  2166. try {
  2167. $infoAdquisition = (array) DB::table('S002V01TINAR')
  2168. ->where([
  2169. ['INAR_IDIN', '=', $requestData['ID_INFORMATION']],
  2170. ['INAR_NULI', '=', $requestData['NUMERO_LINEA']],
  2171. ])
  2172. ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
  2173. ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')
  2174. ->first([
  2175. 'DEAR_CAAR AS CANTIDAD_ARTICULOS',
  2176. ]);
  2177. } catch (\Throwable $th) {
  2178. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de la adquisición.', $th->getMessage(), 404);
  2179. }
  2180. if (empty($infoAdquisition)) {
  2181. return $this->responseController->makeResponse(true, 'No existe la información de la adquisición.', [], 404);
  2182. }
  2183. noDescription:
  2184. $infoAdquisition['CANTIDAD_ARTICULOS'] = $idInformation <= 0 ? 1 : intval($infoAdquisition['CANTIDAD_ARTICULOS']);
  2185. $requestData['NUMBER_ITEMS'] = intval($requestData['NUMBER_ITEMS']);
  2186. $amountArticle = $infoAdquisition['CANTIDAD_ARTICULOS'] * $requestData['NUMBER_ITEMS'];
  2187. // Se verifica la precodificación
  2188. if (count($requestData['PRE_CODIFICATE']) !== $amountArticle) {
  2189. DB::rollBack();
  2190. return $this->responseController->makeResponse(true, 'La cantidad registrada de la precodificación no es igual la cantidad de artículos seleccionados.', [$requestData['PRE_CODIFICATE'], $requestData['NUMBER_ITEMS']], 500);
  2191. }
  2192. // Se obtiene la información encriptada
  2193. try {
  2194. $idWarehouse = $this->encController->decrypt($requestData['WAREHOUSE']);
  2195. } catch (\Throwable $th) {
  2196. DB::rollBack();
  2197. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el almacen.', $th->getMessage(), 500);
  2198. }
  2199. if ($idWarehouse === false) {
  2200. DB::rollBack();
  2201. return $this->responseController->makeResponse(true, 'La encriptación del almacen no es correcta.', [], 500);
  2202. }
  2203. try {
  2204. $idArea = $this->encController->decrypt($requestData['AREA']);
  2205. } catch (\Throwable $th) {
  2206. DB::rollBack();
  2207. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el área.', $th->getMessage(), 500);
  2208. }
  2209. if ($idArea === false) {
  2210. DB::rollBack();
  2211. return $this->responseController->makeResponse(true, 'La encriptacipon del área no es correcta.', [], 500);
  2212. }
  2213. try {
  2214. $idLevel = $this->encController->decrypt($requestData['LEVEL']);
  2215. } catch (\Throwable $th) {
  2216. DB::rollBack();
  2217. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el nivel.', $th->getMessage(), 500);
  2218. }
  2219. if ($idLevel === false) {
  2220. DB::rollBack();
  2221. return $this->responseController->makeResponse(true, 'La encriptación del nivel no es correcta.', [], 500);
  2222. }
  2223. try {
  2224. $idZone = $this->encController->decrypt($requestData['ZONE']);
  2225. } catch (\Throwable $th) {
  2226. DB::rollBack();
  2227. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la zona.', $th->getMessage(), 500);
  2228. }
  2229. if ($idZone === false) {
  2230. DB::rollBack();
  2231. return $this->responseController->makeResponse(true, 'La encriptación de la zona no es correcta.', [], 500);
  2232. }
  2233. try {
  2234. $idFamily = $this->encController->decrypt($requestData['FAMILIA']);
  2235. } catch (\Throwable $th) {
  2236. DB::rollBack();
  2237. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la familia.', $th->getMessage(), 500);
  2238. }
  2239. if ($idFamily === false) {
  2240. DB::rollBack();
  2241. return $this->responseController->makeResponse(true, 'La encriptación de la familia no es correcta.', [], 500);
  2242. }
  2243. try {
  2244. $idSubfamily = $this->encController->decrypt($requestData['SUBFAMILIA']);
  2245. } catch (\Throwable $th) {
  2246. DB::rollBack();
  2247. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la subfamilia.', $th->getMessage(), 500);
  2248. }
  2249. if ($idSubfamily === false) {
  2250. DB::rollBack();
  2251. return $this->responseController->makeResponse(true, 'La encriptación de la subfamilia no es correcta.', [], 500);
  2252. }
  2253. // Se verifica que la información exista
  2254. try {
  2255. $validateWarehouse = DB::table('S002V01TALMA')
  2256. ->where('ALMA_COAL', '=', $idWarehouse)
  2257. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  2258. ->exists();
  2259. } catch (\Throwable $th) {
  2260. DB::rollBack();
  2261. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el almacen existe.', $th->getMessage(), 500);
  2262. }
  2263. if ($validateWarehouse === false) {
  2264. DB::rollBack();
  2265. return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
  2266. }
  2267. try {
  2268. $validateArea = DB::table('S002V01TAREA')
  2269. ->where('AREA_COAL', '=', $idWarehouse)
  2270. ->where('AREA_COAR', '=', $idArea)
  2271. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  2272. ->exists();
  2273. } catch (\Throwable $th) {
  2274. DB::rollBack();
  2275. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el área existe.', $th->getMessage(), 500);
  2276. }
  2277. if ($validateArea === false) {
  2278. DB::rollBack();
  2279. return $this->responseController->makeResponse(true, 'El área no existe.', [], 500);
  2280. }
  2281. try {
  2282. $validateLevel = DB::table('S002V01TNIVE')
  2283. ->where('NIVE_COAL', '=', $idWarehouse)
  2284. ->where('NIVE_COAR', '=', $idArea)
  2285. ->where('NIVE_CONI', '=', $idLevel)
  2286. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  2287. ->exists();
  2288. } catch (\Throwable $th) {
  2289. DB::rollBack();
  2290. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el nivel existe.', $th->getMessage(), 500);
  2291. }
  2292. if ($validateLevel === false) {
  2293. DB::rollBack();
  2294. return $this->responseController->makeResponse(true, 'El nivel no existe.', [], 500);
  2295. }
  2296. try {
  2297. $validateZone = DB::table('S002V01TZONA')
  2298. ->where('ZONA_COAL', '=', $idWarehouse)
  2299. ->where('ZONA_COAR', '=', $idArea)
  2300. ->where('ZONA_CONI', '=', $idLevel)
  2301. ->where('ZONA_COZO', '=', $idZone)
  2302. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  2303. ->exists();
  2304. } catch (\Throwable $th) {
  2305. DB::rollBack();
  2306. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la zona existe.', $th->getMessage(), 500);
  2307. }
  2308. if ($validateZone === false) {
  2309. return $this->responseController->makeResponse(true, 'La zona no existe.', [], 500);
  2310. }
  2311. try {
  2312. $validateFamily = DB::table('S002V01TFAMI')
  2313. ->where('FAMI_COFA', '=', $idFamily)
  2314. ->where('FAMI_NULI', '=', $requestData['NUMERO_LINEA'])
  2315. ->exists();
  2316. } catch (\Throwable $th) {
  2317. DB::rollBack();
  2318. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la familia existe.', $th->getMessage(), 500);
  2319. }
  2320. if ($validateFamily === false) {
  2321. DB::rollBack();
  2322. return $this->responseController->makeResponse(true, 'La familia no existe.', [], 500);
  2323. }
  2324. try {
  2325. $validateSubfamily = DB::table('S002V01TSUBF')
  2326. ->where('SUBF_COFA', '=', $idFamily)
  2327. ->where('SUBF_COSU', '=', $idSubfamily)
  2328. ->where('SUBF_NULI', '=', $requestData['NUMERO_LINEA'])
  2329. ->exists();
  2330. } catch (\Throwable $th) {
  2331. DB::rollBack();
  2332. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la subfamilia existe.', $th->getMessage(), 500);
  2333. }
  2334. if ($validateSubfamily === false) {
  2335. DB::rollBack();
  2336. return $this->responseController->makeResponse(true, 'La subfamilia no existe.', [], 500);
  2337. }
  2338. try {
  2339. $orden = (array) DB::table('S002V01TORCO')
  2340. ->where('ORCO_NUOR', '=', $requestData['ORDER'])
  2341. ->where('ORCO_NULI', '=', $requestData['NUMERO_LINEA'])
  2342. ->where('ORCO_ESTA', '=', 'Recibido')
  2343. ->first([
  2344. 'ORCO_IDLI AS ID_LINEA_SOLICITUD',
  2345. 'ORCO_IDDE AS ID_DESCRIPCION',
  2346. ]);
  2347. } catch (\Throwable $th) {
  2348. DB::rollBack();
  2349. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de la orden de compra.', $th->getMessage(), 500);
  2350. }
  2351. if (is_null($orden)) {
  2352. DB::rollBack();
  2353. return $this->responseController->makeResponse(true, 'La orden de compra no existe.', [], 500);
  2354. }
  2355. $now = $this->functionsController->now();
  2356. $currentDate = $now->toDateTimeString();
  2357. if($idInformation <= 0){
  2358. goto noInformation;
  2359. }
  2360. try {
  2361. $info = DB::table('S002V01TARSE')
  2362. ->where('ARSE_IDIN', '=', $requestData['ID_INFORMATION'])
  2363. ->where('ARSE_ESTA', '=', 'Activo')
  2364. ->where('ARSE_IDLI', '=', $orden['ID_LINEA_SOLICITUD'])
  2365. ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
  2366. ->where('ARTI_NULI', '=', $requestData['NUMERO_LINEA'])
  2367. ->where('DEAR_NULI', '=', $requestData['NUMERO_LINEA'])
  2368. ->where('UNID_NULI', '=', $requestData['NUMERO_LINEA'])
  2369. ->where('INAR_NULI', '=', $requestData['NUMERO_LINEA'])
  2370. ->where('ARSE_ESTA', '=', 'Activo')
  2371. ->where('ARTI_ESTA', '=', 'Activo')
  2372. ->where('DEAR_ESTA', '=', 'Activo')
  2373. ->where('UNID_ESTA', '=', 'Activo')
  2374. ->where('INAR_ESTA', '=', 'Activo')
  2375. ->where('INAR_CODI', '=', $requestData['CODIGO_MODELO'])
  2376. ->where('INAR_MODE', '=', $requestData['MODELO'])
  2377. ->join('S002V01TARTI', 'ARTI_IDAR', '=', 'ARSE_IDAR')
  2378. ->join('S002V01TINAR', 'INAR_IDIN', '=', 'ARSE_IDIN')
  2379. ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
  2380. ->join('S002V01TUNID', 'UNID_IDUN', '=', 'DEAR_IDUN')
  2381. ->limit($requestData['NUMBER_ITEMS'])
  2382. ->get([
  2383. 'ARSE_IDAS AS NUMERO_SELECCIONADO',
  2384. 'ARTI_IDAR AS ID_ARTICULO',
  2385. 'ARTI_COFA AS CODIGO_FAMILIA',
  2386. 'ARTI_COSU AS CODIGO_SUBFAMILIA',
  2387. 'ARTI_CODI AS CODIGO_ARTICULO',
  2388. 'ARTI_NOMB AS NOMBRE_ARTICULO',
  2389. 'DEAR_IDDE AS ID_DESCRIPCION',
  2390. 'DEAR_IMAG AS IMAGENES',
  2391. 'DEAR_DESC AS DESCRIPCION',
  2392. 'DEAR_CARA AS CARACTERISTICAS',
  2393. 'DEAR_COWE AS COMPRA_WEB',
  2394. 'DEAR_NUPR AS NUMERO_PROVEEDOR',
  2395. 'UNID_IDUN AS ID_UNIDAD',
  2396. 'UNID_NOMB AS NOMBRE_UNIDAD',
  2397. 'UNID_ACRO AS ACRONIMO_UNIDAD',
  2398. 'INAR_IDIN AS ID_INFORMACION',
  2399. 'INAR_CODI AS CODIGO_INFORMACION',
  2400. 'INAR_MODE AS MODELO_INFORMACION',
  2401. 'INAR_COMO AS CODIGO_MONEDA',
  2402. 'INAR_PREC AS PRECIO',
  2403. 'INAR_MOMI AS MONTO_MINIMO',
  2404. 'INAR_CARA AS CARACTERISTICAS',
  2405. ]);
  2406. $info = json_decode(json_encode($info), true);
  2407. } catch (\Throwable $th) {
  2408. DB::rollBack();
  2409. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de los productos.', $th->getMessage(), 500);
  2410. }
  2411. if ( is_null($info) || empty($info) ) {
  2412. DB::rollBack();
  2413. return $this->responseController->makeResponse(true, 'No existen artículos asociados a la orden de compra.', [], 500);
  2414. }
  2415. // Se verifica que existan los datos suficientes para hacer el traslado.
  2416. if ( count($info) !== $requestData['NUMBER_ITEMS']) {
  2417. DB::rollBack();
  2418. return $this->responseController->makeResponse(true, 'La cantidad de artículos en la orden de compra no corresponde a la cantidad de artículos seleccionados a Stock.', [count($info), $requestData['NUMBER_ITEMS']], 500);
  2419. }
  2420. noInformation:
  2421. // Se verifica los códigos de barras
  2422. $uniqueBarcode = false;
  2423. $arrBarcode = explode(',', $requestData['CODIGO_BARRAS']);
  2424. if ( count($arrBarcode) === 0) {
  2425. DB::rollBack();
  2426. return $this->responseController->makeResponse(true, 'No hay códigos de barras registrados.', [], 500);
  2427. } else if (count($arrBarcode) === $requestData['NUMBER_ITEMS']) {
  2428. $uniqueBarcode = false;
  2429. } else if (array_key_exists(0, $arrBarcode) && count($arrBarcode) === 1 && $arrBarcode[0] !== '' ) {
  2430. $uniqueBarcode = true;
  2431. } else {
  2432. DB::rollBack();
  2433. return $this->responseController->makeResponse(true, 'Ocurrió un error con los códigos de barras registrados.', [], 500);
  2434. }
  2435. // Se verifica que los códigos de barras del formulario no sean repetidos
  2436. $temp_array = array_unique($arrBarcode);
  2437. $duplicates = sizeof($temp_array) != sizeof($arrBarcode);
  2438. if ($duplicates) {
  2439. return $this->responseController->makeResponse(true, 'Los códigos de barras no se pueden repetir.', [], 400);
  2440. }
  2441. // Se verifican que los códigos de barras no se repitan
  2442. foreach ($arrBarcode as $key => $barcode) {
  2443. try {
  2444. $validateBarcode = DB::table('S002V01TSTAR')
  2445. ->where('STAR_COBA', '=', $barcode)
  2446. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  2447. ->exists();
  2448. } catch (\Throwable $th) {
  2449. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar los códigos de barras.', $th->getMessage(), 500);
  2450. }
  2451. if ($validateBarcode === true) {
  2452. return $this->responseController->makeResponse(true, 'El código '.$barcode.' ya se encuentra registrado', [], 500);
  2453. }
  2454. }
  2455. // Se verifica la fecha de vencimientos
  2456. $arrDueDate = array();
  2457. $uniqueDueDate = false;
  2458. if ($requestData['FECHA_VENCIMIENTO'] !== '' && !is_null($requestData['FECHA_VENCIMIENTO'])) {
  2459. $arrDueDate = explode(',', $requestData['FECHA_VENCIMIENTO']);
  2460. if ( count($arrDueDate) === 0) {
  2461. DB::rollBack();
  2462. return $this->responseController->makeResponse(true, 'No hay fechas de vencimientos registradas.', [], 500);
  2463. } else if (count($arrDueDate) === $requestData['NUMBER_ITEMS']) {
  2464. $uniqueDueDate = false;
  2465. } else if (array_key_exists(0, $arrDueDate) && count($arrDueDate) === 1 && $arrDueDate[0] !== '' ) {
  2466. $uniqueDueDate = true;
  2467. } else {
  2468. DB::rollBack();
  2469. return $this->responseController->makeResponse(true, 'Ocurrió un error con las fechas de vencimientos registrados.', [], 500);
  2470. }
  2471. }
  2472. // Se obtiene la fecha actual
  2473. $now = $this->functionsController->now();
  2474. $currentDate = $now->toDateTimeString();
  2475. $idInfoStock = null;
  2476. if(!isset($info)){
  2477. goto noStockInfo;
  2478. }
  2479. try {
  2480. $infoStock = (array) DB::table('S002V01TINST')
  2481. ->where('INST_COFA', '=', $idFamily)
  2482. ->where('INST_COSU', '=', $idSubfamily)
  2483. ->where('INST_ARTI', '=', $info[0]['ID_ARTICULO'])
  2484. ->where('INST_MODE', '=', $requestData['MODELO'])
  2485. ->where('INST_COMO', '=', $requestData['CODIGO_MODELO'])
  2486. ->where('INST_NULI', '=', $requestData['NUMERO_LINEA'])
  2487. ->where('INST_ESTA', '=', 'Activo')
  2488. ->first([
  2489. 'INST_IDIS AS ID_INFO_STOCK'
  2490. ]);
  2491. } catch (\Throwable $th) {
  2492. DB::rollBack();
  2493. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar la información del stock.', $th->getMessage(), 500);
  2494. }
  2495. noStockInfo:
  2496. if (empty($infoStock) || is_null($infoStock)) {
  2497. // Se obtiene el arreglo de las imagenes
  2498. $imagesArr = json_decode($requestData['IMAGES'], true);
  2499. // Se verifica que el arreglo contenga imagenes
  2500. if(count($imagesArr) < 1){
  2501. DB::rollBack();
  2502. return $this->responseController->makeResponse(true, 'El arreglo de la galería de imágenes está vacío.', [], 400);
  2503. }
  2504. $imagesGallery = [];
  2505. // Se iteran las imagenes
  2506. foreach($imagesArr as $imageFile){
  2507. // Se verifica que tenga un formato correcto
  2508. if(!array_key_exists('type', $imageFile)){
  2509. DB::rollBack();
  2510. return $this->responseController->makeResponse(true, 'El arreglo de la galería de imágenes tiene un formato inválido.', [], 400);
  2511. // Si la imagen es nueva, entonces...
  2512. }else if($imageFile['type'] == 'Nuevo'){
  2513. // Se obtiene el ID de la imagen
  2514. $tempFileID = $this->encController->decrypt($imageFile['id']);
  2515. // Se obtiene la información registrada en la tabla de archivos temporales
  2516. $tempFile = DB::table('S002V01TARTE')->where([
  2517. ['ARTE_IDAR', '=', $tempFileID],
  2518. ['ARTE_NULI', '=', $requestData['NUMERO_LINEA']]
  2519. ])->first();
  2520. // La imagen es colocada en su posición final
  2521. $finalFile = $this->documentManagementController->moveFinalFile($requestData['NUMERO_LINEA'], 'GEEQ', 'FO', $tempFile, $user);
  2522. // Si ocurrió un error, entonces se manda el error
  2523. if(!$finalFile[0]){
  2524. return $this->responseController->makeResponse(true, $finalFile[1], [], 400);
  2525. }
  2526. // La información es guardada en un arreglo
  2527. $imagesGallery[] = $finalFile[1];
  2528. }else{
  2529. // Se desencripta el id de la imagen
  2530. $fileID = $this->encController->decrypt($imageFile['id']);
  2531. // Es guardada en un arreglo
  2532. $imagesGallery[] = $fileID;
  2533. }
  2534. }
  2535. // El arreglo de las imagenes es pasada en formato string
  2536. $imagesGalleryStr = json_encode($imagesGallery);
  2537. try {
  2538. $idArtitle = isset($info) ? $info[0]['ID_ARTICULO'] : 0;
  2539. $idInsert = DB::table('S002V01TINST')->insertGetId([
  2540. 'INST_NULI' => $requestData['NUMERO_LINEA'],
  2541. 'INST_COFA' => $idFamily,
  2542. 'INST_COSU' => $idSubfamily,
  2543. 'INST_ARTI' => $idArtitle,
  2544. 'INST_MODE' => $requestData['MODELO'],
  2545. 'INST_COMO' => $requestData['CODIGO_MODELO'],
  2546. 'INST_IMAG' => $imagesGalleryStr,
  2547. 'INST_USRE' => $user,
  2548. 'INST_FERE' => $currentDate,
  2549. 'INST_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2550. ]);
  2551. } catch (\Throwable $th) {
  2552. DB::rollBack();
  2553. return $this->responseController->makeResponse(true, 'Ocurrió un error al insertar la información del stock.', $th->getMessage(), 500);
  2554. }
  2555. if ($idInsert === false || is_null($idInsert)) {
  2556. DB::rollBack();
  2557. return $this->responseController->makeResponse(true, 'No se pudo insertar la información del stock.', [], 500);
  2558. }
  2559. $idInfoStock = $idInsert;
  2560. } else {
  2561. $idInfoStock = $infoStock['ID_INFO_STOCK'];
  2562. }
  2563. if (is_null($idInfoStock)) {
  2564. DB::rollBack();
  2565. return $this->responseController->makeResponse(true, 'No se pudo obtener el ID de la información del Stock.', [], 500);
  2566. }
  2567. for ($i=0; $i < $requestData['NUMBER_ITEMS']; $i++) {
  2568. $dueDate = null;
  2569. if (count($arrDueDate) > 0 && $uniqueDueDate === true) {
  2570. $dueDate = $arrDueDate[0];
  2571. } else if (count($arrDueDate) > 0 && $uniqueDueDate === false) {
  2572. $dueDate = $arrDueDate[$i];
  2573. }
  2574. if (!is_null($dueDate) && str_contains($dueDate, 'T')) {
  2575. $dueDate = explode('T', $dueDate)[0];
  2576. }
  2577. try {
  2578. $preCodificate = $this->encController->decrypt($requestData['PRE_CODIFICATE'][$i]);
  2579. } catch (\Throwable $th) {
  2580. DB::rollBack();
  2581. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el identificador de la pre-codificación.', $th->getMessage(), 500);
  2582. }
  2583. if ($preCodificate === false) {
  2584. DB::rollBack();
  2585. return $this->responseController->makeResponse(true, 'No se pudo desencriptar el identificador de la pre-codificación.', [], 500);
  2586. }
  2587. try {
  2588. $tiad = isset($info) ? 'Por pedido' : 'Sin Pedido';
  2589. $idun = isset($info) ? $info[$i]['ID_UNIDAD'] : 0;
  2590. $nupr = isset($info) ? $info[$i]['NUMERO_PROVEEDOR'] : 0;
  2591. $prad = isset($info) ? $info[$i]['PRECIO'] : 0;
  2592. $como = isset($info) ? $info[$i]['CODIGO_MONEDA'] : 0;
  2593. $idInsertStAr = DB::table('S002V01TSTAR')->insertGetId([
  2594. 'STAR_NULI' => $requestData['NUMERO_LINEA'],
  2595. 'STAR_IDIS' => $idInfoStock,
  2596. 'STAR_COBA' => $uniqueBarcode === true ? $arrBarcode[0] : $arrBarcode[$i],
  2597. 'STAR_FEVE' => $dueDate,
  2598. 'STAR_IDUN' => $idun,
  2599. 'STAR_NUPR' => $nupr,
  2600. 'STAR_TIAD' => $tiad,
  2601. 'STAR_IDPC' => $preCodificate,
  2602. 'STAR_CONS' => $requestData['CONSUMIBLE'] ? 'Si' : 'No',
  2603. 'STAR_REPA' => $requestData['REPARABLE'] ? 'Si' : 'No',
  2604. 'STAR_PRAD' => $prad,
  2605. 'STAR_COMO' => $como,
  2606. 'STAR_ESTA' => 'Pendiente',
  2607. 'STAR_USRE' => $user,
  2608. 'STAR_FERE' => $currentDate,
  2609. 'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2610. ]);
  2611. } catch (\Throwable $th) {
  2612. DB::rollBack();
  2613. return $this->responseController->makeResponse(true, 'Ocurrió un error al registrar el equipamiento.', $th->getMessage(), 500);
  2614. }
  2615. if ($idInsertStAr === false || is_null($idInsertStAr)) {
  2616. DB::rollBack();
  2617. return $this->responseController->makeResponse(true, 'No se pudo registrar el equipamiento.', [], 500);
  2618. }
  2619. try {
  2620. $preCodeCodificate = $this->encController->decrypt($requestData['PRE_GENERATED_CODE']);
  2621. } catch (\Throwable $th) {
  2622. DB::rollBack();
  2623. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el pre-código generado', $th->getMessage(), 500);
  2624. }
  2625. if ( $preCodeCodificate === false ) {
  2626. DB::rollBack();
  2627. return $this->responseController->makeResponse(true, 'No se pudo desencriptar el pre-código del equipamientos.', [], 500);
  2628. }
  2629. try {
  2630. $validateInsertUbAr = DB::table('S002V01TUBAR')->insert([
  2631. 'UBAR_NULI' => $requestData['NUMERO_LINEA'],
  2632. 'UBAR_COAL' => $idWarehouse,
  2633. 'UBAR_COAR' => $idArea,
  2634. 'UBAR_CONI' => $idLevel,
  2635. 'UBAR_COZO' => $idZone,
  2636. 'UBAR_IDST' => $idInsertStAr,
  2637. 'UBAR_COUB' => $preCodeCodificate,
  2638. 'UBAR_ESTA' => 'Pendiente',
  2639. 'UBAR_USRE' => $user,
  2640. 'UBAR_FERE' => $currentDate,
  2641. 'UBAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2642. ]);
  2643. } catch (\Throwable $th) {
  2644. DB::rollBack();
  2645. return $this->responseController->makeResponse(true, 'Ocurrió un error al registrar la ubicación del artículo.', $th->getMessage(), 500);
  2646. }
  2647. if ( $validateInsertUbAr === false ) {
  2648. DB::rollBack();
  2649. return $this->responseController->makeResponse(true, 'No se pudo registrar la ubicación del artículo.', [], 500);
  2650. }
  2651. try {
  2652. $idas = isset($info) ? $info[$i]['NUMERO_SELECCIONADO'] : 0;
  2653. $idar = isset($info) ? $info[$i]['ID_ARTICULO'] : 0;
  2654. $nupr = isset($info) ? $info[$i]['NUMERO_PROVEEDOR'] : 0;
  2655. $idli = array_key_exists('ID_LINEA_SOLICITUD', $orden) ? $orden['ID_LINEA_SOLICITUD'] : 0;
  2656. $validateUpdateArSe = DB::table('S002V01TARSE')
  2657. ->where('ARSE_IDAS', '=', $idas)
  2658. ->where('ARSE_NULI', '=', $requestData['NUMERO_LINEA'])
  2659. ->where('ARSE_IDLI', '=', $idli)
  2660. ->where('ARSE_IDAR', '=', $idar)
  2661. ->where('ARSE_NUPR', '=', $nupr)
  2662. ->where('ARSE_IDIN', '=', $requestData['ID_INFORMATION'])
  2663. ->where('ARSE_ESTA', '=', 'Activo')
  2664. ->update([
  2665. 'ARSE_ESTA' => 'Guardado',
  2666. 'ARSE_USMO' => $user,
  2667. 'ARSE_FEMO' => $currentDate,
  2668. 'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2669. ]);
  2670. } catch (\Throwable $th) {
  2671. DB::rollBack();
  2672. return $this->responseController->makeResponse(true, 'Ocurrió un error al modificar el artículo seleccionado.', $th->getMessage(), 500);
  2673. }
  2674. if ($validateUpdateArSe === false) {
  2675. DB::rollBack();
  2676. return $this->responseController->makeResponse(true, 'No se pudo modificar el artículo seleccionado.', [], 500);
  2677. }
  2678. }
  2679. DB::commit();
  2680. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  2681. }
  2682. // FUNCIÓN INTERCAMBIO DE ARTICULOS ENTRE ALMACENES
  2683. public function getCurrentLocationArtitles($user, $line) {
  2684. try {
  2685. $arrStockArtitle = DB::table('S002V01TSTAR')
  2686. ->where('STAR_NULI', '=', $line)
  2687. ->where('STAR_ESTA', '=', 'Activo')
  2688. ->where('INST_NULI', '=', $line)
  2689. ->where('INST_ESTA', '=', 'Activo')
  2690. ->where('UBAR_ESTA', '=', 'Activo')
  2691. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  2692. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  2693. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  2694. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  2695. ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  2696. ->join('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  2697. ->join('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  2698. ->join('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  2699. ->orderBy('ID_STOCK', 'DESC')
  2700. ->get([
  2701. 'STAR_IDST AS ID_STOCK',
  2702. 'INST_IDIS AS ID_INFORMACION_STOCK',
  2703. 'FAMI_COFA AS CODIGO_FAMILIA',
  2704. 'FAMI_NOFA AS NOMBRE_FAMILIA',
  2705. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  2706. 'SUBF_NOSU AS NOMBRE_SUBFAMILIA',
  2707. 'INST_ARTI AS ARTITULO',
  2708. 'INST_MODE AS MODELO',
  2709. 'INST_COMO AS CODIGO_MODELO',
  2710. 'INST_IMAG AS IMAGENES',
  2711. 'UBAR_COUB AS CODIGO',
  2712. DB::raw('CONCAT(ALMA_NOAL, " (", ALMA_COAL, ")") AS NOMBRE_ALMACEN'),
  2713. DB::raw('CONCAT(AREA_NOAR, " (", AREA_COAR, ")") AS NOMBRE_AREA'),
  2714. DB::raw('CONCAT(NIVE_NONI, " (", NIVE_CONI, ")") AS NOMBRE_NIVEL'),
  2715. DB::raw('CONCAT(ZONA_NOZO, " (", ZONA_COZO, ")") AS NOMBRE_ZONA'),
  2716. ]);
  2717. $arrStockArtitle = json_decode(json_encode($arrStockArtitle), true);
  2718. } catch (\Throwable $th) {
  2719. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  2720. }
  2721. foreach ($arrStockArtitle as $key => $stockArtitle) {
  2722. $imagesGallery = [];
  2723. $arrImages = json_decode($stockArtitle['IMAGENES']);
  2724. foreach($arrImages as $image) {
  2725. $imageCodeEnc = $this->encController->encrypt($image);
  2726. $response = $this->documentManagementController->privateGetPublicDocumentURL(
  2727. $imageCodeEnc,
  2728. $user,
  2729. $line
  2730. );
  2731. if($response['error']){
  2732. return $this->responseController->makeresponse(true, $response['msg'], [], 500);
  2733. }
  2734. $imagesGallery[] = $response['response']['public_uri'];
  2735. }
  2736. $stockArtitle['IMAGENES'] = $imagesGallery;
  2737. $arrStockArtitle[$key] = $stockArtitle;
  2738. }
  2739. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStockArtitle);
  2740. }
  2741. // FUNCIÓN PARA JOSÉ LUIS
  2742. public function getInfoStock($user, $line) {
  2743. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  2744. if ($arrResponseCheckUser['error']) {
  2745. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  2746. }
  2747. try {
  2748. $arrStockArtitle = DB::table('S002V01TSTAR')
  2749. ->where('STAR_NULI', '=', $line)
  2750. ->where('STAR_ESTA', '=', 'Activo')
  2751. ->where('INST_NULI', '=', $line)
  2752. ->where('INST_ESTA', '=', 'Activo')
  2753. ->where('UBAR_ESTA', '=', 'Activo')
  2754. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  2755. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  2756. ->get([
  2757. 'STAR_IDST AS ID_STOCK',
  2758. 'INST_MODE AS MODELO',
  2759. 'INST_COMO AS CODIGO_MODELO',
  2760. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  2761. 'STAR_CONS AS CONSUMIBLE',
  2762. 'STAR_REPA AS REPARABLE',
  2763. ]);
  2764. } catch (\Throwable $th) {
  2765. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  2766. }
  2767. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStockArtitle);
  2768. }
  2769. public function moveToStock(Request $request, string $idStock ) {
  2770. $validator = Validator::make($request->all(), [
  2771. 'ALMACEN' => 'required|string',
  2772. 'AREA' => 'required|string',
  2773. 'NIVEL' => 'required|string',
  2774. 'ZONA' => 'required|string',
  2775. 'FAMILIA' => 'required|string',
  2776. 'SUBFAMILIA' => 'required|string',
  2777. 'LINEA' => 'required|string',
  2778. 'TIPO' => 'required|string',
  2779. 'MODELO' => 'required|string',
  2780. 'ID_EQUIPMENTO' => 'required|string',
  2781. 'STATUS' => 'required|string',
  2782. 'CODIGO_EQUIPAMIENTO' => 'required|string',
  2783. 'USUARIO' => 'required|string',
  2784. 'NUMERO_LINEA' => 'required|integer',
  2785. ]);
  2786. if($validator->fails()){
  2787. return $this->responseController->makeResponse(
  2788. true,
  2789. "Se encontraron uno o más errores.",
  2790. $this->responseController->makeErrors(
  2791. $validator->errors()->messages()
  2792. ),
  2793. 401
  2794. );
  2795. }
  2796. DB::beginTransaction();
  2797. $requestData = $request->all();
  2798. $arrInfoRegistro = array();
  2799. $arrToWorkflow = array();
  2800. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  2801. if ($arrResponseCheckUser['error']) {
  2802. DB::rollBack();
  2803. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  2804. }
  2805. $user = $arrResponseCheckUser['response'];
  2806. // Se obtiene el identificador del stock
  2807. $idStock = $this->encController->decrypt($idStock);
  2808. if ($idStock === false) {
  2809. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el stock.', [], 406);
  2810. }
  2811. // Se obtiene el valor del almacen
  2812. $requestData['ALMACEN'] = $this->encController->decrypt($requestData['ALMACEN']);
  2813. if ($requestData['ALMACEN'] === false) {
  2814. DB::rollBack();
  2815. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el ID del almacen.', [], 406);
  2816. }
  2817. // Se obtiene el valor del area
  2818. $requestData['AREA'] = $this->encController->decrypt($requestData['AREA']);
  2819. if ($requestData['AREA'] === false) {
  2820. DB::rollBack();
  2821. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el ID del área.', [], 406);
  2822. }
  2823. // Se obtiene el valor del nivel
  2824. $requestData['NIVEL'] = $this->encController->decrypt($requestData['NIVEL']);
  2825. if ($requestData['NIVEL'] === false) {
  2826. DB::rollBack();
  2827. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el ID del nivel.', [], 406);
  2828. }
  2829. // Se obtiene el valor de la zona
  2830. $requestData['ZONA'] = $this->encController->decrypt($requestData['ZONA']);
  2831. if ($requestData['ZONA'] === false) {
  2832. DB::rollBack();
  2833. return $this->responseController->makeResponse(true, 'Ocurrió un error al desencriptar el ID de la zona.', [], 406);
  2834. }
  2835. // Se verifica el código del artículo que sea válido
  2836. $codeVerified = $this->verifyPreCode($requestData);
  2837. if ($codeVerified !== $requestData['CODIGO_EQUIPAMIENTO']) {
  2838. DB::rollBack();
  2839. return $this->responseController->makeResponse(true, 'El código generado no coincide con el código verificado a partir de la información del formulario.', [], 406);
  2840. }
  2841. // Se verifica que el código no sea el mismo que el anterior
  2842. if ($requestData['ANTERIOR_CODIGO_EQUIPAMIENTO'] === $requestData['CODIGO_EQUIPAMIENTO']) {
  2843. DB::rollBack();
  2844. return $this->responseController->makeResponse(true, 'Los códigos no deben ser los mismos.', [], 406);
  2845. }
  2846. // Se verifica que la información del almacen exista
  2847. try {
  2848. $validateWarehouse = DB::table('S002V01TALMA')
  2849. ->where('ALMA_COAL', '=', $requestData['ALMACEN'])
  2850. ->where('ALMA_NULI', '=', $requestData['NUMERO_LINEA'])
  2851. ->exists();
  2852. } catch (\Throwable $th) {
  2853. DB::rollBack();
  2854. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el almacen existe.', $th->getMessage(), 500);
  2855. }
  2856. if ($validateWarehouse === false) {
  2857. DB::rollBack();
  2858. return $this->responseController->makeResponse(true, 'El almacen no existe.', [], 500);
  2859. }
  2860. // Se verifica que la informacion del área exista
  2861. try {
  2862. $validateArea = DB::table('S002V01TAREA')
  2863. ->where('AREA_COAL', '=', $requestData['ALMACEN'])
  2864. ->where('AREA_COAR', '=', $requestData['AREA'])
  2865. ->where('AREA_NULI', '=', $requestData['NUMERO_LINEA'])
  2866. ->exists();
  2867. } catch (\Throwable $th) {
  2868. DB::rollBack();
  2869. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el área existe.', $th->getMessage(), 500);
  2870. }
  2871. if ($validateArea === false) {
  2872. DB::rollBack();
  2873. return $this->responseController->makeResponse(true, 'El área no existe.', [], 500);
  2874. }
  2875. // Se verifica que la información del nivel exista
  2876. try {
  2877. $validateLevel = DB::table('S002V01TNIVE')
  2878. ->where('NIVE_COAL', '=', $requestData['ALMACEN'])
  2879. ->where('NIVE_COAR', '=', $requestData['AREA'])
  2880. ->where('NIVE_CONI', '=', $requestData['NIVEL'])
  2881. ->where('NIVE_NULI', '=', $requestData['NUMERO_LINEA'])
  2882. ->exists();
  2883. } catch (\Throwable $th) {
  2884. DB::rollBack();
  2885. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si el nivel existe.', $th->getMessage(), 500);
  2886. }
  2887. if ($validateLevel === false) {
  2888. DB::rollBack();
  2889. return $this->responseController->makeResponse(true, 'El nivel no existe.', [], 500);
  2890. }
  2891. // Se verifica que la información de la zona
  2892. try {
  2893. $validateZone = DB::table('S002V01TZONA')
  2894. ->where('ZONA_COAL', '=', $requestData['ALMACEN'])
  2895. ->where('ZONA_COAR', '=', $requestData['AREA'])
  2896. ->where('ZONA_CONI', '=', $requestData['NIVEL'])
  2897. ->where('ZONA_COZO', '=', $requestData['ZONA'])
  2898. ->where('ZONA_NULI', '=', $requestData['NUMERO_LINEA'])
  2899. ->exists();
  2900. } catch (\Throwable $th) {
  2901. DB::rollBack();
  2902. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si la zona existe.', $th->getMessage(), 500);
  2903. }
  2904. if ($validateZone === false) {
  2905. return $this->responseController->makeResponse(true, 'La zona no existe.', [], 500);
  2906. }
  2907. $arrToWorkflow[] = [
  2908. 'ANTERIOR_CODIGO_EQUIPAMIENTO' => $requestData['ANTERIOR_CODIGO_EQUIPAMIENTO'],
  2909. 'NUEVO_CODIGO_EQUIPAMIENTO' => $requestData['CODIGO_EQUIPAMIENTO'],
  2910. 'ALMACEN' => $requestData['ALMACEN'],
  2911. 'AREA' => $requestData['AREA'],
  2912. 'NIVEL' => $requestData['NIVEL'],
  2913. 'ZONA' => $requestData['ZONA'],
  2914. ];
  2915. $strToWorkflow = json_encode($arrToWorkflow);
  2916. $encToWorkflow = $this->encController->encrypt($strToWorkflow);
  2917. $now = $this->functionsController->now();
  2918. $currentDate = $now->toDateTimeString();
  2919. try {
  2920. $validateUpdate = DB::table('S002V01TUBAR')
  2921. ->where('UBAR_IDST', '=', $idStock)
  2922. ->where('UBAR_COUB', '=', $requestData['ANTERIOR_CODIGO_EQUIPAMIENTO'])
  2923. ->where('UBAR_ESTA', '=', 'Activo')
  2924. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  2925. ->update([
  2926. 'UBAR_ESTA' => 'Obsoleto',
  2927. 'UBAR_USMO' => $user,
  2928. 'UBAR_FEMO' => $currentDate,
  2929. 'UBAR_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  2930. ]);
  2931. } catch (\Throwable $th) {
  2932. DB::rollBack();
  2933. return $this->responseController->makeResponse(true, 'Ocurrió un error al modificar el estado actual del código del stock.', $th->getMessage(), 406);
  2934. }
  2935. if (!$validateUpdate) {
  2936. DB::rollBack();
  2937. return $this->responseController->makeResponse(true, 'No se pudo modificar el estado actual del código del stock.', [], 406);
  2938. }
  2939. try {
  2940. $idUbication = DB::table('S002V01TUBAR')->insertGetId([
  2941. 'UBAR_NULI' => $requestData['NUMERO_LINEA'],
  2942. 'UBAR_COAL' => $requestData['ALMACEN'],
  2943. 'UBAR_COAR' => $requestData['AREA'],
  2944. 'UBAR_CONI' => $requestData['NIVEL'],
  2945. 'UBAR_COZO' => $requestData['ZONA'],
  2946. 'UBAR_IDST' => $idStock,
  2947. 'UBAR_COUB' => $requestData['CODIGO_EQUIPAMIENTO'],
  2948. 'UBAR_ESTA' => 'Workflow',
  2949. 'UBAR_USRE' => $user,
  2950. 'UBAR_FERE' => $currentDate,
  2951. 'UBAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  2952. ]);
  2953. } catch (\Throwable $th) {
  2954. DB::rollBack();
  2955. return $this->responseController->makeResponse(true, 'Ocurrió un error al insertar la nueva ubicación del artículo.', $th->getMessage(), 406);
  2956. }
  2957. if (!$idUbication) {
  2958. DB::rollBack();
  2959. return $this->responseController->makeResponse(true, 'No se pudo insertar la nueva ubicación del artículo.', [], 406);
  2960. }
  2961. $arrInfoRegistro['S002V01TUBAR'][] = [
  2962. 'UBAR_IDUB' => $idUbication,
  2963. 'UBAR_IDST' => $idStock,
  2964. 'UBAR_COUB' => $requestData['CODIGO_EQUIPAMIENTO'],
  2965. ];
  2966. try {
  2967. $equipment = (array) DB::table('S002V01TEQUI')
  2968. ->where('EQUI_COEQ', '=', $requestData['ANTERIOR_CODIGO_EQUIPAMIENTO'])
  2969. ->where('EQUI_NULI', '=', $requestData['NUMERO_LINEA'])
  2970. ->first();
  2971. } catch (\Throwable $th) {
  2972. DB::rollBack();
  2973. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del artículo.', $th->getMessage(), 406);
  2974. }
  2975. if (is_null($equipment) || empty($equipment)) {
  2976. DB::rollBack();
  2977. return $this->responseController->makeResponse(true, 'No se se pudo obtener la información del equipamiento.', [], 406);
  2978. }
  2979. $strHistorial = $equipment['EQUI_HICO'];
  2980. $arrHistorial = json_decode($strHistorial, true);
  2981. $arrHistorial[] = [
  2982. "FECHA" => $currentDate,
  2983. "PADRE" => null,
  2984. "CODIGO" => $requestData['CODIGO_EQUIPAMIENTO'],
  2985. ];
  2986. $strHistorial = json_encode($arrHistorial);
  2987. try {
  2988. $validateUpdate = DB::table('S002V01TEQUI')
  2989. ->where('EQUI_COEQ', '=', $requestData['ANTERIOR_CODIGO_EQUIPAMIENTO'])
  2990. ->where('EQUI_NULI', '=', $requestData['NUMERO_LINEA'])
  2991. ->update([
  2992. 'EQUI_COEQ' => $requestData['CODIGO_EQUIPAMIENTO'],
  2993. 'EQUI_ALMA' => $requestData['ALMACEN'],
  2994. 'EQUI_AREA' => $requestData['AREA'],
  2995. 'EQUI_NIVE' => $requestData['NIVEL'],
  2996. 'EQUI_ZONA' => $requestData['ZONA'],
  2997. 'EQUI_HICO' => $strHistorial,
  2998. 'EQUI_USMO' => $user,
  2999. 'EQUI_FEMO' => $currentDate,
  3000. 'EQUI_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  3001. ]);
  3002. } catch (\Throwable $th) {
  3003. DB::rollBack();
  3004. return $this->responseController->makeResponse(true, 'Ocurrió un error al modificar el equipamiento.', $th->getMessage(), 406);
  3005. }
  3006. if (!$validateUpdate) {
  3007. DB::rollBack();
  3008. return $this->responseController->makeResponse(true, 'No se pudo modificar el equipamiento.', [], 406);
  3009. }
  3010. try {
  3011. $existsEquipmentWorkflow = DB::table('S002V01TEQWO')
  3012. ->where('EQWO_COEQ', '=', $requestData['CODIGO_EQUIPAMIENTO'])
  3013. ->where('EQWO_NULI', '=', $requestData['NUMERO_LINEA'])
  3014. ->where('EQWO_ESTA', '=', 'En Workflow')
  3015. ->exists();
  3016. } catch (\Throwable $th) {
  3017. DB::rollBack();
  3018. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el estado del equipamiento.', $th->getMessage(), 406);
  3019. }
  3020. if ( !$existsEquipmentWorkflow ) {
  3021. try {
  3022. $idEquipmentWorkflow = DB::table('S002V01TEQWO')->insertGetId([
  3023. 'EQWO_NULI' => $requestData['NUMERO_LINEA'],
  3024. 'EQWO_COEQ' => $requestData['CODIGO_EQUIPAMIENTO'],
  3025. 'EQWO_ESTA' => 'En Workflow',
  3026. 'EQWO_USRE' => $user,
  3027. 'EQWO_FERE' => $currentDate,
  3028. 'EQWO_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  3029. ]);
  3030. } catch (\Throwable $th) {
  3031. DB::rollBack();
  3032. return $this->responseController->makeResponse(true, 'Ocurrió un error al registrar el equipamiento en el workflow.', $th->getMessage(), 406);
  3033. }
  3034. if (!$idEquipmentWorkflow) {
  3035. DB::rollBack();
  3036. return $this->responseController->makeResponse(true, 'No se pudo registrar el equipamiento en el workflow.', [], 406);
  3037. }
  3038. $arrInfoRegistro['S002V01TEQWO'][] = [
  3039. 'EQWO_IDEW' => $idEquipmentWorkflow,
  3040. 'EQWO_COEQ' => $requestData['CODIGO_EQUIPAMIENTO'],
  3041. ];
  3042. } else {
  3043. DB::rollBack();
  3044. return $this->responseController->makeResponse(true, 'No se pudo hacer el intercambio si el equipamiento se encuentra en proceso de validación.', [], 406);
  3045. }
  3046. $strInfoRegistro = json_encode($arrInfoRegistro);
  3047. $encInfoRegistro = $this->encController->encrypt($strInfoRegistro);
  3048. /*
  3049. TABLA: S002V01TPRWO
  3050. [
  3051. {
  3052. "TABLA": "S002V01TEQWO",
  3053. "CAMPO_ESTADO": "EQWO_ESTA",
  3054. "NUMERO_LINEA": "EQWO_NULI",
  3055. "CAMBIO_ESTADO": "Finalizado",
  3056. "FECHA_MODIFICA": "EQWO_FEMO",
  3057. "FECHA_REGISTRA": "EQWO_FERE",
  3058. "USUARIO_MODIFICA": "EQWO_USMO",
  3059. "USUARIO_REGISTRA": "EQWO_USRE"
  3060. },
  3061. {
  3062. "TABLA": "S002V01TUBAR",
  3063. "CAMPO_ESTADO": "UBAR_ESTA",
  3064. "NUMERO_LINEA": "UBAR_NULI",
  3065. "CAMBIO_ESTADO": "Activo",
  3066. "FECHA_MODIFICA": "UBAR_FEMO",
  3067. "FECHA_REGISTRA": "UBAR_FERE",
  3068. "USUARIO_MODIFICA": "UBAR_USMO",
  3069. "USUARIO_REGISTRA": "UBAR_USRE"
  3070. }
  3071. ] */
  3072. $arrResponseRequestWorkflow = $this->processManagementController->registerRequestWorkflow(2, $encToWorkflow, $encInfoRegistro, $user, $requestData['NUMERO_LINEA']);
  3073. if ($arrResponseRequestWorkflow['error']) {
  3074. DB::rollBack();
  3075. return $this->responseController->makeResponse(true, $arrResponseRequestWorkflow['msg'], $arrResponseRequestWorkflow['response'], 500);
  3076. }
  3077. DB::commit();
  3078. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  3079. }
  3080. private function verifyPreCode(array $parameters) {
  3081. $siteTag = '';
  3082. $site = ['LINEA', 'AREA', 'NIVEL'];
  3083. foreach($site as $ctrl){
  3084. $val = $parameters[$ctrl];
  3085. if($ctrl == 'LINE'){
  3086. $val = intval($val) < 10 ? "0$val" : "$val";
  3087. }
  3088. $siteTag .= $val.'.';
  3089. }
  3090. $siteTag = substr($siteTag, 0, -1);
  3091. $areaTag = '';
  3092. $area = ['ALMACEN', 'ZONA'];
  3093. foreach($area as $ctrl){
  3094. $val = $parameters[$ctrl];
  3095. $areaTag .= $val.'.';
  3096. }
  3097. $areaTag = substr($areaTag, 0, -1);
  3098. $technicalSpecificationTag = '';
  3099. $technicalSpecification = ['FAMILIA', 'SUBFAMILIA', 'STATUS'];
  3100. foreach($technicalSpecification as $ctrl){
  3101. $val = $parameters[$ctrl];
  3102. $technicalSpecificationTag .= $val.'.';
  3103. }
  3104. $technicalSpecificationTag = substr($technicalSpecificationTag, 0, -1);
  3105. $equipmentIdentifierTag = '';
  3106. $equipmentIdentifier = ['TIPO', 'MODELO', 'ID_EQUIPMENTO'];
  3107. foreach($equipmentIdentifier as $ctrl){
  3108. $val = $parameters[$ctrl];
  3109. if($ctrl == 'MODELO'){
  3110. $val = $this->processElement($val, 'model');
  3111. }else if($ctrl == 'TIPO'){
  3112. $val = $this->processElement($val, 'element');
  3113. }
  3114. $equipmentIdentifierTag .= $val.'-';
  3115. }
  3116. $equipmentIdentifierTag = substr($equipmentIdentifierTag, 0, -1);
  3117. $code = $siteTag.'-'.$areaTag.'_'.$technicalSpecificationTag.'.'.$equipmentIdentifierTag;
  3118. return $code;
  3119. }
  3120. private function processElement(string $value, string $type) : string {
  3121. $value = strtoupper($value);
  3122. $validVal0 = $this->functionsController->unaccent($value);
  3123. $CONNECTORS = ['DE', 'PARA', 'Y', 'O', 'DEL', 'EL', 'LA', 'LOS', 'POR', 'EN'];
  3124. $valueArr1 = explode(' ', $validVal0);
  3125. $validVal1 = [];
  3126. foreach($valueArr1 as $word){
  3127. if(!in_array($word, $CONNECTORS)){
  3128. $validVal1[] = $word;
  3129. }
  3130. }
  3131. $validLength = count($validVal1);
  3132. $validVal2 = "";
  3133. if($validLength < 1){
  3134. return "ERROR";
  3135. }else if($validLength == 1){
  3136. if(strlen($validVal1[0]) < 5){
  3137. $validVal2 = $validVal1[0];
  3138. for($i = strlen($validVal1[0]); $i < 5; $i++){
  3139. if($type == 'model'){
  3140. $validVal2 = "X$validVal2";
  3141. }else{
  3142. $validVal2 = $validVal2 . "X";
  3143. }
  3144. }
  3145. }else{
  3146. $validVal2 = substr($validVal1[0], 0, 5);
  3147. }
  3148. }else if($validLength == 2){
  3149. $word1 = "";
  3150. if(strlen($validVal1[0]) < 2){
  3151. if($type == 'model'){
  3152. $word1 = "X$validVal1[0]";
  3153. }else{
  3154. $word1 = $validVal1[0] . "X";
  3155. }
  3156. }else{
  3157. $word1 = substr($validVal1[0], 0, 2);
  3158. }
  3159. $word2 = "";
  3160. if(strlen($validVal1[1]) < 3){
  3161. $word2 = $validVal1[1];
  3162. for($i = strlen($validVal1[1]); $i < 3; $i++){
  3163. if($type == 'model'){
  3164. $word2 = "X$word2";
  3165. }else{
  3166. $word2 = $word2 . "X";
  3167. }
  3168. }
  3169. }else{
  3170. $word2 = substr($validVal1[1], 0, 3);
  3171. }
  3172. $validVal2 = $word1 . $word2;
  3173. }else if($validLength == 3){
  3174. $word1 = "";
  3175. if(strlen($validVal1[0]) < 2){
  3176. if($type == 'model'){
  3177. $word1 = "X$validVal1[0]";
  3178. }else{
  3179. $word1 = $validVal1[0] . "X";
  3180. }
  3181. }else{
  3182. $word1 = substr($validVal1[0], 0, 2);
  3183. }
  3184. $word2 = substr($validVal1[1], 0, 1);
  3185. $word3 = "";
  3186. if(strlen($validVal1[2]) < 2){
  3187. if($type == 'model'){
  3188. $word3 = "X$validVal1[2]";
  3189. }else{
  3190. $word3 = $validVal1[2] . "X";
  3191. }
  3192. }else{
  3193. $word3 = substr($validVal1[2], 0, 2);
  3194. }
  3195. $validVal2 = $word1 . $word2 . $word3;
  3196. }else if($validLength == 4){
  3197. $word1 = "";
  3198. if(strlen($validVal1[0]) < 2){
  3199. if($type == 'model'){
  3200. $word1 = "X$validVal1[0]";
  3201. }else{
  3202. $word1 = $validVal1[0] . "X";
  3203. }
  3204. }else{
  3205. $word1 = substr($validVal1[0], 0, 2);
  3206. }
  3207. $word2 = substr($validVal1[1], 0, 1);
  3208. $word3 = substr($validVal1[2], 0, 1);
  3209. $word4 = substr($validVal1[3], 0, 1);
  3210. $validVal2 = $word1 . $word2 . $word3 . $word4;
  3211. }else if($validLength >= 5){
  3212. $word1 = substr($validVal1[0], 0, 1);
  3213. $word2 = substr($validVal1[1], 0, 1);
  3214. $word3 = substr($validVal1[2], 0, 1);
  3215. $word4 = substr($validVal1[3], 0, 1);
  3216. $word5 = substr($validVal1[4], 0, 1);
  3217. $validVal2 = $word1 . $word2 . $word3 . $word4 . $word5;
  3218. }else{
  3219. return "ERROR";
  3220. }
  3221. return $validVal2;
  3222. }
  3223. public function getLocationStock($user, $line) {
  3224. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3225. if ($arrResponseCheckUser['error']) {
  3226. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3227. }
  3228. try {
  3229. $arrLocation = DB::table('S002V01TUBAR')
  3230. ->where('UBAR_NULI', '=', $line)
  3231. ->where('UBAR_ESTA', '=', 'Activo')
  3232. ->whereOr('UBAR_ESTA', '=', 'Otro')
  3233. ->get([
  3234. DB::raw("CONCAT('#', UBAR_IDST) AS ID_STOCK"),
  3235. DB::raw("CONCAT('#', UBAR_IDUB) AS ID_UBICACION "),
  3236. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3237. 'UBAR_ESTA AS ESTADO',
  3238. 'UBAR_USRE AS USUARIO_REGISTRA',
  3239. 'UBAR_FERE AS FECHA_REGISTRA',
  3240. 'UBAR_USMO AS USUARIO_MODIFICA',
  3241. 'UBAR_FEMO AS FECHA_MODIFICA',
  3242. ]);
  3243. $arrLocation = json_decode(json_encode($arrLocation), true);
  3244. } catch (\Throwable $th) {
  3245. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el emplazamiento del stock.', $th->getMessage(), 500);
  3246. }
  3247. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrLocation, $line);
  3248. if ($responseCheckLatestUpdate['error']) {
  3249. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  3250. }
  3251. $arrLocation = $responseCheckLatestUpdate['response'];
  3252. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrLocation);
  3253. }
  3254. public function getLocationByStock($idStock, $user, $line) {
  3255. $idStock = $this->encController->decrypt($idStock);
  3256. if (is_null($idStock)) {
  3257. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID del Stock.', [], 401);
  3258. }
  3259. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3260. if ($arrResponseCheckUser['error']) {
  3261. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3262. }
  3263. try {
  3264. $arrLocation = DB::table('S002V01TUBAR')
  3265. ->where('UBAR_NULI', '=', $line)
  3266. ->where('UBAR_IDST', '=', $idStock)
  3267. ->orderBy('UBAR_IDUB', 'DESC')
  3268. ->get([
  3269. DB::raw("CONCAT('#', UBAR_IDUB) AS ID_UBICACION "),
  3270. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3271. 'UBAR_ESTA AS ESTADO',
  3272. 'UBAR_USRE AS USUARIO_REGISTRA',
  3273. 'UBAR_FERE AS FECHA_REGISTRA',
  3274. 'UBAR_USMO AS USUARIO_MODIFICA',
  3275. 'UBAR_FEMO AS FECHA_MODIFICA',
  3276. ]);
  3277. $arrLocation = json_decode(json_encode($arrLocation), true);
  3278. } catch (\Throwable $th) {
  3279. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el emplazamiento del stock.', $th->getMessage(), 500);
  3280. }
  3281. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrLocation, $line);
  3282. if ($responseCheckLatestUpdate['error']) {
  3283. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  3284. }
  3285. $arrLocation = $responseCheckLatestUpdate['response'];
  3286. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrLocation);
  3287. }
  3288. public function getDetaisLocation($idStock, $idLocation, $user, $line) {
  3289. $idStock = $this->encController->decrypt($idStock);
  3290. if (is_null($idStock)) {
  3291. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID del Stock.', [], 401);
  3292. }
  3293. $idLocation = $this->encController->decrypt($idLocation);
  3294. if (is_null($idLocation)) {
  3295. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la ubicación.', [], 401);
  3296. }
  3297. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3298. if ($arrResponseCheckUser['error']) {
  3299. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3300. }
  3301. try {
  3302. $arrLocation = (array) DB::table('S002V01TUBAR')
  3303. ->where('UBAR_NULI', '=', $line)
  3304. ->where('UBAR_IDST', '=', $idStock)
  3305. ->where('UBAR_IDUB', '=', $idLocation)
  3306. ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  3307. ->join('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  3308. ->join('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  3309. ->join('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  3310. ->first([
  3311. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3312. DB::raw('CONCAT(ALMA_NOAL, " (", ALMA_COAL, ")") AS ALMACEN'),
  3313. DB::raw('CONCAT(AREA_NOAR, " (", AREA_COAL, ")") AS AREA'),
  3314. DB::raw('CONCAT(NIVE_NONI, " (", NIVE_CONI, ")") AS NIVEL'),
  3315. DB::raw('CONCAT(ZONA_NOZO, " (", ZONA_COZO, ")") AS ZONA'),
  3316. 'UBAR_ESTA AS ESTADO',
  3317. ]);
  3318. } catch (\Throwable $th) {
  3319. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el emplazamiento del stock.', $th->getMessage(), 500);
  3320. }
  3321. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrLocation);
  3322. }
  3323. public function search(Request $request) {
  3324. $validator = Validator::make($request->all(), [
  3325. 'ID_STOCK' => 'nullable|string',
  3326. 'CODIGO_EQUIPAMIENTO' => 'nullable|string',
  3327. 'ID_UBICACION' => 'nullable|string',
  3328. 'FAMILIA' => 'nullable|string',
  3329. 'SUBFAMILIA' => 'nullable|string',
  3330. 'MODELO' => 'nullable|string',
  3331. 'CODIGO_MODELO' => 'nullable|string',
  3332. 'ALMACEN' => 'nullable|string',
  3333. 'AREA' => 'nullable|string',
  3334. 'NIVEL' => 'nullable|string',
  3335. 'ZONA' => 'nullable|string',
  3336. 'TIPO_ADQUISICION' => 'nullable|string',
  3337. 'NUMERO_PROVEEDOR' => 'nullable|string',
  3338. 'CODIGO_BARRAS' => 'nullable|string',
  3339. 'FECHA_VENCIMIENTO' => 'nullable|string',
  3340. 'TASA_ROTACION' => 'nullable|string',
  3341. 'STOCK_MINIMO' => 'nullable|string',
  3342. 'STOCK_MAXIMO' => 'nullable|string',
  3343. 'ESTADO' => 'nullable|string',
  3344. 'CONSUMIBLE' => 'nullable|string',
  3345. 'REPARABLE' => 'nullable|string',
  3346. 'USUARIO' => 'nullable|string',
  3347. 'NUMERO_LINEA' => 'nullable|string',
  3348. ]);
  3349. if ($validator->fails()) {
  3350. return $this->responseController->makeResponse(
  3351. true,
  3352. "Se encontraron uno o más errores.",
  3353. $this->responseController->makeErrors($validator->errors()->messages()),
  3354. 401
  3355. );
  3356. }
  3357. DB::beginTransaction();
  3358. $requestData = $request->all();
  3359. $arrClausules = [
  3360. 'FAMILIA' => 'INST_COFA',
  3361. 'SUBFAMILIA' => 'INST_COSU',
  3362. 'MODELO' => 'INST_MODE',
  3363. 'CODIGO_MODELO' => 'INST_COMO',
  3364. 'STOCK_MINIMO' => 'INST_STMI',
  3365. 'STOCK_MAXIMO' => 'INST_STMA',
  3366. 'ID_STOCK' => 'STAR_IDST',
  3367. 'CODIGO_BARRAS' => 'STAR_COBA',
  3368. 'FECHA_VENCIMIENTO' => 'STAR_FEVE',
  3369. 'NUMERO_PROVEEDOR' => 'STAR_NUPR',
  3370. 'TIPO_ADQUISICION' => 'STAR_TIAD',
  3371. 'CONSUMIBLE' => 'STAR_CONS',
  3372. 'REPARABLE' => 'STAR_REPA',
  3373. 'ESTADO' => 'STAR_ESTA',
  3374. 'ID_UBICACION' => 'UBAR_IDUB',
  3375. 'ALMACEN' => 'UBAR_COAL',
  3376. 'AREA' => 'UBAR_COAR',
  3377. 'NIVEL' => 'UBAR_CONI',
  3378. 'ZONA' => 'UBAR_COZO',
  3379. 'CODIGO_EQUIPAMIENTO' => 'UBAR_COUB',
  3380. ];
  3381. $arrWhere = array();
  3382. foreach ($requestData as $key => $value) {
  3383. if (!is_null($value) && $key !== 'USUARIO' && $key !== 'NUMERO_LINEA') {
  3384. $column = $arrClausules[$key];
  3385. $arrWhere[$column] = $value;
  3386. }
  3387. }
  3388. if (empty($arrWhere)) {
  3389. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", []);
  3390. }
  3391. try {
  3392. $arrInfo = DB::table('S002V01TSTAR')
  3393. ->where($arrWhere)
  3394. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  3395. ->where('INST_NULI', '=', $requestData['NUMERO_LINEA'])
  3396. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  3397. ->where('INST_ESTA', '=', 'Activo')
  3398. ->where('UBAR_ESTA', '=', 'Activo')
  3399. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  3400. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  3401. ->get([
  3402. 'STAR_IDST AS ID_STOCK',
  3403. 'INST_MODE AS MODELO',
  3404. 'INST_COMO AS CODIGO_MODELO',
  3405. 'INST_IMAG AS IMAGENES',
  3406. 'UBAR_COUB AS CODIGO',
  3407. ]);
  3408. $arrInfo = json_decode(json_encode($arrInfo), true);
  3409. } catch (\Throwable $th) {
  3410. return $this->responseController->makeResponse(true, "Ocurrió un error al recuperar la información.", $th->getMessage(), 500);
  3411. }
  3412. foreach ($arrInfo as $key => $info) {
  3413. $arrImages = json_decode($info['IMAGENES']);
  3414. $arrUrlImage = array();
  3415. foreach ($arrImages as $keyImages => $images) {
  3416. $images = $this->encController->encrypt($images);
  3417. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  3418. if ($responseDocument['error']) {
  3419. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  3420. }
  3421. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  3422. }
  3423. $arrInfo[$key]['IMAGENES'] = $arrUrlImage;
  3424. }
  3425. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInfo);
  3426. }
  3427. public function getInfoByStock($idStock, $user, $line) {
  3428. $idStock = $this->encController->decrypt($idStock);
  3429. if (is_null($idStock)) {
  3430. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID del Stock.', [], 401);
  3431. }
  3432. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3433. if ($arrResponseCheckUser['error']) {
  3434. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3435. }
  3436. try {
  3437. $arrInfo = (array) DB::table('S002V01TSTAR')
  3438. ->where('STAR_IDST', '=', $idStock)
  3439. ->where('STAR_NULI', '=', $line)
  3440. ->where('INST_NULI', '=', $line)
  3441. ->where('UBAR_NULI', '=', $line)
  3442. ->where('INST_ESTA', '=', 'Activo')
  3443. ->where('UBAR_ESTA', '=', 'Activo')
  3444. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  3445. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  3446. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  3447. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  3448. ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  3449. ->join('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  3450. ->join('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  3451. ->join('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  3452. ->join('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  3453. ->first([
  3454. DB::raw('CONCAT(FAMI_NOFA, " (", FAMI_COFA, ")") AS FAMILIA'),
  3455. DB::raw('CONCAT(SUBF_NOSU, " (", SUBF_COSU, ")") AS SUBFAMILIA'),
  3456. 'INST_MODE AS MODELO',
  3457. 'INST_COMO AS CODIGO_MODELO',
  3458. 'INST_STMI AS STOCK_MINIMO',
  3459. 'INST_STMA AS STOCK_MAXIMO',
  3460. 'STAR_IDST AS ID_STOCK',
  3461. 'STAR_COBA AS CODIGO_BARRAS',
  3462. 'STAR_FEVE AS FECHA_VENCIMIENTO',
  3463. DB::raw('CONCAT(PROV_NOCO, " (", PROV_NUPR, ")") AS NUMERO_PROVEEDOR'),
  3464. 'STAR_TIAD AS TIPO_ADQUISICION',
  3465. 'STAR_CONS AS CONSUMIBLE',
  3466. 'STAR_REPA AS REPARABLE',
  3467. 'STAR_ESTA AS ESTADO',
  3468. 'UBAR_IDUB AS ID_UBICACION',
  3469. DB::raw('CONCAT(ALMA_NOAL, " (", ALMA_COAL, ")") AS ALMACEN'),
  3470. DB::raw('CONCAT(AREA_NOAR, " (", AREA_COAR, ")") AS AREA'),
  3471. DB::raw('CONCAT(NIVE_NONI, " (", NIVE_CONI, ")") AS NIVEL'),
  3472. DB::raw('CONCAT(ZONA_NOZO, " (", ZONA_COZO, ")") AS ZONA'),
  3473. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3474. ]);
  3475. $arrInfo = json_decode(json_encode($arrInfo), true);
  3476. } catch (\Throwable $th) {
  3477. return $this->responseController->makeResponse(true, "Ocurrió un error al recuperar la información.", $th->getMessage(), 500);
  3478. }
  3479. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInfo);
  3480. }
  3481. public function getMaxMinStock($user, $line) {
  3482. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3483. if ($arrResponseCheckUser['error']) {
  3484. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3485. }
  3486. try {
  3487. $arrInfoStock = DB::table('S002V01TINST')
  3488. ->where('INST_NULI', '=', $line)
  3489. ->where('INST_ESTA', '=', 'Activo')
  3490. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  3491. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  3492. ->get([
  3493. 'INST_IDIS AS ID_INFORMACION_STOCK',
  3494. DB::raw('CONCAT(FAMI_NOFA, " (", FAMI_COFA, ")") AS FAMILIA'),
  3495. DB::raw('CONCAT(SUBF_NOSU, " (", SUBF_COSU, ")") AS SUBFAMILIA'),
  3496. 'INST_MODE AS MODELO',
  3497. 'INST_COMO AS CODIGO_MODELO',
  3498. 'INST_STMI AS STOCK_MINIMO',
  3499. 'INST_STMA AS STOCK_MAXIMO',
  3500. 'INST_IMAG AS IMAGENES',
  3501. ]);
  3502. $arrInfoStock = json_decode(json_encode($arrInfoStock), true);
  3503. } catch (\Throwable $th) {
  3504. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  3505. }
  3506. foreach ($arrInfoStock as $key => $info) {
  3507. $arrImages = json_decode($info['IMAGENES']);
  3508. $arrUrlImage = array();
  3509. foreach ($arrImages as $keyImages => $images) {
  3510. $images = $this->encController->encrypt($images);
  3511. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  3512. if ($responseDocument['error']) {
  3513. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  3514. }
  3515. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  3516. }
  3517. $arrInfoStock[$key]['IMAGENES'] = $arrUrlImage;
  3518. try {
  3519. $countStock = DB::table('S002V01TSTAR')
  3520. ->where('STAR_NULI', '=', $line)
  3521. ->where('STAR_IDIS', '=', $info['ID_INFORMACION_STOCK'])
  3522. ->where('STAR_ESTA', '=', 'Activo')
  3523. ->count();
  3524. } catch (\Throwable $th) {
  3525. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  3526. }
  3527. $arrInfoStock[$key]['CANTIDAD_ACTUAL'] = $countStock;
  3528. $stateStock = '';
  3529. if ($countStock < $info['STOCK_MINIMO'] && !is_null($info['STOCK_MINIMO'])) {
  3530. $stateStock = 'Menor al Stock Requerido';
  3531. } else if ($countStock > $info['STOCK_MAXIMO'] && !is_null($info['STOCK_MAXIMO'])) {
  3532. $stateStock = 'Exedente al Stock Requerido';
  3533. } else if (is_null($info['STOCK_MINIMO']) && is_null($info['STOCK_MAXIMO'])) {
  3534. $stateStock = 'No aplica';
  3535. } else {
  3536. $stateStock = 'Stock Normal';
  3537. }
  3538. if (is_null($info['STOCK_MINIMO'])) {
  3539. $arrInfoStock[$key]['STOCK_MINIMO'] = 'Sin Definir';
  3540. }
  3541. if (is_null($info['STOCK_MAXIMO'])) {
  3542. $arrInfoStock[$key]['STOCK_MAXIMO'] = 'Sin Definir';
  3543. }
  3544. $arrInfoStock[$key]['ESTADO'] = $stateStock;
  3545. }
  3546. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInfoStock);
  3547. }
  3548. public function updateStockMaxMin(Request $request, $idInfo) {
  3549. $validator = Validator::make($request->all(), [
  3550. 'STOCK_MINIMO' => 'required|integer',
  3551. 'STOCK_MAXIMO' => 'required|integer',
  3552. 'USUARIO' => 'required|string',
  3553. 'NUMERO_LINEA' => 'required|integer',
  3554. ]);
  3555. if($validator->fails()){
  3556. return $this->responseController->makeResponse(
  3557. true,
  3558. "Se encontraron uno o más errores.",
  3559. $this->responseController->makeErrors(
  3560. $validator->errors()->messages()
  3561. ),
  3562. 401
  3563. );
  3564. }
  3565. DB::beginTransaction();
  3566. $requestData = $request->all();
  3567. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  3568. if ($arrResponseCheckUser['error']) {
  3569. DB::rollBack();
  3570. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3571. }
  3572. $user = $arrResponseCheckUser['response'];
  3573. $idInfo = $this->encController->decrypt($idInfo);
  3574. if (is_null($idInfo)) {
  3575. DB::rollBack();
  3576. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  3577. }
  3578. try {
  3579. $validateExist = DB::table('S002V01TINST')
  3580. ->where('INST_NULI', '=', $requestData['NUMERO_LINEA'])
  3581. ->where('INST_IDIS', '=', $idInfo)
  3582. ->where('INST_ESTA', '=', 'Activo')
  3583. ->exists();
  3584. } catch (\Throwable $th) {
  3585. DB::rollBack();
  3586. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar si existe el artículo.', $th->getMessage(), 500);
  3587. }
  3588. if (!$validateExist) {
  3589. DB::rollBack();
  3590. return $this->responseController->makeResponse(true, 'El artículo no existe.', [], 401);
  3591. }
  3592. try {
  3593. $stockMin = intval($requestData['STOCK_MINIMO']);
  3594. } catch (\Throwable $th) {
  3595. DB::rollBack();
  3596. return $this->responseController->makeResponse(true, 'Ocurrió un error con el formato del stock mínimo.', $th->getMessage(), 500);
  3597. }
  3598. try {
  3599. $stockMax = intval($requestData['STOCK_MAXIMO']);
  3600. } catch (\Throwable $th) {
  3601. DB::rollBack();
  3602. return $this->responseController->makeResponse(true, 'Ocurrió un error con el formato del stock mínimo.', $th->getMessage(), 500);
  3603. }
  3604. if ($stockMin < 0) {
  3605. DB::rollBack();
  3606. return $this->responseController->makeResponse(true, 'La cantidad del stock mínimo no debe ser menor a 0.', [], 401);
  3607. }
  3608. if ($stockMax < 0) {
  3609. DB::rollBack();
  3610. return $this->responseController->makeResponse(true, 'La cantidad del stock máximo no debe ser menos a 0.', [], 401);
  3611. }
  3612. if ($stockMin > $stockMax) {
  3613. DB::rollBack();
  3614. return $this->responseController->makeResponse(true, 'La cantidad del stock mínimo no debe ser mayos al stock máximo.', [], 401);
  3615. }
  3616. $now = $this->functionsController->now();
  3617. $currentDate = $now->toDateTimeString();
  3618. try {
  3619. $validateUpdate = DB::table('S002V01TINST')
  3620. ->where('INST_NULI', '=', $requestData['NUMERO_LINEA'])
  3621. ->where('INST_IDIS', '=', $idInfo)
  3622. ->where('INST_ESTA', '=', 'Activo')
  3623. ->update([
  3624. 'INST_STMI' => $stockMin,
  3625. 'INST_STMA' => $stockMax,
  3626. 'INST_USMO' => $user,
  3627. 'INST_FEMO' => $currentDate,
  3628. 'INST_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  3629. ]);
  3630. } catch (\Throwable $th) {
  3631. DB::rollBack();
  3632. return $this->responseController->makeResponse(true, 'Ocurrió un error al modificar el stock mínimo y máximo.', $th->getMessage(), 500);
  3633. }
  3634. if (!$validateUpdate) {
  3635. DB::rollBack();
  3636. return $this->responseController->makeResponse(true, 'No se pudo modificar el stock mínimo y máximo.', [], 401);
  3637. }
  3638. DB::commit();
  3639. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  3640. }
  3641. public function getStockBarcode($user, $line) {
  3642. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3643. if ($arrResponseCheckUser['error']) {
  3644. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3645. }
  3646. try {
  3647. $arrStock = DB::table('S002V01TSTAR')
  3648. ->where('STAR_NULI', '=', $line)
  3649. ->where('STAR_ESTA', '=', 'Activo')
  3650. ->where('INST_NULI', '=', $line)
  3651. ->where('INST_ESTA', '=', 'Activo')
  3652. ->where('UBAR_NULI', '=', $line)
  3653. ->where('UBAR_ESTA', '=', 'Activo')
  3654. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  3655. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  3656. ->get([
  3657. 'STAR_IDST AS ID_STOCK',
  3658. 'INST_MODE AS MODELO',
  3659. 'INST_COMO AS CODIGO_MODELO',
  3660. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3661. 'STAR_COBA AS CODIGO_BARRA',
  3662. 'INST_IMAG AS IMAGENES',
  3663. ]);
  3664. $arrStock = json_decode(json_encode($arrStock), true);
  3665. } catch (\Throwable $th) {
  3666. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  3667. }
  3668. foreach ($arrStock as $key => $info) {
  3669. $arrImages = json_decode($info['IMAGENES']);
  3670. $arrUrlImage = array();
  3671. foreach ($arrImages as $keyImages => $images) {
  3672. $images = $this->encController->encrypt($images);
  3673. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  3674. if ($responseDocument['error']) {
  3675. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  3676. }
  3677. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  3678. }
  3679. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  3680. }
  3681. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStock);
  3682. }
  3683. public function updateStockBarcode(Request $request, $idStock) {
  3684. $validator = Validator::make($request->all(), [
  3685. 'BARCODE' => 'required|string',
  3686. 'USUARIO' => 'required|string',
  3687. 'NUMERO_LINEA' => 'required|integer',
  3688. ]);
  3689. if($validator->fails()){
  3690. return $this->responseController->makeResponse(
  3691. true,
  3692. "Se encontraron uno o más errores.",
  3693. $this->responseController->makeErrors(
  3694. $validator->errors()->messages()
  3695. ),
  3696. 401
  3697. );
  3698. }
  3699. DB::beginTransaction();
  3700. $requestData = $request->all();
  3701. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  3702. if ($arrResponseCheckUser['error']) {
  3703. DB::rollBack();
  3704. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3705. }
  3706. $user = $arrResponseCheckUser['response'];
  3707. $idStock = $this->encController->decrypt($idStock);
  3708. if (is_null($idStock)) {
  3709. DB::rollBack();
  3710. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  3711. }
  3712. try {
  3713. $validateExists = DB::table('S002V01TSTAR')
  3714. ->where('STAR_IDST', '=', $idStock)
  3715. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  3716. ->where('STAR_ESTA', '=', 'Activo')
  3717. ->exists();
  3718. } catch (\Throwable $th) {
  3719. DB::rollBack();
  3720. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el ID del stock.', $th->getMessage(), 500);
  3721. }
  3722. if (!$validateExists) {
  3723. DB::rollBack();
  3724. return $this->responseController->makeResponse(true, 'El número de stock no existe.', [], 500);
  3725. }
  3726. $now = $this->functionsController->now();
  3727. $currentDate = $now->toDateTimeString();
  3728. try {
  3729. $validateUpdate = DB::table('S002V01TSTAR')
  3730. ->where('STAR_IDST', '=', $idStock)
  3731. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  3732. ->where('STAR_ESTA', '=', 'Activo')
  3733. ->update([
  3734. 'STAR_COBA' => $requestData['BARCODE'],
  3735. 'STAR_USMO' => $user,
  3736. 'STAR_FEMO' => $currentDate,
  3737. 'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  3738. ]);
  3739. } catch (\Throwable $th) {
  3740. DB::rollBack();
  3741. return $this->responseController->makeResponse(true, 'Ocurrió un error modificar el código de barra.', $th->getMessage(), 500);
  3742. }
  3743. if (!$validateUpdate) {
  3744. DB::rollBack();
  3745. return $this->responseController->makeResponse(true, 'No se pudo modificar el código de barra.', [], 500);
  3746. }
  3747. DB::commit();
  3748. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  3749. }
  3750. public function getStockDueDate($user, $line) {
  3751. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3752. if ($arrResponseCheckUser['error']) {
  3753. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3754. }
  3755. try {
  3756. $arrStock = DB::table('S002V01TSTAR')
  3757. ->where('STAR_NULI', '=', $line)
  3758. ->where('STAR_ESTA', '=', 'Activo')
  3759. ->where('INST_NULI', '=', $line)
  3760. ->where('INST_ESTA', '=', 'Activo')
  3761. ->where('UBAR_NULI', '=', $line)
  3762. ->where('UBAR_ESTA', '=', 'Activo')
  3763. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  3764. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  3765. ->get([
  3766. 'STAR_IDST AS ID_STOCK',
  3767. 'INST_MODE AS MODELO',
  3768. 'INST_COMO AS CODIGO_MODELO',
  3769. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3770. 'STAR_FEVE AS FECHA_VENCIMIENTO',
  3771. 'INST_IMAG AS IMAGENES',
  3772. ]);
  3773. $arrStock = json_decode(json_encode($arrStock), true);
  3774. } catch (\Throwable $th) {
  3775. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  3776. }
  3777. foreach ($arrStock as $key => $info) {
  3778. $arrImages = json_decode($info['IMAGENES']);
  3779. $arrUrlImage = array();
  3780. foreach ($arrImages as $keyImages => $images) {
  3781. $images = $this->encController->encrypt($images);
  3782. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  3783. if ($responseDocument['error']) {
  3784. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  3785. }
  3786. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  3787. }
  3788. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  3789. if (is_null($info['FECHA_VENCIMIENTO'])) {
  3790. $arrStock[$key]['FECHA_VENCIMIENTO'] = 'Ninguno';
  3791. }
  3792. }
  3793. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStock);
  3794. }
  3795. public function updateDueDateStock(Request $request, $idStock) {
  3796. $validator = Validator::make($request->all(), [
  3797. 'FECHA_VENCIMIENTO' => 'required|string',
  3798. 'USUARIO' => 'required|string',
  3799. 'NUMERO_LINEA' => 'required|integer',
  3800. ]);
  3801. if($validator->fails()){
  3802. return $this->responseController->makeResponse(
  3803. true,
  3804. "Se encontraron uno o más errores.",
  3805. $this->responseController->makeErrors(
  3806. $validator->errors()->messages()
  3807. ),
  3808. 401
  3809. );
  3810. }
  3811. DB::beginTransaction();
  3812. $requestData = $request->all();
  3813. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  3814. if ($arrResponseCheckUser['error']) {
  3815. DB::rollBack();
  3816. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3817. }
  3818. $user = $arrResponseCheckUser['response'];
  3819. $idStock = $this->encController->decrypt($idStock);
  3820. if (is_null($idStock)) {
  3821. DB::rollBack();
  3822. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  3823. }
  3824. try {
  3825. $validateExists = DB::table('S002V01TSTAR')
  3826. ->where('STAR_IDST', '=', $idStock)
  3827. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  3828. ->where('STAR_ESTA', '=', 'Activo')
  3829. ->exists();
  3830. } catch (\Throwable $th) {
  3831. DB::rollBack();
  3832. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el ID del stock.', $th->getMessage(), 500);
  3833. }
  3834. if (!$validateExists) {
  3835. DB::rollBack();
  3836. return $this->responseController->makeResponse(true, 'El número de stock no existe.', [], 500);
  3837. }
  3838. $now = $this->functionsController->now();
  3839. $currentDate = $now->toDateTimeString();
  3840. try {
  3841. $validateUpdate = DB::table('S002V01TSTAR')
  3842. ->where('STAR_IDST', '=', $idStock)
  3843. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  3844. ->where('STAR_ESTA', '=', 'Activo')
  3845. ->update([
  3846. 'STAR_FEVE' => $requestData['FECHA_VENCIMIENTO'],
  3847. 'STAR_USMO' => $user,
  3848. 'STAR_FEMO' => $currentDate,
  3849. 'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  3850. ]);
  3851. } catch (\Throwable $th) {
  3852. DB::rollBack();
  3853. return $this->responseController->makeResponse(true, 'Ocurrió un error modificar la fecha de vencimiento.', $th->getMessage(), 500);
  3854. }
  3855. if (!$validateUpdate) {
  3856. DB::rollBack();
  3857. return $this->responseController->makeResponse(true, 'No se pudo modificar la fecha de vencimiento.', [], 500);
  3858. }
  3859. DB::commit();
  3860. return $this->responseController->makeResponse(false, "ÉXITO: Modificación Exitosa");
  3861. }
  3862. public function getDescriptionSheetStock($user, $line) {
  3863. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3864. if ($arrResponseCheckUser['error']) {
  3865. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3866. }
  3867. try {
  3868. $arrStock = DB::table('S002V01TSTAR')
  3869. ->where('STAR_NULI', '=', $line)
  3870. ->where('STAR_ESTA', '=', 'Activo')
  3871. ->where('INST_NULI', '=', $line)
  3872. ->where('INST_ESTA', '=', 'Activo')
  3873. ->where('UBAR_NULI', '=', $line)
  3874. ->where('UBAR_ESTA', '=', 'Activo')
  3875. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  3876. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  3877. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  3878. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  3879. ->get([
  3880. 'STAR_IDST AS ID_STOCK',
  3881. 'INST_MODE AS MODELO',
  3882. 'INST_COMO AS CODIGO_MODELO',
  3883. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3884. 'FAMI_NOFA AS FAMILIA',
  3885. 'SUBF_NOSU AS SUBFAMILIA',
  3886. 'INST_IMAG AS IMAGENES',
  3887. ]);
  3888. $arrStock = json_decode(json_encode($arrStock), true);
  3889. } catch (\Throwable $th) {
  3890. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  3891. }
  3892. foreach ($arrStock as $key => $info) {
  3893. $arrImages = json_decode($info['IMAGENES']);
  3894. $arrUrlImage = array();
  3895. foreach ($arrImages as $keyImages => $images) {
  3896. $images = $this->encController->encrypt($images);
  3897. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  3898. if ($responseDocument['error']) {
  3899. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  3900. }
  3901. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  3902. }
  3903. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  3904. }
  3905. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStock);
  3906. }
  3907. public function createDescriptionSheetStockXLS($idStock, $user, $line) {
  3908. $idStock = $this->encController->decrypt($idStock);
  3909. if (is_null($idStock)) {
  3910. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID del Stock.', [], 401);
  3911. }
  3912. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  3913. if ($arrResponseCheckUser['error']) {
  3914. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  3915. }
  3916. $user = $arrResponseCheckUser['response'];
  3917. try {
  3918. $arrStock = (array) DB::table('S002V01TSTAR')
  3919. ->where('STAR_IDST', '=', $idStock)
  3920. ->where('STAR_NULI', '=', $line)
  3921. ->where('INST_NULI', '=', $line)
  3922. ->where('UBAR_NULI', '=', $line)
  3923. ->where('INST_ESTA', '=', 'Activo')
  3924. ->where('UBAR_ESTA', '=', 'Activo')
  3925. ->where('STAR_ESTA', '=', 'Activo')
  3926. ->leftJoin('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  3927. ->leftJoin('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  3928. ->leftJoin('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  3929. ->leftJoin('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  3930. ->leftJoin('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  3931. ->leftJoin('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  3932. ->leftJoin('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  3933. ->leftJoin('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  3934. ->leftJoin('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  3935. ->first([
  3936. 'FAMI_COFA AS CODIGO_FAMILIA',
  3937. 'FAMI_NOFA AS FAMILIA',
  3938. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  3939. 'SUBF_NOSU AS SUBFAMILIA',
  3940. 'INST_MODE AS MODELO',
  3941. 'INST_COMO AS CODIGO_MODELO',
  3942. 'INST_STMI AS STOCK_MINIMO',
  3943. 'INST_STMA AS STOCK_MAXIMO',
  3944. 'STAR_IDST AS ID_STOCK',
  3945. 'STAR_COBA AS CODIGO_BARRAS',
  3946. 'STAR_FEVE AS FECHA_VENCIMIENTO',
  3947. 'STAR_NUPR AS NUMERO_PROVEEDOR',
  3948. 'PROV_NOCO AS PROVEEDOR',
  3949. 'STAR_TIAD AS TIPO_ADQUISICION',
  3950. 'STAR_CONS AS CONSUMIBLE',
  3951. 'STAR_REPA AS REPARABLE',
  3952. 'STAR_ESTA AS ESTADO',
  3953. 'UBAR_IDUB AS ID_UBICACION',
  3954. 'ALMA_COAL AS CODIGO_ALMACEN',
  3955. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  3956. 'AREA_COAR AS CODIGO_AREA',
  3957. 'AREA_NOAR AS NOMBRE_AREA',
  3958. 'NIVE_CONI AS CODIGO_NIVEL',
  3959. 'NIVE_NONI AS NOMBRE_NIVEL',
  3960. 'ZONA_COZO AS CODIGO_ZONA',
  3961. 'ZONA_NOZO AS NOMBRE_ZONA',
  3962. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  3963. ]);
  3964. } catch (\Throwable $th) {
  3965. return $this->responseController->makeResponse(true, "Ocurrió un error al recuperar la información.", $th->getMessage(), 500);
  3966. }
  3967. if (empty($arrStock) === 0) {
  3968. return $this->responseController->makeResponse(true, "No se encontró información del stock.", [], 500);
  3969. }
  3970. $spreadsheet = new Spreadsheet();
  3971. $activeWorksheet = $spreadsheet->getActiveSheet()->setTitle($arrStock['ID_STOCK']);
  3972. $cell = 1;
  3973. $activeWorksheet->setCellValue("A$cell", 'Código del Equipamiento');
  3974. $activeWorksheet->setCellValue("B$cell", $arrStock['CODIGO_EQUIPAMIENTO']);
  3975. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  3976. $cell++;
  3977. $activeWorksheet->setCellValue("A$cell", 'Familia');
  3978. $activeWorksheet->setCellValue("B$cell", $arrStock['FAMILIA'].' ('.$arrStock['CODIGO_FAMILIA'].')');
  3979. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  3980. $cell++;
  3981. $activeWorksheet->setCellValue("A$cell", 'Subfamilia');
  3982. $activeWorksheet->setCellValue("B$cell", $arrStock['SUBFAMILIA'].' ('.$arrStock['CODIGO_SUBFAMILIA'].')');
  3983. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  3984. $cell++;
  3985. $activeWorksheet->setCellValue("A$cell", 'Modelo');
  3986. $activeWorksheet->setCellValue("B$cell", $arrStock['MODELO']);
  3987. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  3988. $cell++;
  3989. $activeWorksheet->setCellValue("A$cell", 'Código Modelo');
  3990. $activeWorksheet->setCellValue("B$cell", $arrStock['CODIGO_MODELO']);
  3991. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  3992. $cell++;
  3993. $activeWorksheet->setCellValue("A$cell", 'Tipo de Adquisición');
  3994. $activeWorksheet->setCellValue("B$cell", $arrStock['TIPO_ADQUISICION']);
  3995. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  3996. $cell++;
  3997. if (!is_null($arrStock['NUMERO_PROVEEDOR'])) {
  3998. $activeWorksheet->setCellValue("A$cell", 'Proveedor');
  3999. $activeWorksheet->setCellValue("B$cell", $arrStock['PROVEEDOR'].' ('.$arrStock['NUMERO_PROVEEDOR'].')');
  4000. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4001. $cell++;
  4002. }
  4003. if (!is_null($arrStock['FECHA_VENCIMIENTO'])) {
  4004. $activeWorksheet->setCellValue("A$cell", 'Fecha de Vencimiento');
  4005. $activeWorksheet->setCellValue("B$cell", $arrStock['FECHA_VENCIMIENTO']);
  4006. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4007. $cell++;
  4008. }
  4009. $activeWorksheet->setCellValue("A$cell", 'Código de Barras');
  4010. $activeWorksheet->setCellValue("B$cell", $arrStock['CODIGO_BARRAS']);
  4011. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4012. $cell++;
  4013. if ( array_key_exists('TASA_ROTACION', $arrStock) ) {
  4014. $activeWorksheet->setCellValue("A$cell", 'Tasa de Rotación');
  4015. $activeWorksheet->setCellValue("B$cell", $arrStock['TASA_ROTACION']);
  4016. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4017. $cell++;
  4018. }
  4019. $activeWorksheet->setCellValue("A$cell", 'Stock Mínimo');
  4020. $activeWorksheet->setCellValue("B$cell", is_null($arrStock['STOCK_MINIMO']) ? 'Sin Definir' : $arrStock['STOCK_MINIMO']);
  4021. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4022. $cell++;
  4023. $activeWorksheet->setCellValue("A$cell", 'Stock Máximo');
  4024. $activeWorksheet->setCellValue("B$cell", is_null($arrStock['STOCK_MAXIMO']) ? 'Sin Definir' : $arrStock['STOCK_MAXIMO']);
  4025. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4026. $cell++;
  4027. $activeWorksheet->setCellValue("A$cell", '¿Es consumible?');
  4028. $activeWorksheet->setCellValue("B$cell", $arrStock['CONSUMIBLE']);
  4029. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4030. $cell++;
  4031. $activeWorksheet->setCellValue("A$cell", '¿Es reparable?');
  4032. $activeWorksheet->setCellValue("B$cell", $arrStock['REPARABLE']);
  4033. $activeWorksheet->getStyle( "A$cell" )->getFont()->setBold(true);
  4034. $cell++;
  4035. $activeWorksheet->getColumnDimension("A")->setAutoSize(true);
  4036. $activeWorksheet->getColumnDimension("B")->setAutoSize(true);
  4037. $nuli = $this->resourcesController->formatSecuence($line, 2);
  4038. $como = 'GIST'; // Código del módulo
  4039. $cldo = 'IN'; // Código de la clasificación
  4040. $fecr = date('ymd'); // Fecha en la se carga el archivo
  4041. try {
  4042. $arrSecuence = (array) DB::table('S002V01TAFAL')
  4043. ->where('AFAL_COMO', '=', $como)
  4044. ->where('AFAL_CLDO', '=', $cldo)
  4045. ->where('AFAL_NULI', '=', $line)
  4046. ->orderBy('AFAL_NUSE', 'desc')
  4047. ->first([ 'AFAL_NUSE' ]);
  4048. } catch (\Throwable $th) {
  4049. return $this->responseController->makeResponse(
  4050. true,
  4051. "ERR_PROVIDER_SHEET020: Ocurrió un error al obtener la información de la secuencia.",
  4052. $th->getMessage(),
  4053. 500
  4054. );
  4055. }
  4056. $nuse = 1; // Secuencia del documento
  4057. if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
  4058. $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1;
  4059. }
  4060. $nuse = $this->resourcesController->formatSecuence($nuse, 6);
  4061. $nuve = $this->resourcesController->formatSecuence('1', 2);
  4062. $noar = 'ficha_de_stock_'.$arrStock['ID_STOCK'];
  4063. $exte = 'xlsx';
  4064. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  4065. $filePath = $this->resourcesController->pathService.'\\public\\public_files\\'; // API JEAN
  4066. } else {
  4067. $filePath = $this->resourcesController->pathService.'\\public_files\\'; // API QA
  4068. }
  4069. $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;
  4070. $tempFile = $filePath.$fileName;
  4071. if ( file_exists( $tempFile ) ) {
  4072. if ( !unlink( $tempFile ) ) {
  4073. return $this->responseController->makeResponse(
  4074. true,
  4075. "ERR_PROVIDER_SHEET021: Ocurrió un error al eliminar el siguiente archivo: " . $tempFile,
  4076. [],
  4077. 500
  4078. );
  4079. }
  4080. }
  4081. try {
  4082. $writer = new Xlsx($spreadsheet);
  4083. ob_start();
  4084. $writer->save('php://output');
  4085. $base64 = base64_encode(ob_get_clean());
  4086. $validate = \File::put( $tempFile, base64_decode($base64));
  4087. } catch (\Throwable $th) {
  4088. return $this->responseController->makeResponse(
  4089. true,
  4090. "ERR_PROVIDER_SHEET022: Ocurrió un error al guardar el documento.",
  4091. $th->getMessage(),
  4092. 500
  4093. );
  4094. }
  4095. $ubic = Storage::putFile('files', new File($tempFile));
  4096. $ubic = str_replace("/", "\\", $ubic);
  4097. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  4098. $ubic = $this->resourcesController->pathService."\\storage\\app\\" . $ubic;
  4099. } else {
  4100. $ubic = $this->resourcesController->pathService."\\storage\\app\\" . $ubic;
  4101. }
  4102. $tama = filesize($ubic);
  4103. $usac = json_encode([$user]);
  4104. $now = $this->functionsController->now();
  4105. $currentDate = $now->toDateTimeString();
  4106. try {
  4107. $validateInsert = DB::table('S002V01TAFAL')->insert([
  4108. 'AFAL_NULI' => $line,
  4109. 'AFAL_COMO' => $como,
  4110. 'AFAL_CLDO' => $cldo,
  4111. 'AFAL_FECR' => $fecr,
  4112. 'AFAL_NUSE' => $nuse,
  4113. 'AFAL_NUVE' => $nuve,
  4114. 'AFAL_NOAR' => $noar,
  4115. 'AFAL_EXTE' => $exte,
  4116. 'AFAL_TAMA' => $tama,
  4117. 'AFAL_UBIC' => $ubic,
  4118. 'AFAL_USAC' => $usac,
  4119. 'AFAL_USRE' => $user,
  4120. 'AFAL_FERE' => $currentDate,
  4121. ]);
  4122. } catch (\Throwable $th) {
  4123. return $this->responseController->makeResponse(
  4124. true,
  4125. "ERR_PROVIDER_SHEET023: Ocurrió un error guardar los datos a la tabla final de archivos.",
  4126. $th->getMessage(),
  4127. 500
  4128. );
  4129. }
  4130. if ( !$validateInsert ) {
  4131. return $this->responseController->makeResponse(
  4132. true,
  4133. "ERR_PROVIDER_SHEET024: No se pudo guardar la ficha del proveedor en la base de datos.",
  4134. [],
  4135. 500
  4136. );
  4137. }
  4138. $encCode = $this->encController->encrypt($fileName);
  4139. try {
  4140. $validateInsert = DB::table('S002V01TDOST')->insert([
  4141. 'DOST_NULI' => $line,
  4142. 'DOST_IDST' => $idStock,
  4143. 'DOST_NODO' => 'Ficha de Stock #'.$arrStock['ID_STOCK'],
  4144. 'DOST_CODO' => $encCode,
  4145. 'DOST_EXTE' => $exte,
  4146. 'DOST_TAMA' => $tama,
  4147. 'DOST_CLAS' => 'IN',
  4148. 'DOST_VERS' => 1,
  4149. 'DOST_USRE' => $user,
  4150. 'DOST_FERE' => $currentDate,
  4151. 'DOST_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  4152. ]);
  4153. } catch (\Throwable $th) {
  4154. return $this->responseController->makeResponse(
  4155. true,
  4156. "Ocurrió un error guardar los datos a la tabla final de archivos.",
  4157. $th->getMessage(),
  4158. 500
  4159. );
  4160. }
  4161. if (!$validateInsert) {
  4162. return $this->responseController->makeResponse(
  4163. true,
  4164. "No se pudo guardar la ficha del proveedor en la base de datos.",
  4165. [],
  4166. 500
  4167. );
  4168. }
  4169. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  4170. $urlPublic = 'http://192.168.100.105:8000/public_files/' . $fileName;
  4171. } else {
  4172. $urlPublic = $this->functionsController->getApiURI().'sam/public_files/' . $fileName;
  4173. }
  4174. return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa", [ 'url' => $urlPublic ]);
  4175. }
  4176. public function createDescriptionSheetStockPDF($idStock, $user, $line) {
  4177. $idStock = $this->encController->decrypt($idStock);
  4178. if (is_null($idStock)) {
  4179. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID del Stock.', [], 401);
  4180. }
  4181. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  4182. if ($arrResponseCheckUser['error']) {
  4183. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4184. }
  4185. $user = $arrResponseCheckUser['response'];
  4186. try {
  4187. $arrStock = (array) DB::table('S002V01TSTAR')
  4188. ->where('STAR_IDST', '=', $idStock)
  4189. ->where('STAR_NULI', '=', $line)
  4190. ->where('INST_NULI', '=', $line)
  4191. ->where('UBAR_NULI', '=', $line)
  4192. ->where('INST_ESTA', '=', 'Activo')
  4193. ->where('UBAR_ESTA', '=', 'Activo')
  4194. ->where('STAR_ESTA', '=', 'Activo')
  4195. ->leftJoin('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  4196. ->leftJoin('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  4197. ->leftJoin('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  4198. ->leftJoin('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  4199. ->leftJoin('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  4200. ->leftJoin('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  4201. ->leftJoin('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  4202. ->leftJoin('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  4203. ->leftJoin('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  4204. ->first([
  4205. 'FAMI_COFA AS CODIGO_FAMILIA',
  4206. 'FAMI_NOFA AS FAMILIA',
  4207. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  4208. 'SUBF_NOSU AS SUBFAMILIA',
  4209. 'INST_MODE AS MODELO',
  4210. 'INST_COMO AS CODIGO_MODELO',
  4211. 'INST_STMI AS STOCK_MINIMO',
  4212. 'INST_STMA AS STOCK_MAXIMO',
  4213. 'STAR_IDST AS ID_STOCK',
  4214. 'STAR_COBA AS CODIGO_BARRAS',
  4215. 'STAR_FEVE AS FECHA_VENCIMIENTO',
  4216. 'PROV_NUPR AS NUMERO_PROVEEDOR',
  4217. 'PROV_NOCO AS PROVEEDOR',
  4218. 'STAR_TIAD AS TIPO_ADQUISICION',
  4219. 'STAR_CONS AS CONSUMIBLE',
  4220. 'STAR_REPA AS REPARABLE',
  4221. 'STAR_ESTA AS ESTADO',
  4222. 'UBAR_IDUB AS ID_UBICACION',
  4223. 'ALMA_COAL AS CODIGO_ALMACEN',
  4224. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  4225. 'AREA_COAR AS CODIGO_AREA',
  4226. 'AREA_NOAR AS NOMBRE_AREA',
  4227. 'NIVE_CONI AS CODIGO_NIVEL',
  4228. 'NIVE_NONI AS NOMBRE_NIVEL',
  4229. 'ZONA_COZO AS CODIGO_ZONA',
  4230. 'ZONA_NOZO AS NOMBRE_ZONA',
  4231. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  4232. ]);
  4233. } catch (\Throwable $th) {
  4234. return $this->responseController->makeResponse(true, "Ocurrió un error al recuperar la información.", $th->getMessage(), 500);
  4235. }
  4236. if (empty($arrStock) === 0) {
  4237. return $this->responseController->makeResponse(true, "No se encontró información del stock.", [], 500);
  4238. }
  4239. $html = '<!DOCTYPE html>
  4240. <html lang="en">
  4241. <head>
  4242. <meta charset="UTF-8">
  4243. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  4244. <title>Document</title>
  4245. <style>
  4246. body {
  4247. font-family: Arial, Helvetica, sans-serif;
  4248. font-size: 8pt;
  4249. }
  4250. .section-title {
  4251. margin: 20px 0;
  4252. font-size: 12pt;
  4253. }
  4254. table {
  4255. width: 100%;
  4256. font-size: 8pt;
  4257. }
  4258. thead tr th {
  4259. text-align: start;
  4260. padding: 0 16px;
  4261. height: 52px;
  4262. border-bottom-width: 1px;
  4263. border-bottom-style: solid;
  4264. border-bottom-color: #CCC;
  4265. }
  4266. tbody tr td {
  4267. padding: 0 16px;
  4268. height: 52px;
  4269. border-bottom-width: 1px;
  4270. border-bottom-style: solid;
  4271. border-bottom-color: #CCC;
  4272. }
  4273. p {
  4274. text-align: justify;
  4275. }
  4276. </style>
  4277. </head>
  4278. <body>';
  4279. $html.='<div class="item">
  4280. <b>Código del Equipamiento</b>
  4281. <span>'.$arrStock['CODIGO_EQUIPAMIENTO'].'</span>
  4282. </div>';
  4283. $html.='<div class="item">
  4284. <b>Familia</b>
  4285. <span>'.$arrStock['FAMILIA'].' ('.$arrStock['CODIGO_FAMILIA'].')'.'</span>
  4286. </div>';
  4287. $html.='<div class="item">
  4288. <b>Subfamilia</b>
  4289. <span>'.$arrStock['SUBFAMILIA'].' ('.$arrStock['CODIGO_SUBFAMILIA'].')'.'</span>
  4290. </div>';
  4291. $html.='<div class="item">
  4292. <b>Modelo</b>
  4293. <span>'.$arrStock['MODELO'].'</span>
  4294. </div>';
  4295. $html.='<div class="item">
  4296. <b>Código Modelo</b>
  4297. <span>'.$arrStock['CODIGO_MODELO'].'</span>
  4298. </div>';
  4299. $html.='<div class="item">
  4300. <b>Tipo de Adquisición</b>
  4301. <span>'.$arrStock['TIPO_ADQUISICION'].'</span>
  4302. </div>';
  4303. $html.='<div class="item">
  4304. <b>Proveedor</b>
  4305. <span>'.$arrStock['PROVEEDOR'].' ('.$arrStock['NUMERO_PROVEEDOR'].')'.'</span>
  4306. </div>';
  4307. $html.='<div class="item">
  4308. <b>Fecha de Vencimiento</b>
  4309. <span>'.$arrStock['FECHA_VENCIMIENTO'].'</span>
  4310. </div>';
  4311. $html.='<div class="item">
  4312. <b>Código de Barras</b>
  4313. <span>'.$arrStock['CODIGO_BARRAS'].'</span>
  4314. </div>';
  4315. if ( array_key_exists('TASA_ROTACION', $arrStock) ) {
  4316. $html.='<div class="item">
  4317. <b>Tasa de Rotación</b>
  4318. <span>'.$arrStock['TASA_ROTACION'].'</span>
  4319. </div>';
  4320. }
  4321. $html.='<div class="item">
  4322. <b>Stock Mínimo</b>
  4323. <span>'.is_null($arrStock['STOCK_MINIMO']) ? 'Sin Definir' : $arrStock['STOCK_MINIMO'].'</span>
  4324. </div>';
  4325. $html.='<div class="item">
  4326. <b>Stock Máximo</b>
  4327. <span>'.is_null($arrStock['STOCK_MAXIMO']) ? 'Sin Definir' : $arrStock['STOCK_MAXIMO'].'</span>
  4328. </div>';
  4329. $html.='<div class="item">
  4330. <b>¿Es consumible?</b>
  4331. <span>'.$arrStock['CONSUMIBLE'].'</span>
  4332. </div>';
  4333. $html.='<div class="item">
  4334. <b>¿Es reparable?</b>
  4335. <span>'.$arrStock['REPARABLE'].'</span>
  4336. </div>';
  4337. $html.='</body></html>';
  4338. $nuli = $this->resourcesController->formatSecuence($line, 2);
  4339. $como = 'GIST'; // Código del módulo
  4340. $cldo = 'IN'; // Código de la clasificación
  4341. $fecr = date('ymd'); // Fecha en la se carga el archivo
  4342. try {
  4343. $arrSecuence = (array) DB::table('S002V01TAFAL')
  4344. ->where('AFAL_COMO', '=', $como)
  4345. ->where('AFAL_CLDO', '=', $cldo)
  4346. ->where('AFAL_NULI', '=', $line)
  4347. ->orderBy('AFAL_NUSE', 'desc')
  4348. ->first([ 'AFAL_NUSE' ]);
  4349. } catch (\Throwable $th) {
  4350. return $this->responseController->makeResponse(
  4351. true,
  4352. "ERR_PROVIDER_SHEET020: Ocurrió un error al obtener la información de la secuencia.",
  4353. $th->getMessage(),
  4354. 500
  4355. );
  4356. }
  4357. $nuse = 1; // Secuencia del documento
  4358. if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
  4359. $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1;
  4360. }
  4361. $nuse = $this->resourcesController->formatSecuence($nuse, 6);
  4362. $nuve = $this->resourcesController->formatSecuence('1', 2);
  4363. $noar = 'ficha_de_adquisición_' . $arrStock['ID_STOCK'];
  4364. $nuli = $this->resourcesController->formatSecuence($line, 2);
  4365. $como = 'GIST'; // Código del módulo
  4366. $cldo = 'IN'; // Código de la clasificación
  4367. $fecr = date('ymd'); // Fecha en la se carga el archivo
  4368. try {
  4369. $arrSecuence = (array) DB::table('S002V01TAFAL')
  4370. ->where('AFAL_COMO', '=', $como)
  4371. ->where('AFAL_CLDO', '=', $cldo)
  4372. ->where('AFAL_NULI', '=', $line)
  4373. ->orderBy('AFAL_NUSE', 'desc')
  4374. ->first([ 'AFAL_NUSE' ]);
  4375. } catch (\Throwable $th) {
  4376. return $this->responseController->makeResponse(
  4377. true,
  4378. "ERR_PROVIDER_SHEET020: Ocurrió un error al obtener la información de la secuencia.",
  4379. $th->getMessage(),
  4380. 500
  4381. );
  4382. }
  4383. $nuse = 1; // Secuencia del documento
  4384. if ( !empty( $arrSecuence ) && !is_null( $arrSecuence ) ) {
  4385. $nuse = intval( $arrSecuence['AFAL_NUSE'] ) + 1;
  4386. }
  4387. $nuse = $this->resourcesController->formatSecuence($nuse, 6);
  4388. $nuve = $this->resourcesController->formatSecuence('1', 2);
  4389. $noar = 'ficha_de_stock_' . $arrStock['ID_STOCK'];
  4390. $exte = 'pdf';
  4391. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  4392. $filePath = $this->resourcesController->pathService.'\\public\\public_files\\'; // API JEAN
  4393. } else {
  4394. $filePath = $this->resourcesController->pathService.'\\public_files\\'; // API QA
  4395. }
  4396. $fileName = $nuli.'-'.$como.'-'.$cldo.'-'.$fecr.'-'.$nuse.'='.$nuve.'='.$noar.'.'.$exte;
  4397. $tempFile = $filePath . $fileName;
  4398. $dompdf = new Dompdf();
  4399. $dompdf ->loadHtml($html);
  4400. $dompdf->setPaper('A4', 'landscape');
  4401. $dompdf->render();
  4402. $output = $dompdf->output();
  4403. file_put_contents($tempFile, $output);
  4404. $ubic = Storage::putFile('files', new File($tempFile));
  4405. $ubic = str_replace("/", "\\", $ubic);
  4406. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  4407. $ubic = $this->resourcesController->pathService."\\storage\\app\\" . $ubic;
  4408. } else {
  4409. $ubic = $this->resourcesController->pathService."\\storage\\app\\" . $ubic;
  4410. }
  4411. $tama = filesize($ubic);
  4412. $usac = json_encode([$user]);
  4413. $now = $this->functionsController->now();
  4414. $currentDate = $now->toDateTimeString();
  4415. try {
  4416. $validateInsert = DB::table('S002V01TAFAL')->insert([
  4417. 'AFAL_NULI' => $line,
  4418. 'AFAL_COMO' => $como,
  4419. 'AFAL_CLDO' => $cldo,
  4420. 'AFAL_FECR' => $fecr,
  4421. 'AFAL_NUSE' => $nuse,
  4422. 'AFAL_NUVE' => $nuve,
  4423. 'AFAL_NOAR' => $noar,
  4424. 'AFAL_EXTE' => $exte,
  4425. 'AFAL_TAMA' => $tama,
  4426. 'AFAL_UBIC' => $ubic,
  4427. 'AFAL_USAC' => $usac,
  4428. 'AFAL_USRE' => $user,
  4429. 'AFAL_FERE' => $currentDate,
  4430. ]);
  4431. } catch (\Throwable $th) {
  4432. return $this->responseController->makeResponse(
  4433. true,
  4434. "ERR_PROVIDER_SHEET023: Ocurrió un error guardar los datos a la tabla final de archivos.",
  4435. $th->getMessage(),
  4436. 500
  4437. );
  4438. }
  4439. if ( !$validateInsert ) {
  4440. return $this->responseController->makeResponse(
  4441. true,
  4442. "ERR_PROVIDER_SHEET024: No se pudo guardar la ficha del proveedor en la base de datos.",
  4443. [],
  4444. 500
  4445. );
  4446. }
  4447. $encCode = $this->encController->encrypt($fileName);
  4448. try {
  4449. $validateInsert = DB::table('S002V01TDOST')->insert([
  4450. 'DOST_NULI' => $line,
  4451. 'DOST_IDST' => $idStock,
  4452. 'DOST_NODO' => 'Ficha de Stock #'.$arrStock['ID_STOCK'],
  4453. 'DOST_CODO' => $encCode,
  4454. 'DOST_EXTE' => $exte,
  4455. 'DOST_TAMA' => $tama,
  4456. 'DOST_CLAS' => 'IN',
  4457. 'DOST_VERS' => 1,
  4458. 'DOST_USRE' => $user,
  4459. 'DOST_FERE' => $currentDate,
  4460. 'DOST_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  4461. ]);
  4462. } catch (\Throwable $th) {
  4463. return $this->responseController->makeResponse(
  4464. true,
  4465. "Ocurrió un error guardar los datos a la tabla final de archivos.",
  4466. $th->getMessage(),
  4467. 500
  4468. );
  4469. }
  4470. if (!$validateInsert) {
  4471. return $this->responseController->makeResponse(
  4472. true,
  4473. "No se pudo guardar la ficha del proveedor en la base de datos.",
  4474. [],
  4475. 500
  4476. );
  4477. }
  4478. if ($_SERVER['SERVER_NAME'] === '192.168.100.105') {
  4479. $urlPublic = 'http://192.168.100.105:8000/public_files/' . $fileName;
  4480. } else {
  4481. $urlPublic = $this->functionsController->getApiURI().'sam/public_files/' . $fileName;
  4482. }
  4483. return $this->responseController->makeResponse(false, "EXITO: Modificación Exitosa", [ 'url' => $urlPublic ]);
  4484. }
  4485. public function getDocumentAssociation($user, $line) {
  4486. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  4487. if ($arrResponseCheckUser['error']) {
  4488. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4489. }
  4490. try {
  4491. $arrStock = DB::table('S002V01TSTAR')
  4492. ->where('STAR_NULI', '=', $line)
  4493. ->where('STAR_ESTA', '=', 'Activo')
  4494. ->where('INST_NULI', '=', $line)
  4495. ->where('INST_ESTA', '=', 'Activo')
  4496. ->where('UBAR_NULI', '=', $line)
  4497. ->where('UBAR_ESTA', '=', 'Activo')
  4498. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  4499. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  4500. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  4501. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  4502. ->get([
  4503. 'STAR_IDST AS ID_STOCK',
  4504. 'INST_MODE AS MODELO',
  4505. 'INST_COMO AS CODIGO_MODELO',
  4506. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  4507. 'FAMI_NOFA AS FAMILIA',
  4508. 'SUBF_NOSU AS SUBFAMILIA',
  4509. 'INST_IMAG AS IMAGENES',
  4510. 'STAR_NUPR AS NUMERO_PROVEEDOR',
  4511. 'STAR_TIAD AS TIPO_ADQUISICION',
  4512. ]);
  4513. $arrStock = json_decode(json_encode($arrStock), true);
  4514. } catch (\Throwable $th) {
  4515. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  4516. }
  4517. foreach ($arrStock as $key => $stock) {
  4518. $arrImages = json_decode($stock['IMAGENES']);
  4519. $arrUrlImage = array();
  4520. foreach ($arrImages as $keyImages => $images) {
  4521. $images = $this->encController->encrypt($images);
  4522. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  4523. if ($responseDocument['error']) {
  4524. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  4525. }
  4526. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  4527. }
  4528. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  4529. try {
  4530. $count = DB::table('S002V01TDOST')
  4531. ->where('DOST_IDST', '=', $stock['ID_STOCK'])
  4532. ->where('DOST_NULI', '=', $line)
  4533. ->where('DOST_ESTA', '=', 'Activo')
  4534. ->count();
  4535. } catch (\Throwable $th) {
  4536. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la cantidad de documentos.', $th->getMessage(), 500);
  4537. }
  4538. $arrStock[$key]['CANTIDAD_DOCUMENTOS'] = $count;
  4539. }
  4540. return $this->responseController->makeResponse(false, "ÉXITO: Consulta ExitosaA", $arrStock);
  4541. }
  4542. public function getDocumentsByStock($idStock, $user, $line) {
  4543. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  4544. if ($arrResponseCheckUser['error']) {
  4545. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4546. }
  4547. $idStock = $this->encController->decrypt($idStock);
  4548. if (is_null($idStock)) {
  4549. DB::rollBack();
  4550. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  4551. }
  4552. try {
  4553. $stock = (array) DB::table('S002V01TUBAR')
  4554. ->where([
  4555. ['UBAR_IDST', '=', $idStock],
  4556. ['UBAR_ESTA', '=', 'Activo'],
  4557. ['UBAR_NULI', '=', $line],
  4558. ])
  4559. ->first([
  4560. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  4561. ]);
  4562. } catch (\Throwable $th) {
  4563. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el código del equipamento del stock.', $th->getMessage(), 401);
  4564. }
  4565. if (is_null($stock)) {
  4566. return $this->responseController->makeResponse(true, 'No se pudo obtener el código del equipamento del stock.', [], 401);
  4567. }
  4568. try {
  4569. $equip = (array) DB::table('S002V01TEQUI')
  4570. ->where([
  4571. ['EQUI_COEQ', '=', $stock['CODIGO_EQUIPAMIENTO']],
  4572. ['EQUI_NULI', '=', $line],
  4573. ])
  4574. ->first([
  4575. 'EQUI_DORE AS DOCUMENTOS',
  4576. ]);
  4577. } catch (\Throwable $th) {
  4578. return $this->responseController->makeResponse(true, 'Ocurrió un error obtener el códigos del documento del equipamiento.', $th->getMessage(), 401);
  4579. }
  4580. if (is_null($equip)) {
  4581. return $this->responseController->makeResponse(true, 'No se pudo obtener el códigos del documento del equipamiento.', [], 401);
  4582. }
  4583. $arrDocuments = json_decode($equip['DOCUMENTOS'], true);
  4584. $documentsFn = [];
  4585. foreach($arrDocuments as $document){
  4586. $codeArr = explode('=',$document);
  4587. $codeArr0 = explode('-', $codeArr[0]);
  4588. $file = DB::table('S002V01TAFAL')->where([
  4589. ['AFAL_NULI', '=', $line],
  4590. ['AFAL_COMO', '=', $codeArr0[1]],
  4591. ['AFAL_CLDO', '=', $codeArr0[2]],
  4592. ['AFAL_FECR', '=', $codeArr0[3]],
  4593. ['AFAL_NUSE', '=', $codeArr0[4]],
  4594. ['AFAL_NUVE', '=', $codeArr[1]],
  4595. ])->first();
  4596. if(is_null($file)){
  4597. return $this->responseController->makeResponse(true, "El archivo $document no está registrado.", [], 404);
  4598. }
  4599. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($this->encController->encrypt($document), $user, $line);
  4600. if ($responseDocument['error']) {
  4601. return $this->responseController->makeResponse(true, $responseDocument['msg'], $responseDocument['response'], 500);
  4602. }
  4603. $url = $responseDocument['response']['public_uri'];
  4604. $documentsFn[] = [
  4605. 'ID' => $this->encController->encrypt($document),
  4606. 'URL' => $url,
  4607. 'DOCUMENTO' => $file->AFAL_NOAR,
  4608. 'CLASIFICACION' => $this->resourcesController->arrClasificateDocument[$file->AFAL_CLDO],
  4609. 'EXTENSION' => $file->AFAL_EXTE,
  4610. 'VERSION' => $file->AFAL_NUVE,
  4611. 'TAMANO' => $this->resourcesController->formatBytes($file->AFAL_TAMA),
  4612. 'ESTADO' => $file->AFAL_ESTA,
  4613. 'USUARIO_REGISTRA' => $file->AFAL_USRE,
  4614. 'FECHA_REGISTRA' => $file->AFAL_FERE,
  4615. 'USUARIO_MODIFICA' => $file->AFAL_USMO,
  4616. 'FECHA_MODIFICA' => $file->AFAL_FEMO,
  4617. ];
  4618. }
  4619. $stockDocuments = DB::table('S002V01TDOST')->select([
  4620. 'DOST_CODO AS CODIGO_DOCUMENTO'
  4621. ])->where([
  4622. ['DOST_IDST', '=', $idStock],
  4623. ['DOST_NULI', '=', $line],
  4624. ])->get()->all();
  4625. foreach($stockDocuments as $stockDocument){
  4626. $codeDec = $this->encController->decrypt($stockDocument->CODIGO_DOCUMENTO);
  4627. $codeArr0 = explode('.', $codeDec);
  4628. if(count($codeArr0) == 2){
  4629. $exte = $codeArr0[1];
  4630. $codeArr1 = explode('=', $codeArr0[0]);
  4631. if(count($codeArr1) == '3'){
  4632. $noar = $codeArr1[2];
  4633. $nuve = $codeArr1[1];
  4634. $codeArr2 = explode('-', $codeArr1[0]);
  4635. if(count($codeArr2) == 5){
  4636. $como = $codeArr2[1];
  4637. $cldo = $codeArr2[2];
  4638. $fecr = $codeArr2[3];
  4639. $nuse = $codeArr2[4];
  4640. $documentBD = DB::table('S002V01TAFAL')->where([
  4641. ['AFAL_NULI', '=', $line],
  4642. ['AFAL_COMO', '=', $como],
  4643. ['AFAL_CLDO', '=', $cldo],
  4644. ['AFAL_FECR', '=', $fecr],
  4645. ['AFAL_NUSE', '=', $nuse],
  4646. ['AFAL_NUVE', '=', $nuve],
  4647. ['AFAL_NOAR', '=', $noar],
  4648. ['AFAL_EXTE', '=', $exte],
  4649. ])->first();
  4650. if(!is_null($documentBD)){
  4651. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($this->encController->encrypt($document), $user, $line);
  4652. if ($responseDocument['error']) {
  4653. return $this->responseController->makeResponse(true, $responseDocument['msg'], $responseDocument['response'], 500);
  4654. }
  4655. $url = $responseDocument['response']['public_uri'];
  4656. $documentsFn[] = [
  4657. 'ID' => $this->encController->encrypt($stockDocument->CODIGO_DOCUMENTO),
  4658. 'URL' => $url,
  4659. 'DOCUMENTO' => $documentBD->AFAL_NOAR,
  4660. 'CLASIFICACION' => $this->resourcesController->arrClasificateDocument[$documentBD->AFAL_CLDO],
  4661. 'EXTENSION' => $documentBD->AFAL_EXTE,
  4662. 'VERSION' => $documentBD->AFAL_NUVE,
  4663. 'TAMANO' => $this->resourcesController->formatBytes($documentBD->AFAL_TAMA),
  4664. 'ESTADO' => $documentBD->AFAL_ESTA,
  4665. 'USUARIO_REGISTRA' => $documentBD->AFAL_USRE,
  4666. 'FECHA_REGISTRA' => $documentBD->AFAL_FERE,
  4667. 'USUARIO_MODIFICA' => $documentBD->AFAL_USMO,
  4668. 'FECHA_MODIFICA' => $documentBD->AFAL_FEMO,
  4669. ];
  4670. }
  4671. }
  4672. }
  4673. }
  4674. }
  4675. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($documentsFn, $line);
  4676. if ($responseCheckLatestUpdate['error']) {
  4677. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  4678. }
  4679. $documentsFn = $responseCheckLatestUpdate['response'];
  4680. return $this->responseController->makeResponse(false, "EXITO: Consulta Exitosa", $documentsFn);
  4681. }
  4682. public function registerDocumentStock(Request $request) {
  4683. $valitador = Validator::make($request->all(), [
  4684. 'ID_STOCK' => 'required|string',
  4685. 'NOMBRE_ARCHIVO' => 'required|string',
  4686. 'TIPO_ARCHIVO' => 'required|string',
  4687. 'ARCHIVO' => 'required|string',
  4688. 'USUARIO' => 'required|string',
  4689. 'NUMERO_LINEA' => 'required|integer',
  4690. ]);
  4691. if ($valitador->fails()) {
  4692. return $this->responseController->makeResponse(
  4693. true,
  4694. "ERR_DOCUMENT_ORDER_REG000: Se encontraron uno o más errores.",
  4695. $this->responseController->makeErrors($valitador->errors()->messages()),
  4696. 401
  4697. );
  4698. }
  4699. DB::beginTransaction();
  4700. $requestData = $request->all();
  4701. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  4702. if ($arrResponseCheckUser['error']) {
  4703. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4704. }
  4705. $user = $arrResponseCheckUser['response'];
  4706. try {
  4707. $idFile = $this->encController->decrypt($requestData['ARCHIVO']);
  4708. } catch (\Throwable $th) {
  4709. DB::rollBack();
  4710. return $this->responseController->makeResponse(true, "ERR_DOCUMENT_ORDER_REG002: Ocurrió un error al desencriptar el documento.", $th->getMessage(), 401);
  4711. }
  4712. $tempFile = DB::table('S002V01TARTE')->where([
  4713. ['ARTE_NULI', '=', $requestData['NUMERO_LINEA']],
  4714. ['ARTE_IDAR', '=', $idFile],
  4715. ])->first();
  4716. if(is_null($tempFile)){
  4717. return $this->responseController->makeResponse(true, 'ERR_DOCUMENT_ORDER_REG003: El archivo consultado no está registrado', [], 404);
  4718. }else if($tempFile->ARTE_ESTA == 'Eliminado'){
  4719. return $this->responseController->makeResponse(true, 'ERR_DOCUMENT_ORDER_REG004: El archivo consultado está eliminado', [], 404);
  4720. }
  4721. $fileResponse = $this->documentManagementController->moveFinalFile(
  4722. intval($requestData['NUMERO_LINEA']),
  4723. 'GEAD',
  4724. $requestData['TIPO_ARCHIVO'],
  4725. $tempFile,
  4726. $user,
  4727. );
  4728. if(!$fileResponse[0]){
  4729. return $this->responseController->makeResponse(true, 'ERR_DOCUMENT_ORDER_REG005: '.$fileResponse[1], [], 400);
  4730. }
  4731. $encCode = $this->encController->encrypt($fileResponse[1]);
  4732. $now = $this->functionsController->now();
  4733. $currentDate = $now->toDateTimeString();
  4734. var_dump($encCode);
  4735. try {
  4736. $validateInsert = DB::table('S002V01TDOST')->insert([
  4737. 'DOST_NULI' => $requestData['NUMERO_LINEA'],
  4738. 'DOST_IDST' => $requestData['ID_STOCK'],
  4739. 'DOST_NODO' => $requestData['NOMBRE_ARCHIVO'],
  4740. 'DOST_CODO' => $encCode,
  4741. 'DOST_EXTE' => $tempFile->ARTE_EXTE,
  4742. 'DOST_TAMA' => $tempFile->ARTE_TAMA,
  4743. 'DOST_CLAS' => $requestData['TIPO_ARCHIVO'],
  4744. 'DOST_VERS' => 1,
  4745. 'DOST_USRE' => $user,
  4746. 'DOST_FERE' => $currentDate,
  4747. 'DOST_FEAR' => DB::raw('CURRENT_TIMESTAMP')
  4748. ]);
  4749. } catch (\Throwable $th) {
  4750. return $this->responseController->makeResponse(
  4751. true,
  4752. "Ocurrió un error guardar los datos a la tabla final de archivos.",
  4753. $th->getMessage(),
  4754. 500
  4755. );
  4756. }
  4757. if (!$validateInsert) {
  4758. return $this->responseController->makeResponse(
  4759. true,
  4760. "No se pudo guardar la ficha del proveedor en la base de datos.",
  4761. [],
  4762. 500
  4763. );
  4764. }
  4765. DB::commit();
  4766. return $this->responseController->makeResponse(false, "ÉXITO: Registro de Documento Exitoso");
  4767. }
  4768. public function getReplenishmentQuantitiesService($user, $line) {
  4769. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  4770. if ($arrResponseCheckUser['error']) {
  4771. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4772. }
  4773. try {
  4774. $arrStock = DB::table('S002V01TSTAR')
  4775. ->where('STAR_TIAD', '=', 'Por Pedido')
  4776. ->where('STAR_NULI', '=', $line)
  4777. ->where('STAR_ESTA', '=', 'Activo')
  4778. ->where('INST_NULI', '=', $line)
  4779. ->where('INST_ESTA', '=', 'Activo')
  4780. ->where('UBAR_NULI', '=', $line)
  4781. ->where('UBAR_ESTA', '=', 'Activo')
  4782. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  4783. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  4784. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  4785. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  4786. ->join('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  4787. ->get([
  4788. 'STAR_IDST AS ID_STOCK',
  4789. 'INST_MODE AS MODELO',
  4790. 'INST_COMO AS CODIGO_MODELO',
  4791. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  4792. 'FAMI_NOFA AS FAMILIA',
  4793. 'SUBF_NOSU AS SUBFAMILIA',
  4794. 'INST_IMAG AS IMAGENES',
  4795. 'PROV_NUPR AS NUMERO_PROVEEDOR',
  4796. 'PROV_NOCO AS NOMBRE_PROVEEDOR',
  4797. ]);
  4798. $arrStock = json_decode(json_encode($arrStock), true);
  4799. } catch (\Throwable $th) {
  4800. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  4801. }
  4802. foreach ($arrStock as $key => $info) {
  4803. $arrImages = json_decode($info['IMAGENES']);
  4804. $arrUrlImage = array();
  4805. foreach ($arrImages as $keyImages => $images) {
  4806. $images = $this->encController->encrypt($images);
  4807. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  4808. if ($responseDocument['error']) {
  4809. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  4810. }
  4811. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  4812. }
  4813. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  4814. $arrStock[$key]['CANTIDAD'] = 0;
  4815. }
  4816. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStock);
  4817. }
  4818. public function createRequestLine(Request $request) {
  4819. $valitador = Validator::make($request->all(), [
  4820. 'REQUEST_LINE' => 'required|array',
  4821. 'USUARIO' => 'required|string',
  4822. 'NUMERO_LINEA' => 'required|integer',
  4823. ]);
  4824. if ($valitador->fails()) {
  4825. return $this->responseController->makeResponse(
  4826. true,
  4827. "ERR_DOCUMENT_ORDER_REG000: Se encontraron uno o más errores.",
  4828. $this->responseController->makeErrors($valitador->errors()->messages()),
  4829. 401
  4830. );
  4831. }
  4832. DB::beginTransaction();
  4833. $requestData = $request->all();
  4834. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  4835. if ($arrResponseCheckUser['error']) {
  4836. DB::rollBack();
  4837. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4838. }
  4839. $user = $arrResponseCheckUser['response'];
  4840. $now = $this->functionsController->now();
  4841. $currentDate = $now->toDateTimeString();
  4842. $arrProviders = array();
  4843. $arrRequestData = array();
  4844. foreach ($requestData['REQUEST_LINE'] as $keyRequest => $request) {
  4845. try {
  4846. $validateInsert = DB::table('S002V01TCARE')->insert([
  4847. 'CARE_NULI' => $requestData['NUMERO_LINEA'],
  4848. 'CARE_IDST' => $request['ID_STOCK'],
  4849. 'CARE_CAAD' => $request['CANTIDAD'],
  4850. 'CARE_USRE' => $user,
  4851. 'CARE_FERE' => $currentDate,
  4852. 'CARE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  4853. ]);
  4854. } catch (\Throwable $th) {
  4855. DB::rollBack();
  4856. return $this->responseController->makeResponse(true, 'Ocurrió un error al guar la información del reabastecimiento del stock.', $th->getMessage(), 500);
  4857. }
  4858. if (!$validateInsert) {
  4859. DB::rollBack();
  4860. return $this->responseController->makeResponse(true, 'No se pudo guardar los datos del reabastecimiento dentro de la base de datos.', [], 500);
  4861. }
  4862. try {
  4863. $arrStock = (array) DB::table('S002V01TSTAR')
  4864. ->where('STAR_IDST', '=', $request['ID_STOCK'])
  4865. ->where('STAR_TIAD', '=', 'Por Pedido')
  4866. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  4867. ->where('STAR_ESTA', '=', 'Activo')
  4868. ->where('INST_NULI', '=', $requestData['NUMERO_LINEA'])
  4869. ->where('INST_ESTA', '=', 'Activo')
  4870. ->where('UBAR_NULI', '=', $requestData['NUMERO_LINEA'])
  4871. ->where('UBAR_ESTA', '=', 'Activo')
  4872. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  4873. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  4874. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  4875. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  4876. ->join('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  4877. ->first([
  4878. 'INST_MODE AS MODELO',
  4879. 'INST_COMO AS CODIGO_MODELO',
  4880. 'FAMI_COFA AS FAMILIA',
  4881. 'SUBF_COSU AS SUBFAMILIA',
  4882. 'PROV_NUPR AS NUMERO_PROVEEDOR',
  4883. ]);
  4884. } catch (\Throwable $th) {
  4885. DB::rollBack();
  4886. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  4887. }
  4888. if (empty($arrStock)) {
  4889. DB::rollBack();
  4890. return $this->responseController->makeResponse(true, 'No se encontró la información del Stock', [], 500);
  4891. }
  4892. if ( !in_array($arrStock['NUMERO_PROVEEDOR'], $arrProviders) ) {
  4893. $arrProviders[] = $arrStock['NUMERO_PROVEEDOR'];
  4894. }
  4895. $request['MODELO'] = $arrStock['MODELO'];
  4896. $request['CODIGO_MODELO'] = $arrStock['CODIGO_MODELO'];
  4897. $request['FAMILIA'] = $arrStock['FAMILIA'];
  4898. $request['SUBFAMILIA'] = $arrStock['SUBFAMILIA'];
  4899. $request['NUMERO_PROVEEDOR'] = $arrStock['NUMERO_PROVEEDOR'];
  4900. try {
  4901. $infoAdquisition = (array) DB::table('S002V01TINAR')
  4902. ->where('INAR_NULI', '=', $requestData['NUMERO_LINEA'])
  4903. ->where('INAR_CODI', '=', $arrStock['CODIGO_MODELO'])
  4904. ->where('INAR_MODE', '=', $arrStock['MODELO'])
  4905. ->where('INAR_ESTA', '=', 'Activo')
  4906. ->where('DEAR_NULI', '=', $requestData['NUMERO_LINEA'])
  4907. ->where('DEAR_NUPR', '=', $arrStock['NUMERO_PROVEEDOR'])
  4908. ->where('DEAR_ESTA', '=', 'Activo')
  4909. ->where('ARTI_NULI', '=', $requestData['NUMERO_LINEA'])
  4910. ->where('ARTI_COFA', '=', $arrStock['FAMILIA'])
  4911. ->where('ARTI_COSU', '=', $arrStock['SUBFAMILIA'])
  4912. ->where('ARTI_ESTA', '=', 'Activo')
  4913. ->join('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
  4914. ->join('S002V01TARTI', 'ARTI_IDAR', '=', 'DEAR_IDAR')
  4915. ->first([
  4916. 'ARTI_IDAR AS ID_ARTICULO',
  4917. 'INAR_IDIN AS ID_INFORMACION',
  4918. ]);
  4919. } catch (\Throwable $th) {
  4920. DB::rollBack();
  4921. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de la adquisición.', $th->getMessage(), 500);
  4922. }
  4923. if (empty($infoAdquisition)) {
  4924. DB::rollBack();
  4925. return $this->responseController->makeResponse(true, 'No se encontró la información de la adquisición.', [], 500);
  4926. }
  4927. $request['ID_ARTICULO'] = $infoAdquisition['ID_ARTICULO'];
  4928. $request['ID_INFORMACION'] = $infoAdquisition['ID_INFORMACION'];
  4929. $arrRequestData[$keyRequest] = $request;
  4930. }
  4931. foreach ($arrProviders as $provider) {
  4932. $contItemRequest = 1;
  4933. foreach ($arrRequestData as $key => $value) {
  4934. if ($provider === $value['NUMERO_PROVEEDOR']) {
  4935. try {
  4936. $idRequest = DB::table('S002V01TLINE')->insertGetId([
  4937. 'LINE_NULI' => $requestData['NUMERO_LINEA'],
  4938. 'LINE_NUPR' => $value['NUMERO_PROVEEDOR'],
  4939. 'LINE_ESTA' => 'En espera',
  4940. 'LINE_USRE' => $user,
  4941. 'LINE_FERE' => $currentDate,
  4942. 'LINE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  4943. ]);
  4944. } catch (\Throwable $th) {
  4945. DB::rollBack();
  4946. return $this->responseController->makeResponse(true, 'Ocurrió un error al insertar la información en la línea de solicitud.', $th->getMessage(), 500);
  4947. }
  4948. if ($idRequest <= 0) {
  4949. DB::rollBack();
  4950. return $this->responseController->makeResponse(true, 'No se pudo insertar la información de la línea de solicitud.', [], 500);
  4951. }
  4952. for ($i=0; $i < $value['CANTIDAD']; $i++) {
  4953. try {
  4954. $validateInsert = DB::table('S002V01TARSE')->insert([
  4955. 'ARSE_IDAS' => $contItemRequest,
  4956. 'ARSE_IDLI' => $idRequest,
  4957. 'ARSE_ESTA' => 'Activo',
  4958. 'ARSE_NULI' => $requestData['NUMERO_LINEA'],
  4959. 'ARSE_IDAR' => $value['ID_ARTICULO'],
  4960. 'ARSE_NUPR' => $value['NUMERO_PROVEEDOR'],
  4961. 'ARSE_IDIN' => $value['ID_INFORMACION'],
  4962. 'ARSE_USRE' => $user,
  4963. 'ARSE_FERE' => $currentDate,
  4964. 'ARSE_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  4965. ]);
  4966. } catch (\Throwable $th) {
  4967. DB::rollBack();
  4968. return $this->responseController->makeResponse(true, 'Ocurrió un error al insertar los artículos en la línea de solicitud.', $th->getMessage(), 500);
  4969. }
  4970. if (!$validateInsert) {
  4971. DB::rollBack();
  4972. return $this->responseController->makeResponse(true, 'No se pudo insertar los artículos en la línea de solicitud.', [], 500);
  4973. }
  4974. $contItemRequest++;
  4975. }
  4976. }
  4977. }
  4978. }
  4979. DB::commit();
  4980. return $this->responseController->makeResponse(false, "ÉXITO: Registro Exitoso");
  4981. }
  4982. public function getReplenishmentSuggestion($user, $line) {
  4983. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  4984. if ($arrResponseCheckUser['error']) {
  4985. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  4986. }
  4987. try {
  4988. $arrInfoStock = DB::table('S002V01TINST')
  4989. ->where('INST_NULI', '=', $line)
  4990. ->where('INST_ESTA', '=', 'Activo')
  4991. ->leftJoin('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  4992. ->leftJoin('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  4993. ->leftJoin('S002V01TSTAR', 'STAR_IDIS', '=', 'INST_IDIS')
  4994. ->get([
  4995. 'INST_IDIS AS ID_INFORMACION_STOCK',
  4996. 'STAR_IDST AS ID_STOCK',
  4997. DB::raw('CONCAT(FAMI_NOFA, " (", FAMI_COFA, ")") AS FAMILIA'),
  4998. DB::raw('CONCAT(SUBF_NOSU, " (", SUBF_COSU, ")") AS SUBFAMILIA'),
  4999. 'INST_MODE AS MODELO',
  5000. 'INST_COMO AS CODIGO_MODELO',
  5001. 'STAR_NUPR AS NUMERO_PROVEEDOR',
  5002. 'INST_STMI AS STOCK_MINIMO',
  5003. 'INST_STMA AS STOCK_MAXIMO',
  5004. 'INST_IMAG AS IMAGENES',
  5005. ]);
  5006. $arrInfoStock = json_decode(json_encode($arrInfoStock), true);
  5007. } catch (\Throwable $th) {
  5008. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  5009. }
  5010. $arrDataStock = array();
  5011. foreach ($arrInfoStock as $key => $info) {
  5012. $arrImages = json_decode($info['IMAGENES']);
  5013. $arrUrlImage = array();
  5014. foreach ($arrImages as $images) {
  5015. $images = $this->encController->encrypt($images);
  5016. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  5017. if ($responseDocument['error']) {
  5018. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  5019. }
  5020. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  5021. }
  5022. $arrInfoStock[$key]['IMAGENES'] = $arrUrlImage;
  5023. try {
  5024. $countStock = DB::table('S002V01TSTAR')
  5025. ->where('STAR_NULI', '=', $line)
  5026. ->where('STAR_IDIS', '=', $info['ID_INFORMACION_STOCK'])
  5027. ->where('STAR_ESTA', '=', 'Activo')
  5028. ->count();
  5029. } catch (\Throwable $th) {
  5030. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el stock.', $th->getMessage(), 500);
  5031. }
  5032. $arrInfoStock[$key]['CANTIDAD_ACTUAL'] = $countStock;
  5033. if ($countStock < $info['STOCK_MINIMO'] && !is_null($info['STOCK_MINIMO'])) {
  5034. $arrInfoStock[$key]['ESTADO'] = 'Menor al Stock Requerido';
  5035. $arrInfoStock[$key]['CANTIDAD_SUGERIDA'] = $info['STOCK_MINIMO'] - $countStock;
  5036. $arrDataStock[] = $arrInfoStock[$key];
  5037. }
  5038. }
  5039. try {
  5040. $arrReplanishment = DB::table('S002V01TCARE')
  5041. ->where('CARE_NULI', '=', $line)
  5042. ->where('CARE_ESTA', '=', 'Activo')
  5043. ->leftJoin('S002V01TSTAR', 'STAR_IDST', '=', 'CARE_IDST')
  5044. ->leftJoin('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  5045. ->leftJoin('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  5046. ->leftJoin('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  5047. ->orderBy('CARE_CAAD', 'DESC')
  5048. ->limit(5)
  5049. ->get([
  5050. 'INST_IDIS AS ID_INFORMACION_STOCK',
  5051. 'STAR_IDST AS ID_STOCK',
  5052. DB::raw('CONCAT(FAMI_NOFA, " (", FAMI_COFA, ")") AS FAMILIA'),
  5053. DB::raw('CONCAT(SUBF_NOSU, " (", SUBF_COSU, ")") AS SUBFAMILIA'),
  5054. 'INST_MODE AS MODELO',
  5055. 'INST_COMO AS CODIGO_MODELO',
  5056. 'STAR_NUPR AS NUMERO_PROVEEDOR',
  5057. 'INST_STMI AS STOCK_MINIMO',
  5058. 'INST_STMA AS STOCK_MAXIMO',
  5059. 'INST_IMAG AS IMAGENES',
  5060. 'CARE_CAAD AS CANTIDAD_SUGERIDA',
  5061. ]);
  5062. $arrReplanishment = json_decode(json_encode($arrReplanishment), true);
  5063. } catch (\Throwable $th) {
  5064. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el reabastecimiento.', $th->getMessage(), 500);
  5065. }
  5066. foreach ($arrReplanishment as $key => $replanishment) {
  5067. $arrImages = json_decode($replanishment['IMAGENES']);
  5068. $arrUrlImage = array();
  5069. foreach ($arrImages as $images) {
  5070. $images = $this->encController->encrypt($images);
  5071. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  5072. if ($responseDocument['error']) {
  5073. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  5074. }
  5075. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  5076. }
  5077. $arrReplanishment[$key]['IMAGENES'] = $arrUrlImage;
  5078. $arrReplanishment[$key]['ESTADO'] = 'Stock habitualmente pedido';
  5079. }
  5080. // Se verifica los campos repetidos
  5081. $arrIdDataStock = array_column($arrDataStock, 'ID_INFORMACION_STOCK');
  5082. $arrIdReplanishment = array_column($arrReplanishment, 'ID_INFORMACION_STOCK');
  5083. $arrRepeated = array_merge($arrIdDataStock, $arrIdReplanishment);
  5084. $arrUnique = array_unique($arrRepeated);
  5085. $arrValues = array_values($arrUnique);
  5086. // Se unen con los estados para el resultado final
  5087. $arrFinal = array();
  5088. foreach ($arrValues as $key => $value) {
  5089. foreach ($arrDataStock as $dataStock) {
  5090. if ($dataStock['ID_INFORMACION_STOCK'] === $value) {
  5091. $arrFinal[$key] = $dataStock;
  5092. }
  5093. }
  5094. foreach ($arrReplanishment as $replanishment) {
  5095. if ($replanishment['ID_INFORMACION_STOCK'] === $value) {
  5096. if (array_key_exists($key, $arrFinal)) {
  5097. $arrFinal[$key]['ESTADO'] .= ' | '.$replanishment['ESTADO'];
  5098. } else {
  5099. $arrFinal[$key] = $replanishment;
  5100. }
  5101. }
  5102. }
  5103. }
  5104. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrFinal);
  5105. }
  5106. public function getNomenclatureManagement($user, $line) {
  5107. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5108. if ($arrResponseCheckUser['error']) {
  5109. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5110. }
  5111. try {
  5112. $arrStock = DB::table('S002V01TSTAR')
  5113. ->where('STAR_TIAD', '=', 'Por Pedido')
  5114. ->where('STAR_NULI', '=', $line)
  5115. ->where('STAR_ESTA', '=', 'Activo')
  5116. ->where('INST_NULI', '=', $line)
  5117. ->where('INST_ESTA', '=', 'Activo')
  5118. ->where('UBAR_NULI', '=', $line)
  5119. ->where('UBAR_ESTA', '=', 'Activo')
  5120. ->leftJoin('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  5121. ->leftJoin('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  5122. ->leftJoin('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  5123. ->leftJoin('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  5124. ->leftJoin('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  5125. ->get([
  5126. 'STAR_IDST AS ID_STOCK',
  5127. 'INST_MODE AS MODELO',
  5128. 'INST_COMO AS CODIGO_MODELO',
  5129. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  5130. 'FAMI_NOFA AS FAMILIA',
  5131. 'SUBF_NOSU AS SUBFAMILIA',
  5132. 'INST_IMAG AS IMAGENES',
  5133. ]);
  5134. $arrStock = json_decode(json_encode($arrStock), true);
  5135. } catch (\Throwable $th) {
  5136. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  5137. }
  5138. foreach ($arrStock as $key => $info) {
  5139. $arrImages = json_decode($info['IMAGENES']);
  5140. $arrUrlImage = array();
  5141. foreach ($arrImages as $keyImages => $images) {
  5142. $images = $this->encController->encrypt($images);
  5143. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  5144. if ($responseDocument['error']) {
  5145. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  5146. }
  5147. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  5148. }
  5149. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  5150. }
  5151. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStock);
  5152. }
  5153. public function getDetailsNomenclature($idStock, $user, $line) {
  5154. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5155. if ($arrResponseCheckUser['error']) {
  5156. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5157. }
  5158. $idStock = $this->encController->decrypt($idStock);
  5159. if (is_null($idStock)) {
  5160. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  5161. }
  5162. try {
  5163. $validateExists = DB::table('S002V01TSTAR')
  5164. ->where('STAR_IDST', '=', $idStock)
  5165. ->where('STAR_NULI', '=', $line)
  5166. ->where('STAR_ESTA', '=', 'Activo')
  5167. ->exists();
  5168. } catch (\Throwable $th) {
  5169. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el ID del stock.', $th->getMessage(), 500);
  5170. }
  5171. if (!$validateExists) {
  5172. return $this->responseController->makeResponse(true, 'El número de stock no existe.', [], 500);
  5173. }
  5174. try {
  5175. $info = (array) DB::table('S002V01TSTAR')
  5176. ->where('STAR_IDST', '=', $idStock)
  5177. ->where('STAR_TIAD', '=', 'Por Pedido')
  5178. ->where('STAR_NULI', '=', $line)
  5179. ->where('STAR_ESTA', '=', 'Activo')
  5180. ->where('INST_NULI', '=', $line)
  5181. ->where('INST_ESTA', '=', 'Activo')
  5182. ->where('UBAR_NULI', '=', $line)
  5183. ->where('UBAR_ESTA', '=', 'Activo')
  5184. ->leftJoin('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  5185. ->leftJoin('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  5186. ->leftJoin('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  5187. ->leftJoin('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  5188. ->leftJoin('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  5189. ->leftJoin('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  5190. ->leftJoin('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  5191. ->leftJoin('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  5192. ->leftJoin('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  5193. ->first([
  5194. 'INST_MODE AS MODELO',
  5195. 'INST_COMO AS CODIGO_MODELO',
  5196. 'FAMI_COFA AS CODIGO_FAMILIA',
  5197. 'FAMI_NOFA AS FAMILIA',
  5198. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  5199. 'SUBF_NOSU AS SUBFAMILIA',
  5200. 'ALMA_COAL AS CODIGO_ALMACEN',
  5201. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  5202. 'AREA_COAR AS CODIGO_AREA',
  5203. 'AREA_NOAR AS NOMBRE_AREA',
  5204. 'NIVE_CONI AS CODIGO_NIVEL',
  5205. 'NIVE_NONI AS NOMBRE_NIVEL',
  5206. 'ZONA_COZO AS CODIGO_ZONA',
  5207. 'ZONA_NOZO AS NOMBRE_ZONA',
  5208. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  5209. ]);
  5210. } catch (\Throwable $th) {
  5211. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el ID del stock.', $th->getMessage(), 500);
  5212. }
  5213. if (empty($info)) {
  5214. return $this->responseController->makeResponse(true, 'No se encontró la información del código.', [], 500);
  5215. }
  5216. $codeEquipment = $info['CODIGO_EQUIPAMIENTO'];
  5217. $arrStructureCode = explode('_', $codeEquipment);
  5218. if ( count($arrStructureCode) !== 2 ) {
  5219. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la estructura del código.' [], 500);
  5220. }
  5221. $strLBS = $arrStructureCode[0];
  5222. $arrStructureLBS = explode('.', $strLBS);
  5223. if (count($arrStructureLBS) !== 4) {
  5224. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la estructura del LBS.' [], 500);
  5225. }
  5226. $levelOccupation = $arrStructureLBS[2];
  5227. $arrStructureLevelOccupation = explode('-', $levelOccupation);
  5228. if (count($arrStructureLevelOccupation) !== 2) {
  5229. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el nivel y la ocupación.', [], 500);
  5230. }
  5231. $codeSite = $arrStructureLBS[0];
  5232. $codeLocation = $arrStructureLBS[1];
  5233. $codeElement = $arrStructureLBS[3];
  5234. $codeLevel = $arrStructureLevelOccupation[0];
  5235. $codeOccupation = $arrStructureLevelOccupation[1];
  5236. $strPBS = $arrStructureCode[1];
  5237. $arrStructurePBS = explode('.', $strPBS);
  5238. if ( count($arrStructurePBS) !== 4 ) {
  5239. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la estructura del PBS.', [], 500);
  5240. }
  5241. $typeModel = $arrStructurePBS[3];
  5242. $arrStructureTypeModel = explode('-', $typeModel);
  5243. if (count($arrStructureTypeModel) !== 3) {
  5244. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener tipo y modelo.', [], 500);
  5245. }
  5246. $codeFamily = $arrStructurePBS[0];
  5247. $codeSubfamily = $arrStructurePBS[1];
  5248. $codeState = $arrStructurePBS[2];
  5249. $codeType = $arrStructureTypeModel[0];
  5250. $codeModel = $arrStructureTypeModel[1];
  5251. $arrClaves = array(
  5252. 'CLAVE_SITIO' => $codeSite,
  5253. 'SITIO' => 'Número de Línea 01',
  5254. 'CLAVE_UBICACION' => $codeLocation,
  5255. 'UBICACION' => $info['NOMBRE_AREA'],
  5256. 'CLAVE_POSICION' => $codeElement,
  5257. 'POSICION' => $info['NOMBRE_NIVEL'],
  5258. 'CLAVE_OCUPACION' => $codeLevel,
  5259. 'OCUPACION' => $info['NOMBRE_ALMACEN'],
  5260. 'CLAVE_ELEMENTO' => $codeOccupation,
  5261. 'ELEMENTO' => $info['NOMBRE_ZONA'],
  5262. 'CLAVE_FAMILIA' => $codeFamily,
  5263. 'FAMILIA' => $info['FAMILIA'],
  5264. 'CLAVE_SUBFAMILIA' => $codeSubfamily,
  5265. 'SUBFAMILIA' => $info['SUBFAMILIA'],
  5266. 'CLAVE_ESTADO' => $codeState,
  5267. 'ESTADO' => $this->resourcesController->arrStatesEquipment[$codeState],
  5268. 'CLAVE_TIPO' => $codeType,
  5269. 'TIPO' => $info['MODELO'],
  5270. 'CLAVE_MODELO' => $codeModel,
  5271. 'MODELO' => $info['CODIGO_MODELO'],
  5272. );
  5273. return $this->responseController->makeResponse(false, 'ÉXITO: Consulta Exitosa.', $arrClaves);
  5274. }
  5275. public function getObjectProperties($user, $line) {
  5276. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5277. if ($arrResponseCheckUser['error']) {
  5278. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5279. }
  5280. try {
  5281. $arrStock = DB::table('S002V01TSTAR')
  5282. ->where('STAR_NULI', '=', $line)
  5283. ->where('STAR_ESTA', '=', 'Activo')
  5284. ->where('INST_NULI', '=', $line)
  5285. ->where('INST_ESTA', '=', 'Activo')
  5286. ->where('UBAR_NULI', '=', $line)
  5287. ->where('UBAR_ESTA', '=', 'Activo')
  5288. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  5289. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  5290. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  5291. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  5292. ->get([
  5293. 'STAR_IDST AS ID_STOCK',
  5294. 'INST_MODE AS MODELO',
  5295. 'INST_COMO AS CODIGO_MODELO',
  5296. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  5297. 'INST_IMAG AS IMAGENES',
  5298. 'FAMI_COFA AS CODIGO_FAMILIA',
  5299. 'FAMI_NOFA AS FAMILIA',
  5300. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  5301. 'SUBF_NOSU AS SUBFAMILIA',
  5302. ]);
  5303. $arrStock = json_decode(json_encode($arrStock), true);
  5304. } catch (\Throwable $th) {
  5305. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información del stock.', $th->getMessage(), 500);
  5306. }
  5307. foreach ($arrStock as $key => $info) {
  5308. $arrImages = json_decode($info['IMAGENES']);
  5309. $arrUrlImage = array();
  5310. foreach ($arrImages as $keyImages => $images) {
  5311. $images = $this->encController->encrypt($images);
  5312. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  5313. if ($responseDocument['error']) {
  5314. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  5315. }
  5316. $arrUrlImage[] = $responseDocument['response']['public_uri'];
  5317. }
  5318. $arrStock[$key]['IMAGENES'] = $arrUrlImage;
  5319. }
  5320. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrStock);
  5321. }
  5322. public function getDetailsObjectProperties($idStock, $user, $line) {
  5323. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5324. if ($arrResponseCheckUser['error']) {
  5325. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5326. }
  5327. $idStock = $this->encController->decrypt($idStock);
  5328. if (is_null($idStock)) {
  5329. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  5330. }
  5331. try {
  5332. $validateExists = DB::table('S002V01TSTAR')
  5333. ->where('STAR_IDST', '=', $idStock)
  5334. ->where('STAR_NULI', '=', $line)
  5335. ->where('STAR_ESTA', '=', 'Activo')
  5336. ->exists();
  5337. } catch (\Throwable $th) {
  5338. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el ID del stock.', $th->getMessage(), 500);
  5339. }
  5340. if (!$validateExists) {
  5341. return $this->responseController->makeResponse(true, 'El número de stock no existe.', [], 500);
  5342. }
  5343. try {
  5344. $arrStock = (array) DB::table('S002V01TSTAR')
  5345. ->where('STAR_IDST', '=', $idStock)
  5346. ->where('STAR_NULI', '=', $line)
  5347. ->where('STAR_ESTA', '=', 'Activo')
  5348. ->where('INST_NULI', '=', $line)
  5349. ->where('INST_ESTA', '=', 'Activo')
  5350. ->where('UBAR_NULI', '=', $line)
  5351. ->where('UBAR_ESTA', '=', 'Activo')
  5352. ->where('FAMI_NULI', '=', $line)
  5353. ->where('FAMI_ESTA', '=', 'Activo')
  5354. ->where('SUBF_NULI', '=', $line)
  5355. ->where('SUBF_ESTA', '=', 'Activo')
  5356. ->join('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  5357. ->join('S002V01TUBAR', 'UBAR_IDST', '=', 'STAR_IDST')
  5358. ->join('S002V01TFAMI', 'FAMI_COFA', '=', 'INST_COFA')
  5359. ->join('S002V01TSUBF', 'SUBF_COSU', '=', 'INST_COSU')
  5360. ->join('S002V01TALMA', 'ALMA_COAL', '=', 'UBAR_COAL')
  5361. ->join('S002V01TAREA', 'AREA_COAR', '=', 'UBAR_COAR')
  5362. ->join('S002V01TNIVE', 'NIVE_CONI', '=', 'UBAR_CONI')
  5363. ->join('S002V01TZONA', 'ZONA_COZO', '=', 'UBAR_COZO')
  5364. ->first([
  5365. 'STAR_COBA AS CODIGO_BARRA',
  5366. 'STAR_FEVE AS FECHA_VENCIMIENTO',
  5367. 'STAR_NUPR AS NUMERO_PROVEEDOR',
  5368. 'STAR_TIAD AS TIPO_ADQUISICION',
  5369. 'STAR_CONS AS CONSUMIBLE',
  5370. 'STAR_REPA AS REPARABLE',
  5371. 'STAR_ALTO AS ALTO',
  5372. 'STAR_ANCH AS ANCHO',
  5373. 'STAR_LARG AS LARGO',
  5374. 'STAR_COLO AS COLOR',
  5375. 'STAR_PRAD AS PRECIO_ADQUIRIDO',
  5376. 'STAR_COMO AS CODIGO_MONEDA',
  5377. 'INST_MODE AS MODELO',
  5378. 'INST_COMO AS CODIGO_MODELO',
  5379. 'INST_STMI AS STOCK_MINIMO',
  5380. 'INST_STMA AS STOCK_MAXIMO',
  5381. 'STAR_NIPE AS NIVEL_PELIGROSIDAD',
  5382. 'INST_IMAG AS IMAGENES',
  5383. 'UBAR_COUB AS CODIGO_EQUIPAMIENTO',
  5384. 'FAMI_COFA AS CODIGO_FAMILIA',
  5385. 'FAMI_NOFA AS NOMBRE_FAMILIA',
  5386. 'SUBF_COSU AS CODIGO_SUBFAMILIA',
  5387. 'SUBF_NOSU AS NOMBRE_SUBFAMILIA',
  5388. 'ALMA_COAL AS CODIGO_ALMACEN',
  5389. 'ALMA_NOAL AS NOMBRE_ALMACEN',
  5390. 'AREA_COAR AS CODIGO_AREA',
  5391. 'AREA_NOAR AS NOMBRE_AREA',
  5392. 'NIVE_CONI AS CODIGO_NIVEL',
  5393. 'NIVE_NONI AS NOMBRE_NIVEL',
  5394. 'ZONA_COZO AS CODIGO_ZONA',
  5395. 'ZONA_NOZO AS NOMBRE_ZONA',
  5396. ]);
  5397. } catch (\Throwable $th) {
  5398. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los datos del stock.', $th->getMessage(), 500);
  5399. }
  5400. if (empty($arrStock)) {
  5401. return $this->responseController->makeResponse(true, 'No existe información de stock.', [], 500);
  5402. }
  5403. $arrImages = array();
  5404. $arrImagesTemp = json_decode($arrStock['IMAGENES']);
  5405. foreach ($arrImagesTemp as $key => $value) {
  5406. $images = $this->encController->encrypt($value);
  5407. $responseDocument = $this->documentManagementController->privateGetPublicDocumentURL($images, $user, $line);
  5408. if ($responseDocument['error']) {
  5409. return $this->responseController->makeResponse(true, $responseDocument['msg'], [], 500);
  5410. }
  5411. $arrImages[] = $responseDocument['response']['public_uri'];
  5412. }
  5413. $arrStock['IMAGENES'] = $arrImages;
  5414. if($arrStock['TIPO_ADQUISICION'] == 'Sin Pedido'){
  5415. $arrStock['DESCRIPCION_PROVEEDOR'] = null;
  5416. $arrStock['CARACTERISTICA_PROVEEDOR'] = null;
  5417. $arrStock['NOMBRE_PROVEEDOR'] = null;
  5418. goto noAdquisition;
  5419. }
  5420. try {
  5421. $infoAdquisition = (array) DB::table('S002V01TINAR')
  5422. ->where('INAR_NULI', '=', $line)
  5423. ->where('INAR_CODI', '=', $arrStock['CODIGO_MODELO'])
  5424. ->where('INAR_MODE', '=', $arrStock['MODELO'])
  5425. ->where('INAR_ESTA', '=', 'Activo')
  5426. ->where('DEAR_NULI', '=', $line)
  5427. ->where('DEAR_NUPR', '=', $arrStock['NUMERO_PROVEEDOR'])
  5428. ->where('DEAR_ESTA', '=', 'Activo')
  5429. ->where('ARTI_NULI', '=', $line)
  5430. ->where('ARTI_COFA', '=', $arrStock['CODIGO_FAMILIA'])
  5431. ->where('ARTI_COSU', '=', $arrStock['CODIGO_SUBFAMILIA'])
  5432. ->where('ARTI_ESTA', '=', 'Activo')
  5433. ->leftJoin('S002V01TDEAR', 'DEAR_IDDE', '=', 'INAR_IDDE')
  5434. ->leftJoin('S002V01TARTI', 'ARTI_IDAR', '=', 'DEAR_IDAR')
  5435. ->leftJoin('S002V01TPROV', 'PROV_NUPR', '=', 'DEAR_NUPR')
  5436. ->first([
  5437. 'DEAR_DESC AS DESCRIPCION_PROVEEDOR',
  5438. 'DEAR_CARA AS CARACTERISTICA_PROVEEDOR',
  5439. 'PROV_NOCO AS NOMBRE_PROVEEDOR',
  5440. ]);
  5441. } catch (\Throwable $th) {
  5442. DB::rollBack();
  5443. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener la información de la adquisición.', $th->getMessage(), 500);
  5444. }
  5445. if (empty($infoAdquisition)) {
  5446. /*DB::rollBack();
  5447. return $this->responseController->makeResponse(true, 'No se encontró la información de la adquisición.', [], 500);*/
  5448. $infoAdquisition = [
  5449. "DESCRIPCION_PROVEEDOR" => '-',
  5450. "CARACTERISTICA_PROVEEDOR" => '-',
  5451. "NOMBRE_PROVEEDOR" => '-',
  5452. ];
  5453. }
  5454. $arrGeneralInfo = array_merge($arrStock, $infoAdquisition);
  5455. return $this->responseController->makeResponse(false, 'ÉXITO: Consulta Exitosa', $arrGeneralInfo);
  5456. noAdquisition:
  5457. return $this->responseController->makeResponse(false, 'ÉXITO: Consulta Exitosa', $arrStock);
  5458. }
  5459. public function saveInfoStock(Request $request, $idStock) {
  5460. $valitador = Validator::make($request->all(), [
  5461. 'ALTO' => 'string|nullable',
  5462. 'ANCHO' => 'string|nullable',
  5463. 'LARGO' => 'string|nullable',
  5464. 'COLOR' => 'string|nullable',
  5465. 'NIVEL_PELIGROSIDAD' => 'string|nullable',
  5466. 'TASA_ROTACION' => 'string|nullable',
  5467. 'USUARIO' => 'required|string',
  5468. 'NUMERO_LINEA' => 'required|integer',
  5469. ]);
  5470. if ($valitador->fails()) {
  5471. return $this->responseController->makeResponse(
  5472. true,
  5473. "ERR_DOCUMENT_ORDER_REG000: Se encontraron uno o más errores.",
  5474. $this->responseController->makeErrors($valitador->errors()->messages()),
  5475. 401
  5476. );
  5477. }
  5478. DB::beginTransaction();
  5479. $requestData = $request->all();
  5480. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($requestData['USUARIO'], $requestData['NUMERO_LINEA']);
  5481. if ($arrResponseCheckUser['error']) {
  5482. DB::rollBack();
  5483. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5484. }
  5485. $user = $arrResponseCheckUser['response'];
  5486. $idStock = $this->encController->decrypt($idStock);
  5487. if (is_null($idStock)) {
  5488. DB::rollBack();
  5489. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener el ID de la información.', [], 401);
  5490. }
  5491. try {
  5492. $validateExists = DB::table('S002V01TSTAR')
  5493. ->where('STAR_IDST', '=', $idStock)
  5494. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  5495. ->where('STAR_ESTA', '=', 'Activo')
  5496. ->exists();
  5497. } catch (\Throwable $th) {
  5498. DB::rollBack();
  5499. return $this->responseController->makeResponse(true, 'Ocurrió un error al verificar el ID del stock.', $th->getMessage(), 500);
  5500. }
  5501. if (!$validateExists) {
  5502. DB::rollBack();
  5503. return $this->responseController->makeResponse(true, 'El número de stock no existe.', [], 500);
  5504. }
  5505. $now = $this->functionsController->now();
  5506. $currentDate = $now->toDateTimeString();
  5507. try {
  5508. $validateInsert = DB::table('S002V01TSTAR')
  5509. ->where('STAR_IDST', '=', $idStock)
  5510. ->where('STAR_NULI', '=', $requestData['NUMERO_LINEA'])
  5511. ->where('STAR_ESTA', '=', 'Activo')
  5512. ->update([
  5513. 'STAR_ALTO' => $requestData['ALTO'],
  5514. 'STAR_ANCH' => $requestData['ANCHO'],
  5515. 'STAR_LARG' => $requestData['LARGO'],
  5516. 'STAR_COLO' => $requestData['COLOR'],
  5517. 'STAR_NIPE' => $requestData['NIVEL_PELIGROSIDAD'],
  5518. 'STAR_USMO' => $user,
  5519. 'STAR_FEMO' => $currentDate,
  5520. 'STAR_FEAR' => DB::raw('CURRENT_TIMESTAMP'),
  5521. ]);
  5522. } catch (\Throwable $th) {
  5523. DB::rollBack();
  5524. return $this->responseController->makeResponse(true, 'Ocurrió un error al insertar los datos del stock.', $th->getMessage(), 500);
  5525. }
  5526. if (!$validateInsert) {
  5527. DB::rollBack();
  5528. return $this->responseController->makeResponse(true, 'No se pudo insertar los datos del stock.', [], 500);
  5529. }
  5530. DB::commit();
  5531. return $this->responseController->makeResponse(false, 'ÉXITO: Registro Exitoso');
  5532. }
  5533. public function getToolsAndSpare ($user, $line) {
  5534. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5535. if ($arrResponseCheckUser['error']) {
  5536. DB::rollBack();
  5537. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5538. }
  5539. try {
  5540. $arrStock = DB::table('S002V01TINST')
  5541. ->where([
  5542. ['INST_NULI', '=', $line],
  5543. ])->get([
  5544. 'INST_IDIS AS ID',
  5545. 'INST_MODE AS NOMB',
  5546. 'INST_COMO AS MODE',
  5547. ]);
  5548. $arrStock = json_decode(json_encode($arrStock), true);
  5549. } catch (\Throwable $th) {
  5550. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los artículos en stock.', $th->getMessage(), 500);
  5551. }
  5552. $arrTools = [];
  5553. $arrSpares = [];
  5554. foreach ($arrStock as $stock) {
  5555. try {
  5556. $idStockStr = "" . $stock["ID"] . "";
  5557. for($i = strlen($idStockStr); $i < 10; $i++){
  5558. $idStockStr = "0" . $idStockStr;
  5559. }
  5560. $items = DB::table('S002V01TSTAR')
  5561. ->where([
  5562. ['STAR_NULI', '=', $line],
  5563. ['STAR_IDIS', '=', $idStockStr],
  5564. ])
  5565. ->leftJoin('S002V01TUNID', 'UNID_IDUN', '=', 'STAR_IDUN')
  5566. ->get([
  5567. 'UNID_NOMB AS UNIT',
  5568. 'STAR_CONS AS TYPE',
  5569. ]);
  5570. $items = json_decode(json_encode($items), true);
  5571. } catch (\Throwable $th) {
  5572. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los datos de las herramientas y refacciones.', $th->getMessage(), 500);
  5573. }
  5574. $stock['CANTDISP'] = count($items);
  5575. foreach ($items as $item) {
  5576. if ($item['TYPE'] === 'Si') {
  5577. $stock['TYPE'] = 'Refaccción';
  5578. } else {
  5579. $stock['TYPE'] = 'Herramienta';
  5580. }
  5581. $stock['UNIT'] = $item['UNIT'];
  5582. }
  5583. $stock['ID'] = $this->encController->encrypt("{$stock['ID']}");
  5584. if ($stock['TYPE'] === 'Refaccción') {
  5585. $arrSpares[] = $stock;
  5586. } else {
  5587. $arrTools[] = $stock;
  5588. }
  5589. }
  5590. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", [ 'HERRAMIENTAS' => $arrTools, 'REFACCIONES' => $arrSpares ]);
  5591. }
  5592. public function getArticleClassificateByWarehouse ($idWarehouse, $user, $line) {
  5593. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5594. if ($arrResponseCheckUser['error']) {
  5595. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5596. }
  5597. $idWarehouse = $this->encController->decrypt($idWarehouse);
  5598. if (is_null($idWarehouse)) {
  5599. return $this->responseController->makeResponse(true, "El identificador del almancen no fue encritpado correctamente", [], 500);
  5600. }
  5601. try {
  5602. $arrStock = DB::table('S002V01TUBAR')
  5603. ->where([
  5604. ['UBAR_COAL', '=', $idWarehouse],
  5605. ['UBAR_ESTA', '=', 'Activo'],
  5606. ['UBAR_NULI', '=', $line],
  5607. ['STAR_ESTA', '=', 'Activo'],
  5608. ])
  5609. ->leftJoin('S002V01TSTAR', 'STAR_IDST', '=', 'UBAR_IDST')
  5610. ->leftJoin('S002V01TINST', 'INST_IDIS', '=', 'STAR_IDIS')
  5611. ->leftJoin('S002V01TPROV', 'PROV_NUPR', '=', 'STAR_NUPR')
  5612. ->leftJoin('S002V01TINAR', function($join) {
  5613. $join->on('INAR_CODI', '=', 'INST_COMO')
  5614. ->on('INAR_MODE', '=', 'INST_MODE');
  5615. })
  5616. ->get([
  5617. 'STAR_IDST AS ID_STOCK',
  5618. 'PROV_NUPR AS NUMERO_PROVEEDOR',
  5619. 'PROV_NOCO AS PROVEEDOR',
  5620. 'INST_IDIS AS ID_INFORMACION',
  5621. 'INST_MODE AS TIPO_EQUIPAMIENTO',
  5622. 'INST_COMO AS MODELO_EQUIPAMIENTO',
  5623. 'INAR_PREC AS PRECIO',
  5624. 'INAR_COMO AS MONEDA',
  5625. 'STAR_FERE AS FECHA_ADQUISICION',
  5626. ]);
  5627. $arrStock = json_decode(json_encode($arrStock), true);
  5628. } catch (\Throwable $th) {
  5629. return $this->responseController->makeResponse(true, "Ocurrió un error al obtener la información del almacen.", $th->getMessage(), 500);
  5630. }
  5631. $dateOneYearAgo = Carbon::now()->subYears(1);
  5632. $dateHalfYearAgo = Carbon::now()->subMonth(6);
  5633. $dateOneMonthAgo = Carbon::now()->subMonth(1);
  5634. $arrClassificateOneYearAgo = [];
  5635. $arrClassificateHalfYearAgo = [];
  5636. $arrClassificateOneMonthAgo = [];
  5637. $arrClassificate = [];
  5638. foreach ($arrStock as $stock) {
  5639. $providerExists = in_array($stock['NUMERO_PROVEEDOR'], array_column($arrClassificateOneYearAgo, 'NUMERO_PROVEEDOR'));
  5640. $typeExists = in_array($stock['TIPO_EQUIPAMIENTO'], array_column($arrClassificateOneYearAgo, 'TIPO_EQUIPAMIENTO'));
  5641. $modelExists = in_array($stock['MODELO_EQUIPAMIENTO'], array_column($arrClassificateOneYearAgo, 'MODELO_EQUIPAMIENTO'));
  5642. if ($providerExists && $typeExists && $modelExists) {
  5643. $index = array_search($stock['ID_INFORMACION'], array_column($arrClassificateOneYearAgo, 'ID_INFORMACION'));
  5644. $arrClassificateOneYearAgo[$index]['CANTIDAD'] += 1;
  5645. } else {
  5646. $dateAdquisition = new Carbon($stock['FECHA_ADQUISICION']);
  5647. if ($dateAdquisition->gte($dateOneYearAgo)) {
  5648. $arrClassificateOneYearAgo[] = [
  5649. 'ID_INFORMACION' => $stock['ID_INFORMACION'],
  5650. 'NUMERO_PROVEEDOR' => $stock['NUMERO_PROVEEDOR'],
  5651. 'PROVEEDOR' => $stock['PROVEEDOR'],
  5652. 'TIPO_EQUIPAMIENTO' => $stock['TIPO_EQUIPAMIENTO'],
  5653. 'MODELO_EQUIPAMIENTO' => $stock['MODELO_EQUIPAMIENTO'],
  5654. 'PRECIO' => $stock['PRECIO'],
  5655. 'MONEDA' => $stock['MONEDA'],
  5656. 'FECHA_ADQUISICION' => $stock['FECHA_ADQUISICION'],
  5657. 'CANTIDAD' => 1,
  5658. ];
  5659. }
  5660. }
  5661. $providerExists = in_array($stock['NUMERO_PROVEEDOR'], array_column($arrClassificateHalfYearAgo, 'NUMERO_PROVEEDOR'));
  5662. $typeExists = in_array($stock['TIPO_EQUIPAMIENTO'], array_column($arrClassificateHalfYearAgo, 'TIPO_EQUIPAMIENTO'));
  5663. $modelExists = in_array($stock['MODELO_EQUIPAMIENTO'], array_column($arrClassificateHalfYearAgo, 'MODELO_EQUIPAMIENTO'));
  5664. if ($providerExists && $typeExists && $modelExists) {
  5665. $index = array_search($stock['ID_INFORMACION'], array_column($arrClassificateHalfYearAgo, 'ID_INFORMACION'));
  5666. $arrClassificateHalfYearAgo[$index]['CANTIDAD'] += 1;
  5667. } else {
  5668. $dateAdquisition = new Carbon($stock['FECHA_ADQUISICION']);
  5669. if ($dateAdquisition->gte($dateHalfYearAgo)) {
  5670. $arrClassificateHalfYearAgo[] = [
  5671. 'ID_INFORMACION' => $stock['ID_INFORMACION'],
  5672. 'NUMERO_PROVEEDOR' => $stock['NUMERO_PROVEEDOR'],
  5673. 'PROVEEDOR' => $stock['PROVEEDOR'],
  5674. 'TIPO_EQUIPAMIENTO' => $stock['TIPO_EQUIPAMIENTO'],
  5675. 'MODELO_EQUIPAMIENTO' => $stock['MODELO_EQUIPAMIENTO'],
  5676. 'PRECIO' => $stock['PRECIO'],
  5677. 'MONEDA' => $stock['MONEDA'],
  5678. 'FECHA_ADQUISICION' => $stock['FECHA_ADQUISICION'],
  5679. 'CANTIDAD' => 1,
  5680. ];
  5681. }
  5682. }
  5683. $providerExists = in_array($stock['NUMERO_PROVEEDOR'], array_column($arrClassificateOneMonthAgo, 'NUMERO_PROVEEDOR'));
  5684. $typeExists = in_array($stock['TIPO_EQUIPAMIENTO'], array_column($arrClassificateOneMonthAgo, 'TIPO_EQUIPAMIENTO'));
  5685. $modelExists = in_array($stock['MODELO_EQUIPAMIENTO'], array_column($arrClassificateOneMonthAgo, 'MODELO_EQUIPAMIENTO'));
  5686. if ($providerExists && $typeExists && $modelExists) {
  5687. $index = array_search($stock['ID_INFORMACION'], array_column($arrClassificateOneMonthAgo, 'ID_INFORMACION'));
  5688. $arrClassificateOneMonthAgo[$index]['CANTIDAD'] += 1;
  5689. } else {
  5690. $dateAdquisition = new Carbon($stock['FECHA_ADQUISICION']);
  5691. if ($dateAdquisition->gte($dateOneMonthAgo)) {
  5692. $arrClassificateOneMonthAgo[] = [
  5693. 'ID_INFORMACION' => $stock['ID_INFORMACION'],
  5694. 'NUMERO_PROVEEDOR' => $stock['NUMERO_PROVEEDOR'],
  5695. 'PROVEEDOR' => $stock['PROVEEDOR'],
  5696. 'TIPO_EQUIPAMIENTO' => $stock['TIPO_EQUIPAMIENTO'],
  5697. 'MODELO_EQUIPAMIENTO' => $stock['MODELO_EQUIPAMIENTO'],
  5698. 'PRECIO' => $stock['PRECIO'],
  5699. 'MONEDA' => $stock['MONEDA'],
  5700. 'FECHA_ADQUISICION' => $stock['FECHA_ADQUISICION'],
  5701. 'CANTIDAD' => 1,
  5702. ];
  5703. }
  5704. }
  5705. $providerExists = in_array($stock['NUMERO_PROVEEDOR'], array_column($arrClassificate, 'NUMERO_PROVEEDOR'));
  5706. $typeExists = in_array($stock['TIPO_EQUIPAMIENTO'], array_column($arrClassificate, 'TIPO_EQUIPAMIENTO'));
  5707. $modelExists = in_array($stock['MODELO_EQUIPAMIENTO'], array_column($arrClassificate, 'MODELO_EQUIPAMIENTO'));
  5708. if ($providerExists && $typeExists && $modelExists) {
  5709. $index = array_search($stock['ID_INFORMACION'], array_column($arrClassificate, 'ID_INFORMACION'));
  5710. $arrClassificate[$index]['CANTIDAD'] += 1;
  5711. } else {
  5712. $arrClassificate[] = [
  5713. 'ID_INFORMACION' => $stock['ID_INFORMACION'],
  5714. 'NUMERO_PROVEEDOR' => $stock['NUMERO_PROVEEDOR'],
  5715. 'PROVEEDOR' => $stock['PROVEEDOR'],
  5716. 'TIPO_EQUIPAMIENTO' => $stock['TIPO_EQUIPAMIENTO'],
  5717. 'MODELO_EQUIPAMIENTO' => $stock['MODELO_EQUIPAMIENTO'],
  5718. 'PRECIO' => $stock['PRECIO'],
  5719. 'MONEDA' => $stock['MONEDA'],
  5720. 'FECHA_ADQUISICION' => $stock['FECHA_ADQUISICION'],
  5721. 'CANTIDAD' => 1,
  5722. ];
  5723. }
  5724. }
  5725. foreach ($arrClassificate as $key => $classificate) {
  5726. foreach ($arrClassificateOneYearAgo as $classificateTemp) {
  5727. if ($classificate['ID_INFORMACION'] === $classificateTemp['ID_INFORMACION']) {
  5728. $classificate['TASA_ROTACION_ANUAL'] = ($classificateTemp['PRECIO'] * $classificateTemp['CANTIDAD']) / $classificate['CANTIDAD'];
  5729. }
  5730. }
  5731. foreach ($arrClassificateHalfYearAgo as $classificateTemp) {
  5732. if ($classificate['ID_INFORMACION'] === $classificateTemp['ID_INFORMACION']) {
  5733. $classificate['TASA_ROTACION_SEMESTRAL'] = ($classificateTemp['PRECIO'] * $classificateTemp['CANTIDAD']) / $classificate['CANTIDAD'];
  5734. }
  5735. }
  5736. foreach ($arrClassificateOneMonthAgo as $classificateTemp) {
  5737. if ($classificate['ID_INFORMACION'] === $classificateTemp['ID_INFORMACION']) {
  5738. $classificate['TASA_ROTACION_MENSUAL'] = ($classificateTemp['PRECIO'] * $classificateTemp['CANTIDAD']) / $classificate['CANTIDAD'];
  5739. }
  5740. }
  5741. $classificate['PROVEEDOR'] = "{$classificate['PROVEEDOR']} ({$classificate['NUMERO_PROVEEDOR']})";
  5742. $arrClassificate[$key] = $classificate;
  5743. }
  5744. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrClassificate);
  5745. }
  5746. public function getValueStockByPeriod ($idWarehouse, $user, $line) {
  5747. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5748. if ($arrResponseCheckUser['error']) {
  5749. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5750. }
  5751. $idWarehouse = $this->encController->decrypt($idWarehouse);
  5752. if (is_null($idWarehouse)) {
  5753. return $this->responseController->makeResponse(true, "El identificador del almancen no fue encritpado correctamente", [], 500);
  5754. }
  5755. try {
  5756. $arrInformation = DB::table('S002V01TVAST')
  5757. ->where([
  5758. ['VAST_COAL', '=', $idWarehouse],
  5759. ['VAST_NULI', '=', $line],
  5760. ['VAST_ESTA', '=', 'Estado'],
  5761. ])
  5762. ->get([
  5763. 'VAST_IDVS AS ID_VALOR',
  5764. 'VAST_INME AS INFORMACION_VALOR',
  5765. 'VAST_PERI AS PERIODO',
  5766. 'VAST_FERE AS USUARIO_REGISTRA',
  5767. 'VAST_USRE AS FECHA_REGISTRA',
  5768. 'VAST_FEMO AS USUARIO_MODIFICA',
  5769. 'VAST_USMO AS FECHA_MODIFICA',
  5770. ]);
  5771. $arrInformation = json_decode(json_encode($arrInformation), true);
  5772. } catch (\Throwable $th) {
  5773. return $this->responseController->makeResponse(true, "", $th->getMessage(), 500);
  5774. }
  5775. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrInformation, $line);
  5776. if ($responseCheckLatestUpdate['error']) {
  5777. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  5778. }
  5779. $arrInformation = $responseCheckLatestUpdate['response'];
  5780. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrInformation);
  5781. }
  5782. public function getArticlesWithoutMovements($user, $line) {
  5783. $arrResponseCheckUser = $this->resourcesController->checkUserEnc($user, $line);
  5784. if ($arrResponseCheckUser['error']) {
  5785. return $this->responseController->makeResponse(true, $arrResponseCheckUser['msg'], [], 401);
  5786. }
  5787. try {
  5788. $arrArticles = DB::table('S002V01TUBAR')
  5789. ->where([
  5790. ['UBAR_NULI', '=', $line],
  5791. ['UBAR_ESTA', '=', 'Activo'],
  5792. ])
  5793. ->distinct('UBAR_IDST')
  5794. ->orderBy('UBAR_FERE', 'DESC')
  5795. ->get([
  5796. 'UBAR_IDST AS ID_STOCK',
  5797. 'UBAR_FERE AS FECHA_REGISTRA',
  5798. 'UBAR_USRE AS USUARIO_REGISTRA',
  5799. 'UBAR_FEMO AS FECHA_MODIFICA',
  5800. 'UBAR_USMO AS USUARIO_MODIFICA',
  5801. ]);
  5802. $arrArticles = json_decode(json_encode($arrArticles), true);
  5803. } catch (\Throwable $th) {
  5804. return $this->responseController->makeResponse(true, 'Ocurrió un error al obtener los artículos.', $th->getMessage(), 401);
  5805. }
  5806. $responseCheckLatestUpdate = $this->resourcesController->checkLatestUpdate($arrArticles, $line);
  5807. if ($responseCheckLatestUpdate['error']) {
  5808. return $this->responseController->makeResponse(true, $responseCheckLatestUpdate['msg'], [], 500);
  5809. }
  5810. $arrArticles = $responseCheckLatestUpdate['response'];
  5811. $currentDate = Carbon::now();
  5812. foreach ($arrArticles as $key => $article) {
  5813. $dateStock = new Carbon($article['FECHA_MODIFICA']);
  5814. $diff = $currentDate->diff($dateStock);
  5815. $article['DIFERENCIA_ANIOS'] = $diff->y;
  5816. $article['DIFERENCIA_MES'] = $diff->m;
  5817. $article['DIFERENCIA_DIAS'] = $diff->d;
  5818. $arrArticles[$key] = $article;
  5819. }
  5820. return $this->responseController->makeResponse(false, "ÉXITO: Consulta Exitosa", $arrArticles);
  5821. }
  5822. }