product.class.php 220 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069
  1. <?php
  2. /* Copyright (C) 2001-2007 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2014 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2015 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
  6. * Copyright (C) 2007-2011 Jean Heimburger <jean@tiaris.info>
  7. * Copyright (C) 2010-2018 Juanjo Menent <jmenent@2byte.es>
  8. * Copyright (C) 2012 Cedric Salvador <csalvador@gpcsolutions.fr>
  9. * Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
  10. * Copyright (C) 2013-2016 Marcos García <marcosgdf@gmail.com>
  11. * Copyright (C) 2011-2021 Open-DSI <support@open-dsi.fr>
  12. * Copyright (C) 2014 Henry Florian <florian.henry@open-concept.pro>
  13. * Copyright (C) 2014-2016 Philippe Grand <philippe.grand@atoo-net.com>
  14. * Copyright (C) 2014 Ion agorria <ion@agorria.com>
  15. * Copyright (C) 2016-2018 Ferran Marcet <fmarcet@2byte.es>
  16. * Copyright (C) 2017 Gustavo Novaro
  17. * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
  18. *
  19. * This program is free software; you can redistribute it and/or modify
  20. * it under the terms of the GNU General Public License as published by
  21. * the Free Software Foundation; either version 3 of the License, or
  22. * (at your option) any later version.
  23. *
  24. * This program is distributed in the hope that it will be useful,
  25. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  26. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  27. * GNU General Public License for more details.
  28. *
  29. * You should have received a copy of the GNU General Public License
  30. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  31. */
  32. /**
  33. * \file htdocs/product/class/product.class.php
  34. * \ingroup produit
  35. * \brief File of class to manage predefined products or services
  36. */
  37. require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  38. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  39. require_once DOL_DOCUMENT_ROOT.'/product/class/productbatch.class.php';
  40. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  41. /**
  42. * Class to manage products or services
  43. */
  44. class Product extends CommonObject
  45. {
  46. /**
  47. * @var string ID to identify managed object
  48. */
  49. public $element = 'product';
  50. /**
  51. * @var string Name of table without prefix where object is stored
  52. */
  53. public $table_element = 'product';
  54. /**
  55. * @var string Field with ID of parent key if this field has a parent
  56. */
  57. public $fk_element = 'fk_product';
  58. /**
  59. * @var array List of child tables. To test if we can delete object.
  60. */
  61. protected $childtables = array(
  62. 'supplier_proposaldet',
  63. 'propaldet',
  64. 'commandedet',
  65. 'facturedet',
  66. 'contratdet',
  67. 'facture_fourn_det',
  68. 'commande_fournisseurdet'
  69. );
  70. /**
  71. * 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  72. *
  73. * @var int
  74. */
  75. public $ismultientitymanaged = 1;
  76. /**
  77. * @var string picto
  78. */
  79. public $picto = 'product';
  80. /**
  81. * {@inheritdoc}
  82. */
  83. protected $table_ref_field = 'ref';
  84. public $regeximgext = '\.gif|\.jpg|\.jpeg|\.png|\.bmp|\.webp|\.xpm|\.xbm'; // See also into images.lib.php
  85. /**
  86. * @deprecated
  87. * @see $label
  88. */
  89. public $libelle;
  90. /**
  91. * Product label
  92. *
  93. * @var string
  94. */
  95. public $label;
  96. /**
  97. * Product description
  98. *
  99. * @var string
  100. */
  101. public $description;
  102. /**
  103. * Product other fields PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION
  104. *
  105. * @var string
  106. */
  107. public $other;
  108. /**
  109. * Check TYPE constants
  110. *
  111. * @var int
  112. */
  113. public $type = self::TYPE_PRODUCT;
  114. /**
  115. * Selling price
  116. *
  117. * @var float
  118. */
  119. public $price; // Price net
  120. /**
  121. * Price with tax
  122. *
  123. * @var float
  124. */
  125. public $price_ttc;
  126. /**
  127. * Minimum price net
  128. *
  129. * @var float
  130. */
  131. public $price_min;
  132. /**
  133. * Minimum price with tax
  134. *
  135. * @var float
  136. */
  137. public $price_min_ttc;
  138. /**
  139. * Base price ('TTC' for price including tax or 'HT' for net price)
  140. * @var string
  141. */
  142. public $price_base_type;
  143. //! Arrays for multiprices
  144. public $multiprices = array();
  145. public $multiprices_ttc = array();
  146. public $multiprices_base_type = array();
  147. public $multiprices_min = array();
  148. public $multiprices_min_ttc = array();
  149. public $multiprices_tva_tx = array();
  150. public $multiprices_recuperableonly = array();
  151. //! Price by quantity arrays
  152. public $price_by_qty;
  153. public $prices_by_qty = array();
  154. public $prices_by_qty_id = array();
  155. public $prices_by_qty_list = array();
  156. //! Array for multilangs
  157. public $multilangs = array();
  158. //! Default VAT code for product (link to code into llx_c_tva but without foreign keys)
  159. public $default_vat_code;
  160. //! Default VAT rate of product
  161. public $tva_tx;
  162. //! French VAT NPR (0 or 1)
  163. public $tva_npr = 0;
  164. //! Other local taxes
  165. public $localtax1_tx;
  166. public $localtax2_tx;
  167. public $localtax1_type;
  168. public $localtax2_type;
  169. public $lifetime;
  170. public $qc_frequency;
  171. /**
  172. * Stock real
  173. *
  174. * @var int
  175. */
  176. public $stock_reel = 0;
  177. /**
  178. * Stock virtual
  179. *
  180. * @var int
  181. */
  182. public $stock_theorique;
  183. /**
  184. * Cost price
  185. *
  186. * @var float
  187. */
  188. public $cost_price;
  189. //! Average price value for product entry into stock (PMP)
  190. public $pmp;
  191. /**
  192. * Stock alert
  193. *
  194. * @var float
  195. */
  196. public $seuil_stock_alerte = 0;
  197. /**
  198. * Ask for replenishment when $desiredstock < $stock_reel
  199. */
  200. public $desiredstock = 0;
  201. /*
  202. * Service expiration
  203. */
  204. public $duration_value;
  205. /**
  206. * Exoiration unit
  207. */
  208. public $duration_unit;
  209. /**
  210. * Status indicates whether the product is on sale '1' or not '0'
  211. *
  212. * @var int
  213. */
  214. public $status = 0;
  215. /**
  216. * Status indicate whether the product is available for purchase '1' or not '0'
  217. *
  218. * @var int
  219. */
  220. public $status_buy = 0;
  221. /**
  222. * Status indicates whether the product is a finished product '1' or a raw material '0'
  223. *
  224. * @var int
  225. */
  226. public $finished;
  227. /**
  228. * fk_default_bom indicates the default bom
  229. *
  230. * @var int
  231. */
  232. public $fk_default_bom;
  233. /**
  234. * We must manage lot/batch number, sell-by date and so on : '1':yes '0':no
  235. *
  236. * @var int
  237. */
  238. public $status_batch = 0;
  239. /**
  240. * If allowed, we can edit batch or serial number mask for each product
  241. *
  242. * @var string
  243. */
  244. public $batch_mask = '';
  245. /**
  246. * Customs code
  247. *
  248. * @var string
  249. */
  250. public $customcode;
  251. /**
  252. * Product URL
  253. *
  254. * @var string
  255. */
  256. public $url;
  257. //! Metric of products
  258. public $weight;
  259. public $weight_units; // scale -3, 0, 3, 6
  260. public $length;
  261. public $length_units; // scale -3, 0, 3, 6
  262. public $width;
  263. public $width_units; // scale -3, 0, 3, 6
  264. public $height;
  265. public $height_units; // scale -3, 0, 3, 6
  266. public $surface;
  267. public $surface_units; // scale -3, 0, 3, 6
  268. public $volume;
  269. public $volume_units; // scale -3, 0, 3, 6
  270. public $net_measure;
  271. public $net_measure_units; // scale -3, 0, 3, 6
  272. public $accountancy_code_sell;
  273. public $accountancy_code_sell_intra;
  274. public $accountancy_code_sell_export;
  275. public $accountancy_code_buy;
  276. public $accountancy_code_buy_intra;
  277. public $accountancy_code_buy_export;
  278. /**
  279. * Main Barcode value
  280. *
  281. * @var string
  282. */
  283. public $barcode;
  284. /**
  285. * Main Barcode type ID
  286. *
  287. * @var int
  288. */
  289. public $barcode_type;
  290. /**
  291. * Main Barcode type code
  292. *
  293. * @var string
  294. */
  295. public $barcode_type_code;
  296. public $stats_propale = array();
  297. public $stats_commande = array();
  298. public $stats_contrat = array();
  299. public $stats_facture = array();
  300. public $stats_commande_fournisseur = array();
  301. public $stats_reception = array();
  302. public $stats_mrptoconsume = array();
  303. public $stats_mrptoproduce = array();
  304. //! Size of image
  305. public $imgWidth;
  306. public $imgHeight;
  307. /**
  308. * @var integer|string date_creation
  309. */
  310. public $date_creation;
  311. /**
  312. * @var integer|string date_modification
  313. */
  314. public $date_modification;
  315. //! Id du fournisseur
  316. public $product_fourn_id;
  317. //! Product ID already linked to a reference supplier
  318. public $product_id_already_linked;
  319. public $nbphoto = 0;
  320. //! Contains detail of stock of product into each warehouse
  321. public $stock_warehouse = array();
  322. public $oldcopy;
  323. /**
  324. * @var int Default warehouse Id
  325. */
  326. public $fk_default_warehouse;
  327. /**
  328. * @var int ID
  329. */
  330. public $fk_price_expression;
  331. /* To store supplier price found */
  332. public $fourn_pu;
  333. public $fourn_price_base_type;
  334. public $fourn_socid;
  335. /**
  336. * @deprecated
  337. * @see $ref_supplier
  338. */
  339. public $ref_fourn;
  340. /**
  341. * @var string ref supplier
  342. */
  343. public $ref_supplier;
  344. /**
  345. * Unit code ('km', 'm', 'l', 'p', ...)
  346. *
  347. * @var string
  348. */
  349. public $fk_unit;
  350. /**
  351. * Price is generated using multiprice rules
  352. *
  353. * @var int
  354. */
  355. public $price_autogen = 0;
  356. /**
  357. * Array with list of supplier prices of product
  358. *
  359. * @var array
  360. */
  361. public $supplierprices;
  362. /**
  363. * Property set to save result of isObjectUsed(). Used for example by Product API.
  364. *
  365. * @var boolean
  366. */
  367. public $is_object_used;
  368. /**
  369. *
  370. *
  371. *
  372. */
  373. public $mandatory_period;
  374. /**
  375. * 'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  376. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  377. * 'label' the translation key.
  378. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  379. * 'position' is the sort order of field.
  380. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  381. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  382. * 'noteditable' says if field is not editable (1 or 0)
  383. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  384. * 'index' if we want an index in database.
  385. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  386. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  387. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  388. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  389. * 'help' is a string visible as a tooltip on field
  390. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  391. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  392. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  393. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  394. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  395. *
  396. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  397. */
  398. /**
  399. * @var array fields of object product
  400. */
  401. public $fields = array(
  402. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'index'=>1, 'position'=>1, 'comment'=>'Id'),
  403. 'ref' =>array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>1, 'index'=>1, 'position'=>10, 'searchall'=>1, 'comment'=>'Reference of object'),
  404. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>5),
  405. 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'showoncombobox'=>2, 'position'=>15),
  406. 'barcode' =>array('type'=>'varchar(255)', 'label'=>'Barcode', 'enabled'=>'!empty($conf->barcode->enabled)', 'position'=>20, 'visible'=>-1, 'showoncombobox'=>3),
  407. 'fk_barcode_type' => array('type'=>'integer', 'label'=>'BarcodeType', 'enabled'=>'1', 'position'=>21, 'notnull'=>0, 'visible'=>-1,),
  408. 'note_public' =>array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61),
  409. 'note' =>array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62),
  410. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
  411. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
  412. //'date_valid' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>502),
  413. 'fk_user_author'=>array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'llx_user.rowid'),
  414. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511),
  415. //'fk_user_valid' =>array('type'=>'integer', 'label'=>'UserValidation', 'enabled'=>1, 'visible'=>-1, 'position'=>512),
  416. 'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,),
  417. 'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,),
  418. 'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,),
  419. 'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,),
  420. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
  421. //'tosell' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
  422. //'tobuy' =>array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Active', -1=>'Cancel')),
  423. 'mandatory_period' =>array('type'=>'integer', 'label'=>'mandatory_period', 'enabled'=>1, 'visible'=>1, 'notnull'=>1, 'default'=>0, 'index'=>1, 'position'=>1000),
  424. );
  425. /**
  426. * Regular product
  427. */
  428. const TYPE_PRODUCT = 0;
  429. /**
  430. * Service
  431. */
  432. const TYPE_SERVICE = 1;
  433. /**
  434. * Advanced feature: assembly kit
  435. */
  436. const TYPE_ASSEMBLYKIT = 2;
  437. /**
  438. * Advanced feature: stock kit
  439. */
  440. const TYPE_STOCKKIT = 3;
  441. /**
  442. * Constructor
  443. *
  444. * @param DoliDB $db Database handler
  445. */
  446. public function __construct($db)
  447. {
  448. $this->db = $db;
  449. $this->canvas = '';
  450. }
  451. /**
  452. * Check that ref and label are ok
  453. *
  454. * @return int >1 if OK, <=0 if KO
  455. */
  456. public function check()
  457. {
  458. $this->ref = dol_sanitizeFileName(stripslashes($this->ref));
  459. $err = 0;
  460. if (dol_strlen(trim($this->ref)) == 0) {
  461. $err++;
  462. }
  463. if (dol_strlen(trim($this->label)) == 0) {
  464. $err++;
  465. }
  466. if ($err > 0) {
  467. return 0;
  468. } else {
  469. return 1;
  470. }
  471. }
  472. /**
  473. * Insert product into database
  474. *
  475. * @param User $user User making insert
  476. * @param int $notrigger Disable triggers
  477. * @return int Id of product/service if OK, < 0 if KO
  478. */
  479. public function create($user, $notrigger = 0)
  480. {
  481. global $conf, $langs;
  482. $error = 0;
  483. // Clean parameters
  484. $this->ref = dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)));
  485. $this->label = trim($this->label);
  486. $this->price_ttc = price2num($this->price_ttc);
  487. $this->price = price2num($this->price);
  488. $this->price_min_ttc = price2num($this->price_min_ttc);
  489. $this->price_min = price2num($this->price_min);
  490. if (empty($this->tva_tx)) {
  491. $this->tva_tx = 0;
  492. }
  493. if (empty($this->tva_npr)) {
  494. $this->tva_npr = 0;
  495. }
  496. //Local taxes
  497. if (empty($this->localtax1_tx)) {
  498. $this->localtax1_tx = 0;
  499. }
  500. if (empty($this->localtax2_tx)) {
  501. $this->localtax2_tx = 0;
  502. }
  503. if (empty($this->localtax1_type)) {
  504. $this->localtax1_type = '0';
  505. }
  506. if (empty($this->localtax2_type)) {
  507. $this->localtax2_type = '0';
  508. }
  509. if (empty($this->price)) {
  510. $this->price = 0;
  511. }
  512. if (empty($this->price_min)) {
  513. $this->price_min = 0;
  514. }
  515. // Price by quantity
  516. if (empty($this->price_by_qty)) {
  517. $this->price_by_qty = 0;
  518. }
  519. if (empty($this->status)) {
  520. $this->status = 0;
  521. }
  522. if (empty($this->status_buy)) {
  523. $this->status_buy = 0;
  524. }
  525. $price_ht = 0;
  526. $price_ttc = 0;
  527. $price_min_ht = 0;
  528. $price_min_ttc = 0;
  529. //
  530. if ($this->price_base_type == 'TTC' && $this->price_ttc > 0) {
  531. $price_ttc = price2num($this->price_ttc, 'MU');
  532. $price_ht = price2num($this->price_ttc / (1 + ($this->tva_tx / 100)), 'MU');
  533. }
  534. //
  535. if ($this->price_base_type != 'TTC' && $this->price > 0) {
  536. $price_ht = price2num($this->price, 'MU');
  537. $price_ttc = price2num($this->price * (1 + ($this->tva_tx / 100)), 'MU');
  538. }
  539. //
  540. if (($this->price_min_ttc > 0) && ($this->price_base_type == 'TTC')) {
  541. $price_min_ttc = price2num($this->price_min_ttc, 'MU');
  542. $price_min_ht = price2num($this->price_min_ttc / (1 + ($this->tva_tx / 100)), 'MU');
  543. }
  544. //
  545. if (($this->price_min > 0) && ($this->price_base_type != 'TTC')) {
  546. $price_min_ht = price2num($this->price_min, 'MU');
  547. $price_min_ttc = price2num($this->price_min * (1 + ($this->tva_tx / 100)), 'MU');
  548. }
  549. $this->accountancy_code_buy = trim($this->accountancy_code_buy);
  550. $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
  551. $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
  552. $this->accountancy_code_sell = trim($this->accountancy_code_sell);
  553. $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
  554. $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
  555. // Barcode value
  556. $this->barcode = trim($this->barcode);
  557. $this->mandatory_period = empty($this->mandatory_period) ? 0 : $this->mandatory_period;
  558. // Check parameters
  559. if (empty($this->label)) {
  560. $this->error = 'ErrorMandatoryParametersNotProvided';
  561. return -1;
  562. }
  563. if (empty($this->ref) || $this->ref == 'auto') {
  564. // Load object modCodeProduct
  565. $module = (!empty($conf->global->PRODUCT_CODEPRODUCT_ADDON) ? $conf->global->PRODUCT_CODEPRODUCT_ADDON : 'mod_codeproduct_leopard');
  566. if ($module != 'mod_codeproduct_leopard') { // Do not load module file for leopard
  567. if (substr($module, 0, 16) == 'mod_codeproduct_' && substr($module, -3) == 'php') {
  568. $module = substr($module, 0, dol_strlen($module) - 4);
  569. }
  570. dol_include_once('/core/modules/product/'.$module.'.php');
  571. $modCodeProduct = new $module;
  572. if (!empty($modCodeProduct->code_auto)) {
  573. $this->ref = $modCodeProduct->getNextValue($this, $this->type);
  574. }
  575. unset($modCodeProduct);
  576. }
  577. if (empty($this->ref)) {
  578. $this->error = 'ProductModuleNotSetupForAutoRef';
  579. return -2;
  580. }
  581. }
  582. dol_syslog(get_class($this)."::create ref=".$this->ref." price=".$this->price." price_ttc=".$this->price_ttc." tva_tx=".$this->tva_tx." price_base_type=".$this->price_base_type, LOG_DEBUG);
  583. $now = dol_now();
  584. $this->db->begin();
  585. // For automatic creation during create action (not used by Dolibarr GUI, can be used by scripts)
  586. if ($this->barcode == -1) {
  587. $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
  588. }
  589. // Check more parameters
  590. // If error, this->errors[] is filled
  591. $result = $this->verify();
  592. if ($result >= 0) {
  593. $sql = "SELECT count(*) as nb";
  594. $sql .= " FROM ".$this->db->prefix()."product";
  595. $sql .= " WHERE entity IN (".getEntity('product').")";
  596. $sql .= " AND ref = '".$this->db->escape($this->ref)."'";
  597. $result = $this->db->query($sql);
  598. if ($result) {
  599. $obj = $this->db->fetch_object($result);
  600. if ($obj->nb == 0) {
  601. // Produit non deja existant
  602. $sql = "INSERT INTO ".$this->db->prefix()."product (";
  603. $sql .= "datec";
  604. $sql .= ", entity";
  605. $sql .= ", ref";
  606. $sql .= ", ref_ext";
  607. $sql .= ", price_min";
  608. $sql .= ", price_min_ttc";
  609. $sql .= ", label";
  610. $sql .= ", fk_user_author";
  611. $sql .= ", fk_product_type";
  612. $sql .= ", price";
  613. $sql .= ", price_ttc";
  614. $sql .= ", price_base_type";
  615. $sql .= ", tobuy";
  616. $sql .= ", tosell";
  617. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  618. $sql .= ", accountancy_code_buy";
  619. $sql .= ", accountancy_code_buy_intra";
  620. $sql .= ", accountancy_code_buy_export";
  621. $sql .= ", accountancy_code_sell";
  622. $sql .= ", accountancy_code_sell_intra";
  623. $sql .= ", accountancy_code_sell_export";
  624. }
  625. $sql .= ", canvas";
  626. $sql .= ", finished";
  627. $sql .= ", tobatch";
  628. $sql .= ", batch_mask";
  629. $sql .= ", fk_unit";
  630. $sql .= ", mandatory_period";
  631. $sql .= ") VALUES (";
  632. $sql .= "'".$this->db->idate($now)."'";
  633. $sql .= ", ".((int) $conf->entity);
  634. $sql .= ", '".$this->db->escape($this->ref)."'";
  635. $sql .= ", ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  636. $sql .= ", ".price2num($price_min_ht);
  637. $sql .= ", ".price2num($price_min_ttc);
  638. $sql .= ", ".(!empty($this->label) ? "'".$this->db->escape($this->label)."'" : "null");
  639. $sql .= ", ".((int) $user->id);
  640. $sql .= ", ".((int) $this->type);
  641. $sql .= ", ".price2num($price_ht, 'MT');
  642. $sql .= ", ".price2num($price_ttc, 'MT');
  643. $sql .= ", '".$this->db->escape($this->price_base_type)."'";
  644. $sql .= ", ".((int) $this->status);
  645. $sql .= ", ".((int) $this->status_buy);
  646. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  647. $sql .= ", '".$this->db->escape($this->accountancy_code_buy)."'";
  648. $sql .= ", '".$this->db->escape($this->accountancy_code_buy_intra)."'";
  649. $sql .= ", '".$this->db->escape($this->accountancy_code_buy_export)."'";
  650. $sql .= ", '".$this->db->escape($this->accountancy_code_sell)."'";
  651. $sql .= ", '".$this->db->escape($this->accountancy_code_sell_intra)."'";
  652. $sql .= ", '".$this->db->escape($this->accountancy_code_sell_export)."'";
  653. }
  654. $sql .= ", '".$this->db->escape($this->canvas)."'";
  655. $sql .= ", ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? 'NULL' : (int) $this->finished);
  656. $sql .= ", ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : ((int) $this->status_batch));
  657. $sql .= ", '".$this->db->escape($this->batch_mask)."'";
  658. $sql .= ", ".($this->fk_unit > 0 ? ((int) $this->fk_unit) : 'NULL');
  659. $sql .= ", '".$this->db->escape($this->mandatory_period)."'";
  660. $sql .= ")";
  661. dol_syslog(get_class($this)."::Create", LOG_DEBUG);
  662. $result = $this->db->query($sql);
  663. if ($result) {
  664. $id = $this->db->last_insert_id($this->db->prefix()."product");
  665. if ($id > 0) {
  666. $this->id = $id;
  667. $this->price = $price_ht;
  668. $this->price_ttc = $price_ttc;
  669. $this->price_min = $price_min_ht;
  670. $this->price_min_ttc = $price_min_ttc;
  671. $result = $this->_log_price($user);
  672. if ($result > 0) {
  673. if ($this->update($id, $user, true, 'add') <= 0) {
  674. $error++;
  675. }
  676. } else {
  677. $error++;
  678. $this->error = $this->db->lasterror();
  679. }
  680. // update accountancy for this entity
  681. if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  682. $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " .((int) $this->id) . " AND entity = " . ((int) $conf->entity));
  683. $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
  684. $sql .= " fk_product";
  685. $sql .= ", entity";
  686. $sql .= ", accountancy_code_buy";
  687. $sql .= ", accountancy_code_buy_intra";
  688. $sql .= ", accountancy_code_buy_export";
  689. $sql .= ", accountancy_code_sell";
  690. $sql .= ", accountancy_code_sell_intra";
  691. $sql .= ", accountancy_code_sell_export";
  692. $sql .= ") VALUES (";
  693. $sql .= $this->id;
  694. $sql .= ", " . $conf->entity;
  695. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
  696. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
  697. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
  698. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
  699. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
  700. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
  701. $sql .= ")";
  702. $result = $this->db->query($sql);
  703. if (!$result) {
  704. $error++;
  705. $this->error = 'ErrorFailedToInsertAccountancyForEntity';
  706. }
  707. }
  708. } else {
  709. $error++;
  710. $this->error = 'ErrorFailedToGetInsertedId';
  711. }
  712. } else {
  713. $error++;
  714. $this->error = $this->db->lasterror();
  715. }
  716. } else {
  717. // Product already exists with this ref
  718. $langs->load("products");
  719. $error++;
  720. $this->error = "ErrorProductAlreadyExists";
  721. }
  722. } else {
  723. $error++;
  724. $this->error = $this->db->lasterror();
  725. }
  726. if (!$error && !$notrigger) {
  727. // Call trigger
  728. $result = $this->call_trigger('PRODUCT_CREATE', $user);
  729. if ($result < 0) {
  730. $error++;
  731. }
  732. // End call triggers
  733. }
  734. if (!$error) {
  735. $this->db->commit();
  736. return $this->id;
  737. } else {
  738. $this->db->rollback();
  739. return -$error;
  740. }
  741. } else {
  742. $this->db->rollback();
  743. dol_syslog(get_class($this)."::Create fails verify ".join(',', $this->errors), LOG_WARNING);
  744. return -3;
  745. }
  746. }
  747. /**
  748. * Check properties of product are ok (like name, barcode, ...).
  749. * All properties must be already loaded on object (this->barcode, this->barcode_type_code, ...).
  750. *
  751. * @return int 0 if OK, <0 if KO
  752. */
  753. public function verify()
  754. {
  755. global $langs;
  756. $this->errors = array();
  757. $result = 0;
  758. $this->ref = trim($this->ref);
  759. if (!$this->ref) {
  760. $this->errors[] = 'ErrorBadRef';
  761. $result = -2;
  762. }
  763. $arrayofnonnegativevalue = array('weight'=>'Weight', 'width'=>'Width', 'height'=>'Height', 'length'=>'Length', 'surface'=>'Surface', 'volume'=>'Volume');
  764. foreach ($arrayofnonnegativevalue as $key => $value) {
  765. if (property_exists($this, $key) && !empty($this->$key) && ($this->$key < 0)) {
  766. $langs->loadLangs(array("main", "other"));
  767. $this->error = $langs->trans("FieldCannotBeNegative", $langs->transnoentitiesnoconv($value));
  768. $this->errors[] = $this->error;
  769. $result = -4;
  770. }
  771. }
  772. $rescode = $this->check_barcode($this->barcode, $this->barcode_type_code);
  773. if ($rescode) {
  774. if ($rescode == -1) {
  775. $this->errors[] = 'ErrorBadBarCodeSyntax';
  776. } elseif ($rescode == -2) {
  777. $this->errors[] = 'ErrorBarCodeRequired';
  778. } elseif ($rescode == -3) {
  779. // Note: Common usage is to have barcode unique. For variants, we should have a different barcode.
  780. $this->errors[] = 'ErrorBarCodeAlreadyUsed';
  781. }
  782. $result = -3;
  783. }
  784. return $result;
  785. }
  786. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  787. /**
  788. * Check barcode
  789. *
  790. * @param string $valuetotest Value to test
  791. * @param string $typefortest Type of barcode (ISBN, EAN, ...)
  792. * @return int 0 if OK
  793. * -1 ErrorBadBarCodeSyntax
  794. * -2 ErrorBarCodeRequired
  795. * -3 ErrorBarCodeAlreadyUsed
  796. */
  797. public function check_barcode($valuetotest, $typefortest)
  798. {
  799. // phpcs:enable
  800. global $conf;
  801. if (!empty($conf->barcode->enabled) && !empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
  802. $module = strtolower($conf->global->BARCODE_PRODUCT_ADDON_NUM);
  803. $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
  804. foreach ($dirsociete as $dirroot) {
  805. $res = dol_include_once($dirroot.$module.'.php');
  806. if ($res) {
  807. break;
  808. }
  809. }
  810. $mod = new $module();
  811. dol_syslog(get_class($this)."::check_barcode value=".$valuetotest." type=".$typefortest." module=".$module);
  812. $result = $mod->verif($this->db, $valuetotest, $this, 0, $typefortest);
  813. return $result;
  814. } else {
  815. return 0;
  816. }
  817. }
  818. /**
  819. * Update a record into database.
  820. * If batch flag is set to on, we create records into llx_product_batch
  821. *
  822. * @param int $id Id of product
  823. * @param User $user Object user making update
  824. * @param int $notrigger Disable triggers
  825. * @param string $action Current action for hookmanager ('add' or 'update')
  826. * @param boolean $updatetype Update product type
  827. * @return int 1 if OK, -1 if ref already exists, -2 if other error
  828. */
  829. public function update($id, $user, $notrigger = false, $action = 'update', $updatetype = false)
  830. {
  831. global $langs, $conf, $hookmanager;
  832. $error = 0;
  833. // Check parameters
  834. if (!$this->label) {
  835. $this->label = 'MISSING LABEL';
  836. }
  837. // Clean parameters
  838. $this->ref = dol_string_nospecial(trim($this->ref));
  839. $this->label = trim($this->label);
  840. $this->description = trim($this->description);
  841. $this->note = (isset($this->note) ? trim($this->note) : null);
  842. $this->net_measure = price2num($this->net_measure);
  843. $this->net_measure_units = trim($this->net_measure_units);
  844. $this->weight = price2num($this->weight);
  845. $this->weight_units = trim($this->weight_units);
  846. $this->length = price2num($this->length);
  847. $this->length_units = trim($this->length_units);
  848. $this->width = price2num($this->width);
  849. $this->width_units = trim($this->width_units);
  850. $this->height = price2num($this->height);
  851. $this->height_units = trim($this->height_units);
  852. $this->surface = price2num($this->surface);
  853. $this->surface_units = trim($this->surface_units);
  854. $this->volume = price2num($this->volume);
  855. $this->volume_units = trim($this->volume_units);
  856. // set unit not defined
  857. if (is_numeric($this->length_units)) {
  858. $this->width_units = $this->length_units; // Not used yet
  859. }
  860. if (is_numeric($this->length_units)) {
  861. $this->height_units = $this->length_units; // Not used yet
  862. }
  863. // Automated compute surface and volume if not filled
  864. if (empty($this->surface) && !empty($this->length) && !empty($this->width) && $this->length_units == $this->width_units) {
  865. $this->surface = $this->length * $this->width;
  866. $this->surface_units = measuring_units_squared($this->length_units);
  867. }
  868. if (empty($this->volume) && !empty($this->surface) && !empty($this->height) && $this->length_units == $this->height_units) {
  869. $this->volume = $this->surface * $this->height;
  870. $this->volume_units = measuring_units_cubed($this->height_units);
  871. }
  872. if (empty($this->tva_tx)) {
  873. $this->tva_tx = 0;
  874. }
  875. if (empty($this->tva_npr)) {
  876. $this->tva_npr = 0;
  877. }
  878. if (empty($this->localtax1_tx)) {
  879. $this->localtax1_tx = 0;
  880. }
  881. if (empty($this->localtax2_tx)) {
  882. $this->localtax2_tx = 0;
  883. }
  884. if (empty($this->localtax1_type)) {
  885. $this->localtax1_type = '0';
  886. }
  887. if (empty($this->localtax2_type)) {
  888. $this->localtax2_type = '0';
  889. }
  890. if (empty($this->status)) {
  891. $this->status = 0;
  892. }
  893. if (empty($this->status_buy)) {
  894. $this->status_buy = 0;
  895. }
  896. if (empty($this->country_id)) {
  897. $this->country_id = 0;
  898. }
  899. if (empty($this->state_id)) {
  900. $this->state_id = 0;
  901. }
  902. // Barcode value
  903. $this->barcode = trim($this->barcode);
  904. $this->accountancy_code_buy = trim($this->accountancy_code_buy);
  905. $this->accountancy_code_buy_intra = trim($this->accountancy_code_buy_intra);
  906. $this->accountancy_code_buy_export = trim($this->accountancy_code_buy_export);
  907. $this->accountancy_code_sell = trim($this->accountancy_code_sell);
  908. $this->accountancy_code_sell_intra = trim($this->accountancy_code_sell_intra);
  909. $this->accountancy_code_sell_export = trim($this->accountancy_code_sell_export);
  910. $this->db->begin();
  911. $result = 0;
  912. // Check name is required and codes are ok or unique. If error, this->errors[] is filled
  913. if ($action != 'add') {
  914. $result = $this->verify(); // We don't check when update called during a create because verify was already done
  915. } else {
  916. // we can continue
  917. $result = 0;
  918. }
  919. if ($result >= 0) {
  920. if (empty($this->oldcopy)) {
  921. $org = new self($this->db);
  922. $org->fetch($this->id);
  923. $this->oldcopy = $org;
  924. }
  925. // Test if batch management is activated on existing product
  926. // If yes, we create missing entries into product_batch
  927. if ($this->hasbatch() && !$this->oldcopy->hasbatch()) {
  928. //$valueforundefinedlot = 'Undefined'; // In previous version, 39 and lower
  929. $valueforundefinedlot = '000000';
  930. if (!empty($conf->global->STOCK_DEFAULT_BATCH)) {
  931. $valueforundefinedlot = $conf->global->STOCK_DEFAULT_BATCH;
  932. }
  933. dol_syslog("Flag batch of product id=".$this->id." is set to ON, so we will create missing records into product_batch");
  934. $this->load_stock();
  935. foreach ($this->stock_warehouse as $idW => $ObjW) { // For each warehouse where we have stocks defined for this product (for each lines in product_stock)
  936. $qty_batch = 0;
  937. foreach ($ObjW->detail_batch as $detail) { // Each lines of detail in product_batch of the current $ObjW = product_stock
  938. if ($detail->batch == $valueforundefinedlot || $detail->batch == 'Undefined') {
  939. // We discard this line, we will create it later
  940. $sqlclean = "DELETE FROM ".$this->db->prefix()."product_batch WHERE batch in('Undefined', '".$this->db->escape($valueforundefinedlot)."') AND fk_product_stock = ".((int) $ObjW->id);
  941. $result = $this->db->query($sqlclean);
  942. if (!$result) {
  943. dol_print_error($this->db);
  944. exit;
  945. }
  946. continue;
  947. }
  948. $qty_batch += $detail->qty;
  949. }
  950. // Quantities in batch details are not same as stock quantity,
  951. // so we add a default batch record to complete and get same qty in parent and child table
  952. if ($ObjW->real <> $qty_batch) {
  953. $ObjBatch = new Productbatch($this->db);
  954. $ObjBatch->batch = $valueforundefinedlot;
  955. $ObjBatch->qty = ($ObjW->real - $qty_batch);
  956. $ObjBatch->fk_product_stock = $ObjW->id;
  957. if ($ObjBatch->create($user, 1) < 0) {
  958. $error++;
  959. $this->errors = $ObjBatch->errors;
  960. }
  961. }
  962. }
  963. }
  964. // For automatic creation
  965. if ($this->barcode == -1) {
  966. $this->barcode = $this->get_barcode($this, $this->barcode_type_code);
  967. }
  968. $sql = "UPDATE ".$this->db->prefix()."product";
  969. $sql .= " SET label = '".$this->db->escape($this->label)."'";
  970. if ($updatetype && ($this->isProduct() || $this->isService())) {
  971. $sql .= ", fk_product_type = ".((int) $this->type);
  972. }
  973. $sql .= ", ref = '".$this->db->escape($this->ref)."'";
  974. $sql .= ", ref_ext = ".(!empty($this->ref_ext) ? "'".$this->db->escape($this->ref_ext)."'" : "null");
  975. $sql .= ", default_vat_code = ".($this->default_vat_code ? "'".$this->db->escape($this->default_vat_code)."'" : "null");
  976. $sql .= ", tva_tx = ".((float) $this->tva_tx);
  977. $sql .= ", recuperableonly = ".((int) $this->tva_npr);
  978. $sql .= ", localtax1_tx = ".((float) $this->localtax1_tx);
  979. $sql .= ", localtax2_tx = ".((float) $this->localtax2_tx);
  980. $sql .= ", localtax1_type = ".($this->localtax1_type != '' ? "'".$this->db->escape($this->localtax1_type)."'" : "'0'");
  981. $sql .= ", localtax2_type = ".($this->localtax2_type != '' ? "'".$this->db->escape($this->localtax2_type)."'" : "'0'");
  982. $sql .= ", barcode = ".(empty($this->barcode) ? "null" : "'".$this->db->escape($this->barcode)."'");
  983. $sql .= ", fk_barcode_type = ".(empty($this->barcode_type) ? "null" : $this->db->escape($this->barcode_type));
  984. $sql .= ", tosell = ".(int) $this->status;
  985. $sql .= ", tobuy = ".(int) $this->status_buy;
  986. $sql .= ", tobatch = ".((empty($this->status_batch) || $this->status_batch < 0) ? '0' : (int) $this->status_batch);
  987. $sql .= ", batch_mask = '".$this->db->escape($this->batch_mask)."'";
  988. $sql .= ", finished = ".((!isset($this->finished) || $this->finished < 0 || $this->finished == '') ? "null" : (int) $this->finished);
  989. $sql .= ", fk_default_bom = ".((!isset($this->fk_default_bom) || $this->fk_default_bom < 0 || $this->fk_default_bom == '') ? "null" : (int) $this->fk_default_bom);
  990. $sql .= ", net_measure = ".($this->net_measure != '' ? "'".$this->db->escape($this->net_measure)."'" : 'null');
  991. $sql .= ", net_measure_units = ".($this->net_measure_units != '' ? "'".$this->db->escape($this->net_measure_units)."'" : 'null');
  992. $sql .= ", weight = ".($this->weight != '' ? "'".$this->db->escape($this->weight)."'" : 'null');
  993. $sql .= ", weight_units = ".($this->weight_units != '' ? "'".$this->db->escape($this->weight_units)."'" : 'null');
  994. $sql .= ", length = ".($this->length != '' ? "'".$this->db->escape($this->length)."'" : 'null');
  995. $sql .= ", length_units = ".($this->length_units != '' ? "'".$this->db->escape($this->length_units)."'" : 'null');
  996. $sql .= ", width= ".($this->width != '' ? "'".$this->db->escape($this->width)."'" : 'null');
  997. $sql .= ", width_units = ".($this->width_units != '' ? "'".$this->db->escape($this->width_units)."'" : 'null');
  998. $sql .= ", height = ".($this->height != '' ? "'".$this->db->escape($this->height)."'" : 'null');
  999. $sql .= ", height_units = ".($this->height_units != '' ? "'".$this->db->escape($this->height_units)."'" : 'null');
  1000. $sql .= ", surface = ".($this->surface != '' ? "'".$this->db->escape($this->surface)."'" : 'null');
  1001. $sql .= ", surface_units = ".($this->surface_units != '' ? "'".$this->db->escape($this->surface_units)."'" : 'null');
  1002. $sql .= ", volume = ".($this->volume != '' ? "'".$this->db->escape($this->volume)."'" : 'null');
  1003. $sql .= ", volume_units = ".($this->volume_units != '' ? "'".$this->db->escape($this->volume_units)."'" : 'null');
  1004. $sql .= ", fk_default_warehouse = ".($this->fk_default_warehouse > 0 ? $this->db->escape($this->fk_default_warehouse) : 'null');
  1005. $sql .= ", seuil_stock_alerte = ".((isset($this->seuil_stock_alerte) && is_numeric($this->seuil_stock_alerte)) ? (float) $this->seuil_stock_alerte : 'null');
  1006. $sql .= ", description = '".$this->db->escape($this->description)."'";
  1007. $sql .= ", url = ".($this->url ? "'".$this->db->escape($this->url)."'" : 'null');
  1008. $sql .= ", customcode = '".$this->db->escape($this->customcode)."'";
  1009. $sql .= ", fk_country = ".($this->country_id > 0 ? (int) $this->country_id : 'null');
  1010. $sql .= ", fk_state = ".($this->state_id > 0 ? (int) $this->state_id : 'null');
  1011. $sql .= ", lifetime = ".($this->lifetime > 0 ? (int) $this->lifetime : 'null');
  1012. $sql .= ", qc_frequency = ".($this->qc_frequency > 0 ? (int) $this->qc_frequency : 'null');
  1013. $sql .= ", note = ".(isset($this->note) ? "'".$this->db->escape($this->note)."'" : 'null');
  1014. $sql .= ", duration = '".$this->db->escape($this->duration_value.$this->duration_unit)."'";
  1015. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  1016. $sql .= ", accountancy_code_buy = '" . $this->db->escape($this->accountancy_code_buy) . "'";
  1017. $sql .= ", accountancy_code_buy_intra = '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
  1018. $sql .= ", accountancy_code_buy_export = '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
  1019. $sql .= ", accountancy_code_sell= '" . $this->db->escape($this->accountancy_code_sell) . "'";
  1020. $sql .= ", accountancy_code_sell_intra= '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
  1021. $sql .= ", accountancy_code_sell_export= '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
  1022. }
  1023. $sql .= ", desiredstock = ".((isset($this->desiredstock) && is_numeric($this->desiredstock)) ? (float) $this->desiredstock : "null");
  1024. $sql .= ", cost_price = ".($this->cost_price != '' ? $this->db->escape($this->cost_price) : 'null');
  1025. $sql .= ", fk_unit= ".(!$this->fk_unit ? 'NULL' : (int) $this->fk_unit);
  1026. $sql .= ", price_autogen = ".(!$this->price_autogen ? 0 : 1);
  1027. $sql .= ", fk_price_expression = ".($this->fk_price_expression != 0 ? (int) $this->fk_price_expression : 'NULL');
  1028. $sql .= ", fk_user_modif = ".($user->id > 0 ? $user->id : 'NULL');
  1029. $sql .= ", mandatory_period = ".($this->mandatory_period );
  1030. // stock field is not here because it is a denormalized value from product_stock.
  1031. $sql .= " WHERE rowid = ".((int) $id);
  1032. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  1033. $resql = $this->db->query($sql);
  1034. if ($resql) {
  1035. $this->id = $id;
  1036. // Multilangs
  1037. if (!empty($conf->global->MAIN_MULTILANGS)) {
  1038. if ($this->setMultiLangs($user) < 0) {
  1039. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1040. return -2;
  1041. }
  1042. }
  1043. $action = 'update';
  1044. // update accountancy for this entity
  1045. if (!$error && !empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  1046. $this->db->query("DELETE FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = " . ((int) $this->id) . " AND entity = " . ((int) $conf->entity));
  1047. $sql = "INSERT INTO " . $this->db->prefix() . "product_perentity (";
  1048. $sql .= " fk_product";
  1049. $sql .= ", entity";
  1050. $sql .= ", accountancy_code_buy";
  1051. $sql .= ", accountancy_code_buy_intra";
  1052. $sql .= ", accountancy_code_buy_export";
  1053. $sql .= ", accountancy_code_sell";
  1054. $sql .= ", accountancy_code_sell_intra";
  1055. $sql .= ", accountancy_code_sell_export";
  1056. $sql .= ") VALUES (";
  1057. $sql .= $this->id;
  1058. $sql .= ", " . $conf->entity;
  1059. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy) . "'";
  1060. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_intra) . "'";
  1061. $sql .= ", '" . $this->db->escape($this->accountancy_code_buy_export) . "'";
  1062. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell) . "'";
  1063. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_intra) . "'";
  1064. $sql .= ", '" . $this->db->escape($this->accountancy_code_sell_export) . "'";
  1065. $sql .= ")";
  1066. $result = $this->db->query($sql);
  1067. if (!$result) {
  1068. $error++;
  1069. $this->error = 'ErrorFailedToUpdateAccountancyForEntity';
  1070. }
  1071. }
  1072. // Actions on extra fields
  1073. if (!$error) {
  1074. $result = $this->insertExtraFields();
  1075. if ($result < 0) {
  1076. $error++;
  1077. }
  1078. }
  1079. if (!$error && !$notrigger) {
  1080. // Call trigger
  1081. $result = $this->call_trigger('PRODUCT_MODIFY', $user);
  1082. if ($result < 0) {
  1083. $error++;
  1084. }
  1085. // End call triggers
  1086. }
  1087. if (!$error && (is_object($this->oldcopy) && $this->oldcopy->ref !== $this->ref)) {
  1088. // We remove directory
  1089. if ($conf->product->dir_output) {
  1090. $olddir = $conf->product->dir_output."/".dol_sanitizeFileName($this->oldcopy->ref);
  1091. $newdir = $conf->product->dir_output."/".dol_sanitizeFileName($this->ref);
  1092. if (file_exists($olddir)) {
  1093. //include_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
  1094. //$res = dol_move($olddir, $newdir);
  1095. // do not use dol_move with directory
  1096. $res = @rename($olddir, $newdir);
  1097. if (!$res) {
  1098. $langs->load("errors");
  1099. $this->error = $langs->trans('ErrorFailToRenameDir', $olddir, $newdir);
  1100. $error++;
  1101. }
  1102. }
  1103. }
  1104. }
  1105. if (!$error) {
  1106. if (!empty($conf->variants->enabled)) {
  1107. include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  1108. $comb = new ProductCombination($this->db);
  1109. foreach ($comb->fetchAllByFkProductParent($this->id) as $currcomb) {
  1110. $currcomb->updateProperties($this, $user);
  1111. }
  1112. }
  1113. $this->db->commit();
  1114. return 1;
  1115. } else {
  1116. $this->db->rollback();
  1117. return -$error;
  1118. }
  1119. } else {
  1120. if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS') {
  1121. $langs->load("errors");
  1122. if (empty($conf->barcode->enabled) || empty($this->barcode)) {
  1123. $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductAlreadyExists", $this->ref);
  1124. } else {
  1125. $this->error = $langs->trans("Error")." : ".$langs->trans("ErrorProductBarCodeAlreadyExists", $this->barcode);
  1126. }
  1127. $this->errors[] = $this->error;
  1128. $this->db->rollback();
  1129. return -1;
  1130. } else {
  1131. $this->error = $langs->trans("Error")." : ".$this->db->error()." - ".$sql;
  1132. $this->errors[] = $this->error;
  1133. $this->db->rollback();
  1134. return -2;
  1135. }
  1136. }
  1137. } else {
  1138. $this->db->rollback();
  1139. dol_syslog(get_class($this)."::Update fails verify ".join(',', $this->errors), LOG_WARNING);
  1140. return -3;
  1141. }
  1142. }
  1143. /**
  1144. * Delete a product from database (if not used)
  1145. *
  1146. * @param User $user User (object) deleting product
  1147. * @param int $notrigger Do not execute trigger
  1148. * @return int < 0 if KO, 0 = Not possible, > 0 if OK
  1149. */
  1150. public function delete(User $user, $notrigger = 0)
  1151. {
  1152. global $conf, $langs;
  1153. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1154. $error = 0;
  1155. // Check parameters
  1156. if (empty($this->id)) {
  1157. $this->error = "Object must be fetched before calling delete";
  1158. return -1;
  1159. }
  1160. if (($this->type == Product::TYPE_PRODUCT && empty($user->rights->produit->supprimer)) || ($this->type == Product::TYPE_SERVICE && empty($user->rights->service->supprimer))) {
  1161. $this->error = "ErrorForbidden";
  1162. return 0;
  1163. }
  1164. $objectisused = $this->isObjectUsed($this->id);
  1165. if (empty($objectisused)) {
  1166. $this->db->begin();
  1167. if (!$error && empty($notrigger)) {
  1168. // Call trigger
  1169. $result = $this->call_trigger('PRODUCT_DELETE', $user);
  1170. if ($result < 0) {
  1171. $error++;
  1172. }
  1173. // End call triggers
  1174. }
  1175. // Delete from product_batch on product delete
  1176. if (!$error) {
  1177. $sql = "DELETE FROM ".$this->db->prefix().'product_batch';
  1178. $sql .= " WHERE fk_product_stock IN (";
  1179. $sql .= "SELECT rowid FROM ".$this->db->prefix().'product_stock';
  1180. $sql .= " WHERE fk_product = ".((int) $this->id).")";
  1181. $result = $this->db->query($sql);
  1182. if (!$result) {
  1183. $error++;
  1184. $this->errors[] = $this->db->lasterror();
  1185. }
  1186. }
  1187. // Delete all child tables
  1188. if (!$error) {
  1189. $elements = array('product_fournisseur_price', 'product_price', 'product_lang', 'categorie_product', 'product_stock', 'product_customer_price', 'product_lot'); // product_batch is done before
  1190. foreach ($elements as $table) {
  1191. if (!$error) {
  1192. $sql = "DELETE FROM ".$this->db->prefix().$table;
  1193. $sql .= " WHERE fk_product = ".(int) $this->id;
  1194. $result = $this->db->query($sql);
  1195. if (!$result) {
  1196. $error++;
  1197. $this->errors[] = $this->db->lasterror();
  1198. }
  1199. }
  1200. }
  1201. }
  1202. if (!$error) {
  1203. include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
  1204. include_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
  1205. //If it is a parent product, then we remove the association with child products
  1206. $prodcomb = new ProductCombination($this->db);
  1207. if ($prodcomb->deleteByFkProductParent($user, $this->id) < 0) {
  1208. $error++;
  1209. $this->errors[] = 'Error deleting combinations';
  1210. }
  1211. //We also check if it is a child product
  1212. if (!$error && ($prodcomb->fetchByFkProductChild($this->id) > 0) && ($prodcomb->delete($user) < 0)) {
  1213. $error++;
  1214. $this->errors[] = 'Error deleting child combination';
  1215. }
  1216. }
  1217. // Delete from product_association
  1218. if (!$error) {
  1219. $sql = "DELETE FROM ".$this->db->prefix()."product_association";
  1220. $sql .= " WHERE fk_product_pere = ".(int) $this->id." OR fk_product_fils = ".(int) $this->id;
  1221. $result = $this->db->query($sql);
  1222. if (!$result) {
  1223. $error++;
  1224. $this->errors[] = $this->db->lasterror();
  1225. }
  1226. }
  1227. // Remove extrafields
  1228. if (!$error) {
  1229. $result = $this->deleteExtraFields();
  1230. if ($result < 0) {
  1231. $error++;
  1232. dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
  1233. }
  1234. }
  1235. // Delete product
  1236. if (!$error) {
  1237. $sqlz = "DELETE FROM ".$this->db->prefix()."product";
  1238. $sqlz .= " WHERE rowid = ".(int) $this->id;
  1239. $resultz = $this->db->query($sqlz);
  1240. if (!$resultz) {
  1241. $error++;
  1242. $this->errors[] = $this->db->lasterror();
  1243. }
  1244. }
  1245. if (!$error) {
  1246. // We remove directory
  1247. $ref = dol_sanitizeFileName($this->ref);
  1248. if ($conf->product->dir_output) {
  1249. $dir = $conf->product->dir_output."/".$ref;
  1250. if (file_exists($dir)) {
  1251. $res = @dol_delete_dir_recursive($dir);
  1252. if (!$res) {
  1253. $this->errors[] = 'ErrorFailToDeleteDir';
  1254. $error++;
  1255. }
  1256. }
  1257. }
  1258. }
  1259. if (!$error) {
  1260. $this->db->commit();
  1261. return 1;
  1262. } else {
  1263. foreach ($this->errors as $errmsg) {
  1264. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  1265. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  1266. }
  1267. $this->db->rollback();
  1268. return -$error;
  1269. }
  1270. } else {
  1271. $this->error = "ErrorRecordIsUsedCantDelete";
  1272. return 0;
  1273. }
  1274. }
  1275. /**
  1276. * Update or add a translation for a product
  1277. *
  1278. * @param User $user Object user making update
  1279. * @return int <0 if KO, >0 if OK
  1280. */
  1281. public function setMultiLangs($user)
  1282. {
  1283. global $conf, $langs;
  1284. $langs_available = $langs->get_available_languages(DOL_DOCUMENT_ROOT, 0, 2);
  1285. $current_lang = $langs->getDefaultLang();
  1286. foreach ($langs_available as $key => $value) {
  1287. if ($key == $current_lang) {
  1288. $sql = "SELECT rowid";
  1289. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1290. $sql .= " WHERE fk_product = ".((int) $this->id);
  1291. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1292. $result = $this->db->query($sql);
  1293. if ($this->db->num_rows($result)) { // if there is already a description line for this language
  1294. $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
  1295. $sql2 .= " SET ";
  1296. $sql2 .= " label='".$this->db->escape($this->label)."',";
  1297. $sql2 .= " description='".$this->db->escape($this->description)."'";
  1298. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1299. $sql2 .= ", note='".$this->db->escape($this->other)."'";
  1300. }
  1301. $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1302. } else {
  1303. $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
  1304. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1305. $sql2 .= ", note";
  1306. }
  1307. $sql2 .= ")";
  1308. $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->label)."',";
  1309. $sql2 .= " '".$this->db->escape($this->description)."'";
  1310. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1311. $sql2 .= ", '".$this->db->escape($this->other)."'";
  1312. }
  1313. $sql2 .= ")";
  1314. }
  1315. dol_syslog(get_class($this).'::setMultiLangs key = current_lang = '.$key);
  1316. if (!$this->db->query($sql2)) {
  1317. $this->error = $this->db->lasterror();
  1318. return -1;
  1319. }
  1320. } elseif (isset($this->multilangs[$key])) {
  1321. if (empty($this->multilangs["$key"]["label"])) {
  1322. $this->error = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Label"));
  1323. return -1;
  1324. }
  1325. $sql = "SELECT rowid";
  1326. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1327. $sql .= " WHERE fk_product = ".((int) $this->id);
  1328. $sql .= " AND lang = '".$this->db->escape($key)."'";
  1329. $result = $this->db->query($sql);
  1330. if ($this->db->num_rows($result)) { // if there is already a description line for this language
  1331. $sql2 = "UPDATE ".$this->db->prefix()."product_lang";
  1332. $sql2 .= " SET ";
  1333. $sql2 .= " label = '".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1334. $sql2 .= " description = '".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1335. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1336. $sql2 .= ", note = '".$this->db->escape($this->multilangs["$key"]["other"])."'";
  1337. }
  1338. $sql2 .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($key)."'";
  1339. } else {
  1340. $sql2 = "INSERT INTO ".$this->db->prefix()."product_lang (fk_product, lang, label, description";
  1341. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1342. $sql2 .= ", note";
  1343. }
  1344. $sql2 .= ")";
  1345. $sql2 .= " VALUES(".$this->id.",'".$this->db->escape($key)."','".$this->db->escape($this->multilangs["$key"]["label"])."',";
  1346. $sql2 .= " '".$this->db->escape($this->multilangs["$key"]["description"])."'";
  1347. if (!empty($conf->global->PRODUCT_USE_OTHER_FIELD_IN_TRANSLATION)) {
  1348. $sql2 .= ", '".$this->db->escape($this->multilangs["$key"]["other"])."'";
  1349. }
  1350. $sql2 .= ")";
  1351. }
  1352. // We do not save if main fields are empty
  1353. if ($this->multilangs["$key"]["label"] || $this->multilangs["$key"]["description"]) {
  1354. if (!$this->db->query($sql2)) {
  1355. $this->error = $this->db->lasterror();
  1356. return -1;
  1357. }
  1358. }
  1359. } else {
  1360. // language is not current language and we didn't provide a multilang description for this language
  1361. }
  1362. }
  1363. // Call trigger
  1364. $result = $this->call_trigger('PRODUCT_SET_MULTILANGS', $user);
  1365. if ($result < 0) {
  1366. $this->error = $this->db->lasterror();
  1367. return -1;
  1368. }
  1369. // End call triggers
  1370. return 1;
  1371. }
  1372. /**
  1373. * Delete a language for this product
  1374. *
  1375. * @param string $langtodelete Language code to delete
  1376. * @param User $user Object user making delete
  1377. *
  1378. * @return int <0 if KO, >0 if OK
  1379. */
  1380. public function delMultiLangs($langtodelete, $user)
  1381. {
  1382. $sql = "DELETE FROM ".$this->db->prefix()."product_lang";
  1383. $sql .= " WHERE fk_product = ".((int) $this->id)." AND lang = '".$this->db->escape($langtodelete)."'";
  1384. dol_syslog(get_class($this).'::delMultiLangs', LOG_DEBUG);
  1385. $result = $this->db->query($sql);
  1386. if ($result) {
  1387. // Call trigger
  1388. $result = $this->call_trigger('PRODUCT_DEL_MULTILANGS', $user);
  1389. if ($result < 0) {
  1390. $this->error = $this->db->lasterror();
  1391. dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
  1392. return -1;
  1393. }
  1394. // End call triggers
  1395. return 1;
  1396. } else {
  1397. $this->error = $this->db->lasterror();
  1398. dol_syslog(get_class($this).'::delMultiLangs error='.$this->error, LOG_ERR);
  1399. return -1;
  1400. }
  1401. }
  1402. /**
  1403. * Sets an accountancy code for a product.
  1404. * Also calls PRODUCT_MODIFY trigger when modified
  1405. *
  1406. * @param string $type It can be 'buy', 'buy_intra', 'buy_export', 'sell', 'sell_intra' or 'sell_export'
  1407. * @param string $value Accountancy code
  1408. * @return int <0 KO >0 OK
  1409. */
  1410. public function setAccountancyCode($type, $value)
  1411. {
  1412. global $user, $langs, $conf;
  1413. $error = 0;
  1414. $this->db->begin();
  1415. if ($type == 'buy') {
  1416. $field = 'accountancy_code_buy';
  1417. } elseif ($type == 'buy_intra') {
  1418. $field = 'accountancy_code_buy_intra';
  1419. } elseif ($type == 'buy_export') {
  1420. $field = 'accountancy_code_buy_export';
  1421. } elseif ($type == 'sell') {
  1422. $field = 'accountancy_code_sell';
  1423. } elseif ($type == 'sell_intra') {
  1424. $field = 'accountancy_code_sell_intra';
  1425. } elseif ($type == 'sell_export') {
  1426. $field = 'accountancy_code_sell_export';
  1427. } else {
  1428. return -1;
  1429. }
  1430. $sql = "UPDATE ".$this->db->prefix().$this->table_element." SET ";
  1431. $sql .= "$field = '".$this->db->escape($value)."'";
  1432. $sql .= " WHERE rowid = ".((int) $this->id);
  1433. dol_syslog(__METHOD__."", LOG_DEBUG);
  1434. $resql = $this->db->query($sql);
  1435. if ($resql) {
  1436. // Call trigger
  1437. $result = $this->call_trigger('PRODUCT_MODIFY', $user);
  1438. if ($result < 0) {
  1439. $error++;
  1440. }
  1441. // End call triggers
  1442. if ($error) {
  1443. $this->db->rollback();
  1444. return -1;
  1445. }
  1446. $this->$field = $value;
  1447. $this->db->commit();
  1448. return 1;
  1449. } else {
  1450. $this->error = $this->db->lasterror();
  1451. $this->db->rollback();
  1452. return -1;
  1453. }
  1454. }
  1455. /**
  1456. * Load array this->multilangs
  1457. *
  1458. * @return int <0 if KO, >0 if OK
  1459. */
  1460. public function getMultiLangs()
  1461. {
  1462. global $langs;
  1463. $current_lang = $langs->getDefaultLang();
  1464. $sql = "SELECT lang, label, description, note as other";
  1465. $sql .= " FROM ".$this->db->prefix()."product_lang";
  1466. $sql .= " WHERE fk_product = ".((int) $this->id);
  1467. $result = $this->db->query($sql);
  1468. if ($result) {
  1469. while ($obj = $this->db->fetch_object($result)) {
  1470. //print 'lang='.$obj->lang.' current='.$current_lang.'<br>';
  1471. if ($obj->lang == $current_lang) { // si on a les traduct. dans la langue courante on les charge en infos principales.
  1472. $this->label = $obj->label;
  1473. $this->description = $obj->description;
  1474. $this->other = $obj->other;
  1475. }
  1476. $this->multilangs["$obj->lang"]["label"] = $obj->label;
  1477. $this->multilangs["$obj->lang"]["description"] = $obj->description;
  1478. $this->multilangs["$obj->lang"]["other"] = $obj->other;
  1479. }
  1480. return 1;
  1481. } else {
  1482. $this->error = "Error: ".$this->db->lasterror()." - ".$sql;
  1483. return -1;
  1484. }
  1485. }
  1486. /**
  1487. * used to check if price have really change to avoid log pollution
  1488. *
  1489. * @param int $level price level to change
  1490. * @return array
  1491. */
  1492. private function getArrayForPriceCompare($level = 0)
  1493. {
  1494. $testExit = array('multiprices','multiprices_ttc','multiprices_base_type','multiprices_min','multiprices_min_ttc','multiprices_tva_tx','multiprices_recuperableonly');
  1495. foreach ($testExit as $field) {
  1496. if (!isset($this->$field[$level])) {
  1497. return array();
  1498. }
  1499. }
  1500. $lastPrice = array(
  1501. 'level' => $level ? $level : 1,
  1502. 'multiprices' => doubleval($this->multiprices[$level]),
  1503. 'multiprices_ttc' => doubleval($this->multiprices_ttc[$level]),
  1504. 'multiprices_base_type' => $this->multiprices_base_type[$level],
  1505. 'multiprices_min' => doubleval($this->multiprices_min[$level]),
  1506. 'multiprices_min_ttc' => doubleval($this->multiprices_min_ttc[$level]),
  1507. 'multiprices_tva_tx' => doubleval($this->multiprices_tva_tx[$level]),
  1508. 'multiprices_recuperableonly' => doubleval($this->multiprices_recuperableonly[$level]),
  1509. );
  1510. return $lastPrice;
  1511. }
  1512. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1513. /**
  1514. * Insert a track that we changed a customer price
  1515. *
  1516. * @param User $user User making change
  1517. * @param int $level price level to change
  1518. * @return int <0 if KO, >0 if OK
  1519. */
  1520. private function _log_price($user, $level = 0)
  1521. {
  1522. // phpcs:enable
  1523. global $conf;
  1524. $now = dol_now();
  1525. // Clean parameters
  1526. if (empty($this->price_by_qty)) {
  1527. $this->price_by_qty = 0;
  1528. }
  1529. // Add new price
  1530. $sql = "INSERT INTO ".$this->db->prefix()."product_price(price_level,date_price, fk_product, fk_user_author, price, price_ttc, price_base_type,tosell, tva_tx, default_vat_code, recuperableonly,";
  1531. $sql .= " localtax1_tx, localtax2_tx, localtax1_type, localtax2_type, price_min,price_min_ttc,price_by_qty,entity,fk_price_expression) ";
  1532. $sql .= " VALUES(".($level ? ((int) $level) : 1).", '".$this->db->idate($now)."', ".((int) $this->id).", ".((int) $user->id).", ".((float) price2num($this->price)).", ".((float) price2num($this->price_ttc)).",'".$this->db->escape($this->price_base_type)."',".((int) $this->status).", ".((float) price2num($this->tva_tx)).", ".($this->default_vat_code ? ("'".$this->db->escape($this->default_vat_code)."'") : "null").", ".((int) $this->tva_npr).",";
  1533. $sql .= " ".price2num($this->localtax1_tx).", ".price2num($this->localtax2_tx).", '".$this->db->escape($this->localtax1_type)."', '".$this->db->escape($this->localtax2_type)."', ".price2num($this->price_min).", ".price2num($this->price_min_ttc).", ".price2num($this->price_by_qty).", ".((int) $conf->entity).",".($this->fk_price_expression > 0 ? ((int) $this->fk_price_expression) : 'null');
  1534. $sql .= ")";
  1535. dol_syslog(get_class($this)."::_log_price", LOG_DEBUG);
  1536. $resql = $this->db->query($sql);
  1537. if (!$resql) {
  1538. $this->error = $this->db->lasterror();
  1539. dol_print_error($this->db);
  1540. return -1;
  1541. } else {
  1542. return 1;
  1543. }
  1544. }
  1545. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1546. /**
  1547. * Delete a price line
  1548. *
  1549. * @param User $user Object user
  1550. * @param int $rowid Line id to delete
  1551. * @return int <0 if KO, >0 if OK
  1552. */
  1553. public function log_price_delete($user, $rowid)
  1554. {
  1555. // phpcs:enable
  1556. $sql = "DELETE FROM ".$this->db->prefix()."product_price_by_qty";
  1557. $sql .= " WHERE fk_product_price = ".((int) $rowid);
  1558. $resql = $this->db->query($sql);
  1559. $sql = "DELETE FROM ".$this->db->prefix()."product_price";
  1560. $sql .= " WHERE rowid=".((int) $rowid);
  1561. $resql = $this->db->query($sql);
  1562. if ($resql) {
  1563. return 1;
  1564. } else {
  1565. $this->error = $this->db->lasterror();
  1566. return -1;
  1567. }
  1568. }
  1569. /**
  1570. * Return price of sell of a product for a seller/buyer/product.
  1571. *
  1572. * @param Societe $thirdparty_seller Seller
  1573. * @param Societe $thirdparty_buyer Buyer
  1574. * @param int $pqp Id of product price per quantity if a selection was done of such a price
  1575. * @return array Array of price information array('pu_ht'=> , 'pu_ttc'=> , 'tva_tx'=>'X.Y (code)', ...), 'tva_npr'=>0, ...)
  1576. * @see get_buyprice(), find_min_price_product_fournisseur()
  1577. */
  1578. public function getSellPrice($thirdparty_seller, $thirdparty_buyer, $pqp = 0)
  1579. {
  1580. global $conf, $db;
  1581. // Update if prices fields are defined
  1582. $tva_tx = get_default_tva($thirdparty_seller, $thirdparty_buyer, $this->id);
  1583. $tva_npr = get_default_npr($thirdparty_seller, $thirdparty_buyer, $this->id);
  1584. if (empty($tva_tx)) {
  1585. $tva_npr = 0;
  1586. }
  1587. $pu_ht = $this->price;
  1588. $pu_ttc = $this->price_ttc;
  1589. $price_min = $this->price_min;
  1590. $price_base_type = $this->price_base_type;
  1591. // If price per segment
  1592. if (!empty($conf->global->PRODUIT_MULTIPRICES) && !empty($thirdparty_buyer->price_level)) {
  1593. $pu_ht = $this->multiprices[$thirdparty_buyer->price_level];
  1594. $pu_ttc = $this->multiprices_ttc[$thirdparty_buyer->price_level];
  1595. $price_min = $this->multiprices_min[$thirdparty_buyer->price_level];
  1596. $price_base_type = $this->multiprices_base_type[$thirdparty_buyer->price_level];
  1597. if (!empty($conf->global->PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL)) { // using this option is a bug. kept for backward compatibility
  1598. if (isset($this->multiprices_tva_tx[$thirdparty_buyer->price_level])) {
  1599. $tva_tx = $this->multiprices_tva_tx[$thirdparty_buyer->price_level];
  1600. }
  1601. if (isset($this->multiprices_recuperableonly[$thirdparty_buyer->price_level])) {
  1602. $tva_npr = $this->multiprices_recuperableonly[$thirdparty_buyer->price_level];
  1603. }
  1604. if (empty($tva_tx)) {
  1605. $tva_npr = 0;
  1606. }
  1607. }
  1608. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES)) {
  1609. // If price per customer
  1610. require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
  1611. $prodcustprice = new Productcustomerprice($this->db);
  1612. $filter = array('t.fk_product' => $this->id, 't.fk_soc' => $thirdparty_buyer->id);
  1613. $result = $prodcustprice->fetch_all('', '', 0, 0, $filter);
  1614. if ($result) {
  1615. if (count($prodcustprice->lines) > 0) {
  1616. $pu_ht = price($prodcustprice->lines[0]->price);
  1617. $price_min = price($prodcustprice->lines[0]->price_min);
  1618. $pu_ttc = price($prodcustprice->lines[0]->price_ttc);
  1619. $price_base_type = $prodcustprice->lines[0]->price_base_type;
  1620. $tva_tx = $prodcustprice->lines[0]->tva_tx;
  1621. if ($prodcustprice->lines[0]->default_vat_code && !preg_match('/\(.*\)/', $tva_tx)) {
  1622. $tva_tx .= ' ('.$prodcustprice->lines[0]->default_vat_code.')';
  1623. }
  1624. $tva_npr = $prodcustprice->lines[0]->recuperableonly;
  1625. if (empty($tva_tx)) {
  1626. $tva_npr = 0;
  1627. }
  1628. }
  1629. }
  1630. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY)) {
  1631. // If price per quantity
  1632. if ($this->prices_by_qty[0]) {
  1633. // yes, this product has some prices per quantity
  1634. // Search price into product_price_by_qty from $this->id
  1635. foreach ($this->prices_by_qty_list[0] as $priceforthequantityarray) {
  1636. if ($priceforthequantityarray['rowid'] != $pqp) {
  1637. continue;
  1638. }
  1639. // We found the price
  1640. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  1641. $pu_ht = $priceforthequantityarray['unitprice'];
  1642. } else {
  1643. $pu_ttc = $priceforthequantityarray['unitprice'];
  1644. }
  1645. break;
  1646. }
  1647. }
  1648. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) {
  1649. // If price per quantity and customer
  1650. if ($this->prices_by_qty[$thirdparty_buyer->price_level]) {
  1651. // yes, this product has some prices per quantity
  1652. // Search price into product_price_by_qty from $this->id
  1653. foreach ($this->prices_by_qty_list[$thirdparty_buyer->price_level] as $priceforthequantityarray) {
  1654. if ($priceforthequantityarray['rowid'] != $pqp) {
  1655. continue;
  1656. }
  1657. // We found the price
  1658. if ($priceforthequantityarray['price_base_type'] == 'HT') {
  1659. $pu_ht = $priceforthequantityarray['unitprice'];
  1660. } else {
  1661. $pu_ttc = $priceforthequantityarray['unitprice'];
  1662. }
  1663. break;
  1664. }
  1665. }
  1666. }
  1667. return array('pu_ht'=>$pu_ht, 'pu_ttc'=>$pu_ttc, 'price_min'=>$price_min, 'price_base_type'=>$price_base_type, 'tva_tx'=>$tva_tx, 'tva_npr'=>$tva_npr);
  1668. }
  1669. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1670. /**
  1671. * Read price used by a provider.
  1672. * We enter as input couple prodfournprice/qty or triplet qty/product_id/fourn_ref.
  1673. * This also set some properties on product like ->buyprice, ->fourn_pu, ...
  1674. *
  1675. * @param int $prodfournprice Id du tarif = rowid table product_fournisseur_price
  1676. * @param double $qty Quantity asked or -1 to get first entry found
  1677. * @param int $product_id Filter on a particular product id
  1678. * @param string $fourn_ref Filter on a supplier price ref. 'none' to exclude ref in search.
  1679. * @param int $fk_soc If of supplier
  1680. * @return int <-1 if KO, -1 if qty not enough, 0 if OK but nothing found, id_product if OK and found. May also initialize some properties like (->ref_supplier, buyprice, fourn_pu, vatrate_supplier...)
  1681. * @see getSellPrice(), find_min_price_product_fournisseur()
  1682. */
  1683. public function get_buyprice($prodfournprice, $qty, $product_id = 0, $fourn_ref = '', $fk_soc = 0)
  1684. {
  1685. // phpcs:enable
  1686. global $conf;
  1687. $result = 0;
  1688. // We do a first seach with a select by searching with couple prodfournprice and qty only (later we will search on triplet qty/product_id/fourn_ref)
  1689. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent,";
  1690. $sql .= " pfp.fk_product, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_soc, pfp.tva_tx, pfp.fk_supplier_price_expression,";
  1691. $sql .= " pfp.default_vat_code,";
  1692. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
  1693. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1694. $sql .= ", pfp.packaging";
  1695. }
  1696. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
  1697. $sql .= " WHERE pfp.rowid = ".((int) $prodfournprice);
  1698. if ($qty > 0) {
  1699. $sql .= " AND pfp.quantity <= ".((float) $qty);
  1700. }
  1701. $sql .= " ORDER BY pfp.quantity DESC";
  1702. dol_syslog(get_class($this)."::get_buyprice first search by prodfournprice/qty", LOG_DEBUG);
  1703. $resql = $this->db->query($sql);
  1704. if ($resql) {
  1705. $obj = $this->db->fetch_object($resql);
  1706. if ($obj && $obj->quantity > 0) { // If we found a supplier prices from the id of supplier price
  1707. if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
  1708. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1709. $prod_supplier = new ProductFournisseur($this->db);
  1710. $prod_supplier->product_fourn_price_id = $obj->rowid;
  1711. $prod_supplier->id = $obj->fk_product;
  1712. $prod_supplier->fourn_qty = $obj->quantity;
  1713. $prod_supplier->fourn_tva_tx = $obj->tva_tx;
  1714. $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  1715. $priceparser = new PriceParser($this->db);
  1716. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  1717. if ($price_result >= 0) {
  1718. $obj->price = $price_result;
  1719. }
  1720. }
  1721. $this->product_fourn_price_id = $obj->rowid;
  1722. $this->buyprice = $obj->price; // deprecated
  1723. $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product of supplier
  1724. $this->fourn_price_base_type = 'HT'; // Price base type
  1725. $this->fourn_socid = $obj->fk_soc; // Company that offer this price
  1726. $this->ref_fourn = $obj->ref_fourn; // deprecated
  1727. $this->ref_supplier = $obj->ref_fourn; // Ref supplier
  1728. $this->desc_supplier = $obj->desc_fourn; // desc supplier
  1729. $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
  1730. $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
  1731. $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
  1732. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  1733. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  1734. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  1735. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  1736. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  1737. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1738. $this->packaging = $obj->packaging;
  1739. }
  1740. $result = $obj->fk_product;
  1741. return $result;
  1742. } else { // If not found
  1743. // We do a second search by doing a select again but searching with less reliable criteria: couple qty/id product, and if set fourn_ref or fk_soc.
  1744. $sql = "SELECT pfp.rowid, pfp.price as price, pfp.quantity as quantity, pfp.remise_percent, pfp.fk_soc,";
  1745. $sql .= " pfp.fk_product, pfp.ref_fourn as ref_supplier, pfp.desc_fourn as desc_supplier, pfp.tva_tx, pfp.fk_supplier_price_expression,";
  1746. $sql .= " pfp.default_vat_code,";
  1747. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
  1748. $sql .= " pfp.packaging";
  1749. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as pfp";
  1750. $sql .= " WHERE pfp.fk_product = ".((int) $product_id);
  1751. if ($fourn_ref != 'none') {
  1752. $sql .= " AND pfp.ref_fourn = '".$this->db->escape($fourn_ref)."'";
  1753. }
  1754. if ($fk_soc > 0) {
  1755. $sql .= " AND pfp.fk_soc = ".((int) $fk_soc);
  1756. }
  1757. if ($qty > 0) {
  1758. $sql .= " AND pfp.quantity <= ".((float) $qty);
  1759. }
  1760. $sql .= " ORDER BY pfp.quantity DESC";
  1761. $sql .= " LIMIT 1";
  1762. dol_syslog(get_class($this)."::get_buyprice second search from qty/ref/product_id", LOG_DEBUG);
  1763. $resql = $this->db->query($sql);
  1764. if ($resql) {
  1765. $obj = $this->db->fetch_object($resql);
  1766. if ($obj && $obj->quantity > 0) { // If found
  1767. if (!empty($conf->dynamicprices->enabled) && !empty($obj->fk_supplier_price_expression)) {
  1768. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  1769. $prod_supplier = new ProductFournisseur($this->db);
  1770. $prod_supplier->product_fourn_price_id = $obj->rowid;
  1771. $prod_supplier->id = $obj->fk_product;
  1772. $prod_supplier->fourn_qty = $obj->quantity;
  1773. $prod_supplier->fourn_tva_tx = $obj->tva_tx;
  1774. $prod_supplier->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  1775. $priceparser = new PriceParser($this->db);
  1776. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  1777. if ($result >= 0) {
  1778. $obj->price = $price_result;
  1779. }
  1780. }
  1781. $this->product_fourn_price_id = $obj->rowid;
  1782. $this->buyprice = $obj->price; // deprecated
  1783. $this->fourn_qty = $obj->quantity; // min quantity for price for a virtual supplier
  1784. $this->fourn_pu = $obj->price / $obj->quantity; // Unit price of product for a virtual supplier
  1785. $this->fourn_price_base_type = 'HT'; // Price base type for a virtual supplier
  1786. $this->fourn_socid = $obj->fk_soc; // Company that offer this price
  1787. $this->ref_fourn = $obj->ref_supplier; // deprecated
  1788. $this->ref_supplier = $obj->ref_supplier; // Ref supplier
  1789. $this->desc_supplier = $obj->desc_supplier; // desc supplier
  1790. $this->remise_percent = $obj->remise_percent; // remise percent if present and not typed
  1791. $this->vatrate_supplier = $obj->tva_tx; // Vat ref supplier
  1792. $this->default_vat_code = $obj->default_vat_code; // Vat code supplier
  1793. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  1794. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  1795. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  1796. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  1797. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  1798. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  1799. $this->packaging = $obj->packaging;
  1800. }
  1801. $result = $obj->fk_product;
  1802. return $result;
  1803. } else {
  1804. return -1; // Ce produit n'existe pas avec cet id tarif fournisseur ou existe mais qte insuffisante, ni pour le couple produit/ref fournisseur dans la quantité.
  1805. }
  1806. } else {
  1807. $this->error = $this->db->lasterror();
  1808. return -3;
  1809. }
  1810. }
  1811. } else {
  1812. $this->error = $this->db->lasterror();
  1813. return -2;
  1814. }
  1815. }
  1816. /**
  1817. * Modify customer price of a product/Service
  1818. *
  1819. * @param double $newprice New price
  1820. * @param string $newpricebase HT or TTC
  1821. * @param User $user Object user that make change
  1822. * @param double $newvat New VAT Rate (For example 8.5. Should not be a string)
  1823. * @param double $newminprice New price min
  1824. * @param int $level 0=standard, >0 = level if multilevel prices
  1825. * @param int $newnpr 0=Standard vat rate, 1=Special vat rate for French NPR VAT
  1826. * @param int $newpbq 1 if it has price by quantity
  1827. * @param int $ignore_autogen Used to avoid infinite loops
  1828. * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
  1829. * @param string $newdefaultvatcode Default vat code
  1830. * @return int <0 if KO, >0 if OK
  1831. */
  1832. public function updatePrice($newprice, $newpricebase, $user, $newvat = '', $newminprice = 0, $level = 0, $newnpr = 0, $newpbq = 0, $ignore_autogen = 0, $localtaxes_array = array(), $newdefaultvatcode = '')
  1833. {
  1834. global $conf, $langs;
  1835. $lastPriceData = $this->getArrayForPriceCompare($level); // temporary store current price before update
  1836. $id = $this->id;
  1837. dol_syslog(get_class($this)."::update_price id=".$id." newprice=".$newprice." newpricebase=".$newpricebase." newminprice=".$newminprice." level=".$level." npr=".$newnpr." newdefaultvatcode=".$newdefaultvatcode);
  1838. // Clean parameters
  1839. if (empty($this->tva_tx)) {
  1840. $this->tva_tx = 0;
  1841. }
  1842. if (empty($newnpr)) {
  1843. $newnpr = 0;
  1844. }
  1845. if (empty($newminprice)) {
  1846. $newminprice = 0;
  1847. }
  1848. if (empty($newminprice)) {
  1849. $newminprice = 0;
  1850. }
  1851. // Check parameters
  1852. if ($newvat == '') {
  1853. $newvat = $this->tva_tx;
  1854. }
  1855. // If multiprices are enabled, then we check if the current product is subject to price autogeneration
  1856. // Price will be modified ONLY when the first one is the one that is being modified
  1857. if ((!empty($conf->global->PRODUIT_MULTIPRICES) || !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES)) && !$ignore_autogen && $this->price_autogen && ($level == 1)) {
  1858. return $this->generateMultiprices($user, $newprice, $newpricebase, $newvat, $newnpr, $newpbq);
  1859. }
  1860. if (!empty($newminprice) && ($newminprice > $newprice)) {
  1861. $this->error = 'ErrorPriceCantBeLowerThanMinPrice';
  1862. return -1;
  1863. }
  1864. if ($newprice !== '' || $newprice === 0) {
  1865. if ($newpricebase == 'TTC') {
  1866. $price_ttc = price2num($newprice, 'MU');
  1867. $price = price2num($newprice) / (1 + ($newvat / 100));
  1868. $price = price2num($price, 'MU');
  1869. if ($newminprice != '' || $newminprice == 0) {
  1870. $price_min_ttc = price2num($newminprice, 'MU');
  1871. $price_min = price2num($newminprice) / (1 + ($newvat / 100));
  1872. $price_min = price2num($price_min, 'MU');
  1873. } else {
  1874. $price_min = 0;
  1875. $price_min_ttc = 0;
  1876. }
  1877. } else {
  1878. $price = price2num($newprice, 'MU');
  1879. $price_ttc = ($newnpr != 1) ? price2num($newprice) * (1 + ($newvat / 100)) : $price;
  1880. $price_ttc = price2num($price_ttc, 'MU');
  1881. if ($newminprice !== '' || $newminprice === 0) {
  1882. $price_min = price2num($newminprice, 'MU');
  1883. $price_min_ttc = price2num($newminprice) * (1 + ($newvat / 100));
  1884. $price_min_ttc = price2num($price_min_ttc, 'MU');
  1885. //print 'X'.$newminprice.'-'.$price_min;
  1886. } else {
  1887. $price_min = 0;
  1888. $price_min_ttc = 0;
  1889. }
  1890. }
  1891. //print 'x'.$id.'-'.$newprice.'-'.$newpricebase.'-'.$price.'-'.$price_ttc.'-'.$price_min.'-'.$price_min_ttc;
  1892. if (count($localtaxes_array) > 0) {
  1893. $localtaxtype1 = $localtaxes_array['0'];
  1894. $localtax1 = $localtaxes_array['1'];
  1895. $localtaxtype2 = $localtaxes_array['2'];
  1896. $localtax2 = $localtaxes_array['3'];
  1897. } else // old method. deprecated because ot can't retrieve type
  1898. {
  1899. $localtaxtype1 = '0';
  1900. $localtax1 = get_localtax($newvat, 1);
  1901. $localtaxtype2 = '0';
  1902. $localtax2 = get_localtax($newvat, 2);
  1903. }
  1904. if (empty($localtax1)) {
  1905. $localtax1 = 0; // If = '' then = 0
  1906. }
  1907. if (empty($localtax2)) {
  1908. $localtax2 = 0; // If = '' then = 0
  1909. }
  1910. $this->db->begin();
  1911. // Ne pas mettre de quote sur les numeriques decimaux.
  1912. // Ceci provoque des stockages avec arrondis en base au lieu des valeurs exactes.
  1913. $sql = "UPDATE ".$this->db->prefix()."product SET";
  1914. $sql .= " price_base_type='".$this->db->escape($newpricebase)."',";
  1915. $sql .= " price=".$price.",";
  1916. $sql .= " price_ttc=".$price_ttc.",";
  1917. $sql .= " price_min=".$price_min.",";
  1918. $sql .= " price_min_ttc=".$price_min_ttc.",";
  1919. $sql .= " localtax1_tx=".($localtax1 >= 0 ? $localtax1 : 'NULL').",";
  1920. $sql .= " localtax2_tx=".($localtax2 >= 0 ? $localtax2 : 'NULL').",";
  1921. $sql .= " localtax1_type=".($localtaxtype1 != '' ? "'".$this->db->escape($localtaxtype1)."'" : "'0'").",";
  1922. $sql .= " localtax2_type=".($localtaxtype2 != '' ? "'".$this->db->escape($localtaxtype2)."'" : "'0'").",";
  1923. $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
  1924. $sql .= " tva_tx='".price2num($newvat)."',";
  1925. $sql .= " recuperableonly='".$this->db->escape($newnpr)."'";
  1926. $sql .= " WHERE rowid = ".((int) $id);
  1927. dol_syslog(get_class($this)."::update_price", LOG_DEBUG);
  1928. $resql = $this->db->query($sql);
  1929. if ($resql) {
  1930. $this->multiprices[$level] = $price;
  1931. $this->multiprices_ttc[$level] = $price_ttc;
  1932. $this->multiprices_min[$level] = $price_min;
  1933. $this->multiprices_min_ttc[$level] = $price_min_ttc;
  1934. $this->multiprices_base_type[$level] = $newpricebase;
  1935. $this->multiprices_default_vat_code[$level] = $newdefaultvatcode;
  1936. $this->multiprices_tva_tx[$level] = $newvat;
  1937. $this->multiprices_recuperableonly[$level] = $newnpr;
  1938. $this->price = $price;
  1939. $this->price_ttc = $price_ttc;
  1940. $this->price_min = $price_min;
  1941. $this->price_min_ttc = $price_min_ttc;
  1942. $this->price_base_type = $newpricebase;
  1943. $this->default_vat_code = $newdefaultvatcode;
  1944. $this->tva_tx = $newvat;
  1945. $this->tva_npr = $newnpr;
  1946. //Local taxes
  1947. $this->localtax1_tx = $localtax1;
  1948. $this->localtax2_tx = $localtax2;
  1949. $this->localtax1_type = $localtaxtype1;
  1950. $this->localtax2_type = $localtaxtype2;
  1951. // Price by quantity
  1952. $this->price_by_qty = $newpbq;
  1953. // check if price have really change before log
  1954. $newPriceData = $this->getArrayForPriceCompare($level);
  1955. if (!empty(array_diff_assoc($newPriceData, $lastPriceData)) || empty($conf->global->PRODUIT_MULTIPRICES)) {
  1956. $this->_log_price($user, $level); // Save price for level into table product_price
  1957. }
  1958. $this->level = $level; // Store level of price edited for trigger
  1959. // Call trigger
  1960. $result = $this->call_trigger('PRODUCT_PRICE_MODIFY', $user);
  1961. if ($result < 0) {
  1962. $this->db->rollback();
  1963. return -1;
  1964. }
  1965. // End call triggers
  1966. $this->db->commit();
  1967. } else {
  1968. $this->db->rollback();
  1969. dol_print_error($this->db);
  1970. }
  1971. }
  1972. return 1;
  1973. }
  1974. /**
  1975. * Sets the supplier price expression
  1976. *
  1977. * @param int $expression_id Expression
  1978. * @return int <0 if KO, >0 if OK
  1979. * @deprecated Use Product::update instead
  1980. */
  1981. public function setPriceExpression($expression_id)
  1982. {
  1983. global $user;
  1984. $this->fk_price_expression = $expression_id;
  1985. return $this->update($this->id, $user);
  1986. }
  1987. /**
  1988. * Load a product in memory from database
  1989. *
  1990. * @param int $id Id of product/service to load
  1991. * @param string $ref Ref of product/service to load
  1992. * @param string $ref_ext Ref ext of product/service to load
  1993. * @param string $barcode Barcode of product/service to load
  1994. * @param int $ignore_expression When module dynamicprices is on, ignores the math expression for calculating price and uses the db value instead
  1995. * @param int $ignore_price_load Load product without loading $this->multiprices... array (when we are sure we don't need them)
  1996. * @param int $ignore_lang_load Load product without loading $this->multilangs language arrays (when we are sure we don't need them)
  1997. * @return int <0 if KO, 0 if not found, >0 if OK
  1998. */
  1999. public function fetch($id = '', $ref = '', $ref_ext = '', $barcode = '', $ignore_expression = 0, $ignore_price_load = 0, $ignore_lang_load = 0)
  2000. {
  2001. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  2002. global $langs, $conf;
  2003. dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref." ref_ext=".$ref_ext);
  2004. // Check parameters
  2005. if (!$id && !$ref && !$ref_ext && !$barcode) {
  2006. $this->error = 'ErrorWrongParameters';
  2007. dol_syslog(get_class($this)."::fetch ".$this->error, LOG_ERR);
  2008. return -1;
  2009. }
  2010. $sql = "SELECT p.rowid, p.ref, p.ref_ext, p.label, p.description, p.url, p.note_public, p.note as note_private, p.customcode, p.fk_country, p.fk_state, p.lifetime, p.qc_frequency, p.price, p.price_ttc,";
  2011. $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly as tva_npr, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
  2012. $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
  2013. $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
  2014. $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished, p.fk_default_bom, p.mandatory_period,";
  2015. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  2016. $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
  2017. } else {
  2018. $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
  2019. }
  2020. //For MultiCompany
  2021. //PMP per entity & Stocks Sharings stock_reel includes only stocks shared with this entity
  2022. $separatedEntityPMP = false; // Set to true to get the AWP from table llx_product_perentity instead of field 'pmp' into llx_product.
  2023. $separatedStock = false; // Set to true will count stock from subtable llx_product_stock. It is slower than using denormalized field 'stock', but it is required when using multientity and shared warehouses.
  2024. if (!empty($conf->global->MULTICOMPANY_PRODUCT_SHARING_ENABLED)) {
  2025. if (!empty($conf->global->MULTICOMPANY_PMP_PER_ENTITY_ENABLED)) {
  2026. $checkPMPPerEntity = $this->db->query("SELECT pmp FROM " . $this->db->prefix() . "product_perentity WHERE fk_product = ".((int) $id)." AND entity = ".(int) $conf->entity);
  2027. if ($this->db->num_rows($checkPMPPerEntity)>0) {
  2028. $separatedEntityPMP = true;
  2029. }
  2030. }
  2031. global $mc;
  2032. $separatedStock = true;
  2033. $visibleWarehousesEntities = $conf->entity;
  2034. if (isset($mc->sharings['stock']) && !empty($mc->sharings['stock'])) {
  2035. $visibleWarehousesEntities .= "," . implode(",", $mc->sharings['stock']);
  2036. }
  2037. }
  2038. if ($separatedEntityPMP) {
  2039. $sql .= " ppe.pmp,";
  2040. } else {
  2041. $sql .= " p.pmp,";
  2042. }
  2043. $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
  2044. $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf,";
  2045. if ($separatedStock) {
  2046. $sql .= " SUM(sp.reel) as stock";
  2047. } else {
  2048. $sql .= " p.stock";
  2049. }
  2050. $sql .= " FROM ".$this->db->prefix()."product as p";
  2051. if (!empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED) || $separatedEntityPMP) {
  2052. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_perentity as ppe ON ppe.fk_product = p.rowid AND ppe.entity = " . ((int) $conf->entity);
  2053. }
  2054. if ($separatedStock) {
  2055. $sql .= " LEFT JOIN " . $this->db->prefix() . "product_stock as sp ON sp.fk_product = p.rowid AND sp.fk_entrepot IN (SELECT rowid FROM ".$this->db->prefix()."entrepot WHERE entity IN (".$this->db->sanitize($visibleWarehousesEntities)."))";
  2056. }
  2057. if ($id) {
  2058. $sql .= " WHERE p.rowid = ".((int) $id);
  2059. } else {
  2060. $sql .= " WHERE p.entity IN (".getEntity($this->element).")";
  2061. if ($ref) {
  2062. $sql .= " AND p.ref = '".$this->db->escape($ref)."'";
  2063. } elseif ($ref_ext) {
  2064. $sql .= " AND p.ref_ext = '".$this->db->escape($ref_ext)."'";
  2065. } elseif ($barcode) {
  2066. $sql .= " AND p.barcode = '".$this->db->escape($barcode)."'";
  2067. }
  2068. }
  2069. if ($separatedStock) {
  2070. $sql .= " GROUP BY p.rowid, p.ref, p.ref_ext, p.label, p.description, p.url, p.note_public, p.note, p.customcode, p.fk_country, p.fk_state, p.lifetime, p.qc_frequency, p.price, p.price_ttc,";
  2071. $sql .= " p.price_min, p.price_min_ttc, p.price_base_type, p.cost_price, p.default_vat_code, p.tva_tx, p.recuperableonly, p.localtax1_tx, p.localtax2_tx, p.localtax1_type, p.localtax2_type, p.tosell,";
  2072. $sql .= " p.tobuy, p.fk_product_type, p.duration, p.fk_default_warehouse, p.seuil_stock_alerte, p.canvas, p.net_measure, p.net_measure_units, p.weight, p.weight_units,";
  2073. $sql .= " p.length, p.length_units, p.width, p.width_units, p.height, p.height_units,";
  2074. $sql .= " p.surface, p.surface_units, p.volume, p.volume_units, p.barcode, p.fk_barcode_type, p.finished,";
  2075. if (empty($conf->global->MAIN_PRODUCT_PERENTITY_SHARED)) {
  2076. $sql .= " p.accountancy_code_buy, p.accountancy_code_buy_intra, p.accountancy_code_buy_export, p.accountancy_code_sell, p.accountancy_code_sell_intra, p.accountancy_code_sell_export,";
  2077. } else {
  2078. $sql .= " ppe.accountancy_code_buy, ppe.accountancy_code_buy_intra, ppe.accountancy_code_buy_export, ppe.accountancy_code_sell, ppe.accountancy_code_sell_intra, ppe.accountancy_code_sell_export,";
  2079. }
  2080. if ($separatedEntityPMP) {
  2081. $sql .= " ppe.pmp,";
  2082. } else {
  2083. $sql .= " p.pmp,";
  2084. }
  2085. $sql .= " p.datec, p.tms, p.import_key, p.entity, p.desiredstock, p.tobatch, p.batch_mask, p.fk_unit,";
  2086. $sql .= " p.fk_price_expression, p.price_autogen, p.model_pdf";
  2087. if (!$separatedStock) {
  2088. $sql .= ", p.stock";
  2089. }
  2090. }
  2091. $resql = $this->db->query($sql);
  2092. if ($resql) {
  2093. unset($this->oldcopy);
  2094. if ($this->db->num_rows($resql) > 0) {
  2095. $obj = $this->db->fetch_object($resql);
  2096. $this->id = $obj->rowid;
  2097. $this->ref = $obj->ref;
  2098. $this->ref_ext = $obj->ref_ext;
  2099. $this->label = $obj->label;
  2100. $this->description = $obj->description;
  2101. $this->url = $obj->url;
  2102. $this->note_public = $obj->note_public;
  2103. $this->note_private = $obj->note_private;
  2104. $this->note = $obj->note_private; // deprecated
  2105. $this->type = $obj->fk_product_type;
  2106. $this->status = $obj->tosell;
  2107. $this->status_buy = $obj->tobuy;
  2108. $this->status_batch = $obj->tobatch;
  2109. $this->batch_mask = $obj->batch_mask;
  2110. $this->customcode = $obj->customcode;
  2111. $this->country_id = $obj->fk_country;
  2112. $this->country_code = getCountry($this->country_id, 2, $this->db);
  2113. $this->state_id = $obj->fk_state;
  2114. $this->lifetime = $obj->lifetime;
  2115. $this->qc_frequency = $obj->qc_frequency;
  2116. $this->price = $obj->price;
  2117. $this->price_ttc = $obj->price_ttc;
  2118. $this->price_min = $obj->price_min;
  2119. $this->price_min_ttc = $obj->price_min_ttc;
  2120. $this->price_base_type = $obj->price_base_type;
  2121. $this->cost_price = $obj->cost_price;
  2122. $this->default_vat_code = $obj->default_vat_code;
  2123. $this->tva_tx = $obj->tva_tx;
  2124. //! French VAT NPR
  2125. $this->tva_npr = $obj->tva_npr;
  2126. $this->recuperableonly = $obj->tva_npr; // For backward compatibility
  2127. //! Local taxes
  2128. $this->localtax1_tx = $obj->localtax1_tx;
  2129. $this->localtax2_tx = $obj->localtax2_tx;
  2130. $this->localtax1_type = $obj->localtax1_type;
  2131. $this->localtax2_type = $obj->localtax2_type;
  2132. $this->finished = $obj->finished;
  2133. $this->fk_default_bom = $obj->fk_default_bom;
  2134. $this->duration = $obj->duration;
  2135. $this->duration_value = substr($obj->duration, 0, dol_strlen($obj->duration) - 1);
  2136. $this->duration_unit = substr($obj->duration, -1);
  2137. $this->canvas = $obj->canvas;
  2138. $this->net_measure = $obj->net_measure;
  2139. $this->net_measure_units = $obj->net_measure_units;
  2140. $this->weight = $obj->weight;
  2141. $this->weight_units = $obj->weight_units;
  2142. $this->length = $obj->length;
  2143. $this->length_units = $obj->length_units;
  2144. $this->width = $obj->width;
  2145. $this->width_units = $obj->width_units;
  2146. $this->height = $obj->height;
  2147. $this->height_units = $obj->height_units;
  2148. $this->surface = $obj->surface;
  2149. $this->surface_units = $obj->surface_units;
  2150. $this->volume = $obj->volume;
  2151. $this->volume_units = $obj->volume_units;
  2152. $this->barcode = $obj->barcode;
  2153. $this->barcode_type = $obj->fk_barcode_type;
  2154. $this->accountancy_code_buy = $obj->accountancy_code_buy;
  2155. $this->accountancy_code_buy_intra = $obj->accountancy_code_buy_intra;
  2156. $this->accountancy_code_buy_export = $obj->accountancy_code_buy_export;
  2157. $this->accountancy_code_sell = $obj->accountancy_code_sell;
  2158. $this->accountancy_code_sell_intra = $obj->accountancy_code_sell_intra;
  2159. $this->accountancy_code_sell_export = $obj->accountancy_code_sell_export;
  2160. $this->fk_default_warehouse = $obj->fk_default_warehouse;
  2161. $this->seuil_stock_alerte = $obj->seuil_stock_alerte;
  2162. $this->desiredstock = $obj->desiredstock;
  2163. $this->stock_reel = $obj->stock;
  2164. $this->pmp = $obj->pmp;
  2165. $this->date_creation = $obj->datec;
  2166. $this->date_modification = $obj->tms;
  2167. $this->import_key = $obj->import_key;
  2168. $this->entity = $obj->entity;
  2169. $this->ref_ext = $obj->ref_ext;
  2170. $this->fk_price_expression = $obj->fk_price_expression;
  2171. $this->fk_unit = $obj->fk_unit;
  2172. $this->price_autogen = $obj->price_autogen;
  2173. $this->model_pdf = $obj->model_pdf;
  2174. $this->mandatory_period = $obj->mandatory_period;
  2175. $this->db->free($resql);
  2176. // fetch optionals attributes and labels
  2177. $this->fetch_optionals();
  2178. // Multilangs
  2179. if (!empty($conf->global->MAIN_MULTILANGS) && empty($ignore_lang_load)) {
  2180. $this->getMultiLangs();
  2181. }
  2182. // Load multiprices array
  2183. if (!empty($conf->global->PRODUIT_MULTIPRICES) && empty($ignore_price_load)) { // prices per segment
  2184. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  2185. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2186. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
  2187. $sql .= " FROM ".$this->db->prefix()."product_price";
  2188. $sql .= " WHERE entity IN (".getEntity('productprice').")";
  2189. $sql .= " AND price_level=".((int) $i);
  2190. $sql .= " AND fk_product = ".((int) $this->id);
  2191. $sql .= " ORDER BY date_price DESC, rowid DESC"; // Get the most recent line
  2192. $sql .= " LIMIT 1"; // Only the first one
  2193. $resql = $this->db->query($sql);
  2194. if ($resql) {
  2195. $result = $this->db->fetch_array($resql);
  2196. $this->multiprices[$i] = $result ? $result["price"] : null;
  2197. $this->multiprices_ttc[$i] = $result ? $result["price_ttc"] : null;
  2198. $this->multiprices_min[$i] = $result ? $result["price_min"] : null;
  2199. $this->multiprices_min_ttc[$i] = $result ? $result["price_min_ttc"] : null;
  2200. $this->multiprices_base_type[$i] = $result ? $result["price_base_type"] : null;
  2201. // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
  2202. $this->multiprices_tva_tx[$i] = $result ? $result["tva_tx"].($result ? ' ('.$result['default_vat_code'].')' : '') : null;
  2203. $this->multiprices_recuperableonly[$i] = $result ? $result["recuperableonly"] : null;
  2204. // Price by quantity
  2205. /*
  2206. $this->prices_by_qty[$i]=$result["price_by_qty"];
  2207. $this->prices_by_qty_id[$i]=$result["rowid"];
  2208. // Récuperation de la liste des prix selon qty si flag positionné
  2209. if ($this->prices_by_qty[$i] == 1)
  2210. {
  2211. $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
  2212. $sql.= " FROM ".$this->db->prefix()."product_price_by_qty";
  2213. $sql.= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
  2214. $sql.= " ORDER BY quantity ASC";
  2215. $resultat=array();
  2216. $resql = $this->db->query($sql);
  2217. if ($resql)
  2218. {
  2219. $ii=0;
  2220. while ($result= $this->db->fetch_array($resql)) {
  2221. $resultat[$ii]=array();
  2222. $resultat[$ii]["rowid"]=$result["rowid"];
  2223. $resultat[$ii]["price"]= $result["price"];
  2224. $resultat[$ii]["unitprice"]= $result["unitprice"];
  2225. $resultat[$ii]["quantity"]= $result["quantity"];
  2226. $resultat[$ii]["remise_percent"]= $result["remise_percent"];
  2227. $resultat[$ii]["remise"]= $result["remise"]; // deprecated
  2228. $resultat[$ii]["price_base_type"]= $result["price_base_type"];
  2229. $ii++;
  2230. }
  2231. $this->prices_by_qty_list[$i]=$resultat;
  2232. }
  2233. else
  2234. {
  2235. dol_print_error($this->db);
  2236. return -1;
  2237. }
  2238. }*/
  2239. } else {
  2240. $this->error = $this->db->lasterror;
  2241. return -1;
  2242. }
  2243. }
  2244. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES) && empty($ignore_price_load)) { // prices per customers
  2245. // Nothing loaded by default. List may be very long.
  2246. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && empty($ignore_price_load)) { // prices per quantity
  2247. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2248. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid";
  2249. $sql .= " FROM ".$this->db->prefix()."product_price";
  2250. $sql .= " WHERE fk_product = ".((int) $this->id);
  2251. $sql .= " ORDER BY date_price DESC, rowid DESC";
  2252. $sql .= " LIMIT 1";
  2253. $resql = $this->db->query($sql);
  2254. if ($resql) {
  2255. $result = $this->db->fetch_array($resql);
  2256. // Price by quantity
  2257. $this->prices_by_qty[0] = $result["price_by_qty"];
  2258. $this->prices_by_qty_id[0] = $result["rowid"];
  2259. // Récuperation de la liste des prix selon qty si flag positionné
  2260. if ($this->prices_by_qty[0] == 1) {
  2261. $sql = "SELECT rowid,price, unitprice, quantity, remise_percent, remise, remise, price_base_type";
  2262. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2263. $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[0]);
  2264. $sql .= " ORDER BY quantity ASC";
  2265. $resultat = array();
  2266. $resql = $this->db->query($sql);
  2267. if ($resql) {
  2268. $ii = 0;
  2269. while ($result = $this->db->fetch_array($resql)) {
  2270. $resultat[$ii] = array();
  2271. $resultat[$ii]["rowid"] = $result["rowid"];
  2272. $resultat[$ii]["price"] = $result["price"];
  2273. $resultat[$ii]["unitprice"] = $result["unitprice"];
  2274. $resultat[$ii]["quantity"] = $result["quantity"];
  2275. $resultat[$ii]["remise_percent"] = $result["remise_percent"];
  2276. //$resultat[$ii]["remise"]= $result["remise"]; // deprecated
  2277. $resultat[$ii]["price_base_type"] = $result["price_base_type"];
  2278. $ii++;
  2279. }
  2280. $this->prices_by_qty_list[0] = $resultat;
  2281. } else {
  2282. $this->error = $this->db->lasterror;
  2283. return -1;
  2284. }
  2285. }
  2286. } else {
  2287. $this->error = $this->db->lasterror;
  2288. return -1;
  2289. }
  2290. } elseif (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES) && empty($ignore_price_load)) { // prices per customer and quantity
  2291. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  2292. $sql = "SELECT price, price_ttc, price_min, price_min_ttc,";
  2293. $sql .= " price_base_type, tva_tx, default_vat_code, tosell, price_by_qty, rowid, recuperableonly";
  2294. $sql .= " FROM ".$this->db->prefix()."product_price";
  2295. $sql .= " WHERE entity IN (".getEntity('productprice').")";
  2296. $sql .= " AND price_level=".((int) $i);
  2297. $sql .= " AND fk_product = ".((int) $this->id);
  2298. $sql .= " ORDER BY date_price DESC, rowid DESC";
  2299. $sql .= " LIMIT 1";
  2300. $resql = $this->db->query($sql);
  2301. if ($resql) {
  2302. $result = $this->db->fetch_array($resql);
  2303. $this->multiprices[$i] = $result["price"];
  2304. $this->multiprices_ttc[$i] = $result["price_ttc"];
  2305. $this->multiprices_min[$i] = $result["price_min"];
  2306. $this->multiprices_min_ttc[$i] = $result["price_min_ttc"];
  2307. $this->multiprices_base_type[$i] = $result["price_base_type"];
  2308. // Next two fields are used only if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on
  2309. $this->multiprices_tva_tx[$i] = $result["tva_tx"]; // TODO Add ' ('.$result['default_vat_code'].')'
  2310. $this->multiprices_recuperableonly[$i] = $result["recuperableonly"];
  2311. // Price by quantity
  2312. $this->prices_by_qty[$i] = $result["price_by_qty"];
  2313. $this->prices_by_qty_id[$i] = $result["rowid"];
  2314. // Récuperation de la liste des prix selon qty si flag positionné
  2315. if ($this->prices_by_qty[$i] == 1) {
  2316. $sql = "SELECT rowid, price, unitprice, quantity, remise_percent, remise, price_base_type";
  2317. $sql .= " FROM ".$this->db->prefix()."product_price_by_qty";
  2318. $sql .= " WHERE fk_product_price = ".((int) $this->prices_by_qty_id[$i]);
  2319. $sql .= " ORDER BY quantity ASC";
  2320. $resultat = array();
  2321. $resql = $this->db->query($sql);
  2322. if ($resql) {
  2323. $ii = 0;
  2324. while ($result = $this->db->fetch_array($resql)) {
  2325. $resultat[$ii] = array();
  2326. $resultat[$ii]["rowid"] = $result["rowid"];
  2327. $resultat[$ii]["price"] = $result["price"];
  2328. $resultat[$ii]["unitprice"] = $result["unitprice"];
  2329. $resultat[$ii]["quantity"] = $result["quantity"];
  2330. $resultat[$ii]["remise_percent"] = $result["remise_percent"];
  2331. $resultat[$ii]["remise"] = $result["remise"]; // deprecated
  2332. $resultat[$ii]["price_base_type"] = $result["price_base_type"];
  2333. $ii++;
  2334. }
  2335. $this->prices_by_qty_list[$i] = $resultat;
  2336. } else {
  2337. $this->error = $this->db->lasterror;
  2338. return -1;
  2339. }
  2340. }
  2341. } else {
  2342. $this->error = $this->db->lasterror;
  2343. return -1;
  2344. }
  2345. }
  2346. }
  2347. if (!empty($conf->dynamicprices->enabled) && !empty($this->fk_price_expression) && empty($ignore_expression)) {
  2348. include_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  2349. $priceparser = new PriceParser($this->db);
  2350. $price_result = $priceparser->parseProduct($this);
  2351. if ($price_result >= 0) {
  2352. $this->price = $price_result;
  2353. // Calculate the VAT
  2354. $this->price_ttc = price2num($this->price) * (1 + ($this->tva_tx / 100));
  2355. $this->price_ttc = price2num($this->price_ttc, 'MU');
  2356. }
  2357. }
  2358. // We should not load stock during the fetch. If someone need stock of product, he must call load_stock after fetching product.
  2359. // Instead we just init the stock_warehouse array
  2360. $this->stock_warehouse = array();
  2361. return 1;
  2362. } else {
  2363. return 0;
  2364. }
  2365. } else {
  2366. $this->error = $this->db->lasterror();
  2367. return -1;
  2368. }
  2369. }
  2370. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2371. /**
  2372. * Charge tableau des stats OF pour le produit/service
  2373. *
  2374. * @param int $socid Id societe
  2375. * @return int Array of stats in $this->stats_mo, <0 if ko or >0 if ok
  2376. */
  2377. public function load_stats_mo($socid = 0)
  2378. {
  2379. // phpcs:enable
  2380. global $user, $hookmanager, $action;
  2381. $error = 0;
  2382. foreach (array('toconsume', 'consumed', 'toproduce', 'produced') as $role) {
  2383. $this->stats_mo['customers_'.$role] = 0;
  2384. $this->stats_mo['nb_'.$role] = 0;
  2385. $this->stats_mo['qty_'.$role] = 0;
  2386. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2387. $sql .= " SUM(mp.qty) as qty";
  2388. $sql .= " FROM ".$this->db->prefix()."mrp_mo as c";
  2389. $sql .= " INNER JOIN ".$this->db->prefix()."mrp_production as mp ON mp.fk_mo=c.rowid";
  2390. if (empty($user->rights->societe->client->voir) && !$socid) {
  2391. $sql .= "INNER JOIN ".$this->db->prefix()."societe_commerciaux as sc ON sc.fk_soc=c.fk_soc AND sc.fk_user = ".((int) $user->id);
  2392. }
  2393. $sql .= " WHERE ";
  2394. $sql .= " c.entity IN (".getEntity('mo').")";
  2395. $sql .= " AND mp.fk_product = ".((int) $this->id);
  2396. $sql .= " AND mp.role ='".$this->db->escape($role)."'";
  2397. if ($socid > 0) {
  2398. $sql .= " AND c.fk_soc = ".((int) $socid);
  2399. }
  2400. $result = $this->db->query($sql);
  2401. if ($result) {
  2402. $obj = $this->db->fetch_object($result);
  2403. $this->stats_mo['customers_'.$role] = $obj->nb_customers ? $obj->nb_customers : 0;
  2404. $this->stats_mo['nb_'.$role] = $obj->nb ? $obj->nb : 0;
  2405. $this->stats_mo['qty_'.$role] = $obj->qty ? price2num($obj->qty, 'MS') : 0; // qty may be a float due to the SUM()
  2406. } else {
  2407. $this->error = $this->db->error();
  2408. $error++;
  2409. }
  2410. }
  2411. if (!empty($error)) {
  2412. return -1;
  2413. }
  2414. $parameters = array('socid' => $socid);
  2415. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  2416. if ($reshook > 0) {
  2417. $this->stats_mo = $hookmanager->resArray['stats_mo'];
  2418. }
  2419. return 1;
  2420. }
  2421. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2422. /**
  2423. * Charge tableau des stats OF pour le produit/service
  2424. *
  2425. * @param int $socid Id societe
  2426. * @return int Array of stats in $this->stats_bom, <0 if ko or >0 if ok
  2427. */
  2428. public function load_stats_bom($socid = 0)
  2429. {
  2430. // phpcs:enable
  2431. global $user, $hookmanager;
  2432. $error = 0;
  2433. $this->stats_bom['nb_toproduce'] = 0;
  2434. $this->stats_bom['nb_toconsume'] = 0;
  2435. $this->stats_bom['qty_toproduce'] = 0;
  2436. $this->stats_bom['qty_toconsume'] = 0;
  2437. $sql = "SELECT COUNT(DISTINCT b.rowid) as nb_toproduce,";
  2438. $sql .= " SUM(b.qty) as qty_toproduce";
  2439. $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
  2440. $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
  2441. $sql .= " WHERE ";
  2442. $sql .= " b.entity IN (".getEntity('bom').")";
  2443. $sql .= " AND b.fk_product =".((int) $this->id);
  2444. $sql .= " GROUP BY b.rowid";
  2445. $result = $this->db->query($sql);
  2446. if ($result) {
  2447. $obj = $this->db->fetch_object($result);
  2448. $this->stats_bom['nb_toproduce'] = !empty($obj->nb_toproduce) ? $obj->nb_toproduce : 0;
  2449. $this->stats_bom['qty_toproduce'] = !empty($obj->qty_toproduce) ? price2num($obj->qty_toproduce) : 0;
  2450. } else {
  2451. $this->error = $this->db->error();
  2452. $error++;
  2453. }
  2454. $sql = "SELECT COUNT(DISTINCT bl.rowid) as nb_toconsume,";
  2455. $sql .= " SUM(bl.qty) as qty_toconsume";
  2456. $sql .= " FROM ".$this->db->prefix()."bom_bom as b";
  2457. $sql .= " INNER JOIN ".$this->db->prefix()."bom_bomline as bl ON bl.fk_bom=b.rowid";
  2458. $sql .= " WHERE ";
  2459. $sql .= " b.entity IN (".getEntity('bom').")";
  2460. $sql .= " AND bl.fk_product =".((int) $this->id);
  2461. $result = $this->db->query($sql);
  2462. if ($result) {
  2463. $obj = $this->db->fetch_object($result);
  2464. $this->stats_bom['nb_toconsume'] = !empty($obj->nb_toconsume) ? $obj->nb_toconsume : 0;
  2465. $this->stats_bom['qty_toconsume'] = !empty($obj->qty_toconsume) ? price2num($obj->qty_toconsume) : 0;
  2466. } else {
  2467. $this->error = $this->db->error();
  2468. $error++;
  2469. }
  2470. if (!empty($error)) {
  2471. return -1;
  2472. }
  2473. $parameters = array('socid' => $socid);
  2474. $reshook = $hookmanager->executeHooks('loadStatsCustomerMO', $parameters, $this, $action);
  2475. if ($reshook > 0) {
  2476. $this->stats_bom = $hookmanager->resArray['stats_bom'];
  2477. }
  2478. return 1;
  2479. }
  2480. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2481. /**
  2482. * Charge tableau des stats propale pour le produit/service
  2483. *
  2484. * @param int $socid Id societe
  2485. * @return int Array of stats in $this->stats_propale, <0 if ko or >0 if ok
  2486. */
  2487. public function load_stats_propale($socid = 0)
  2488. {
  2489. // phpcs:enable
  2490. global $conf, $user, $hookmanager;
  2491. $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_customers, COUNT(DISTINCT p.rowid) as nb,";
  2492. $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
  2493. $sql .= " FROM ".$this->db->prefix()."propaldet as pd";
  2494. $sql .= ", ".$this->db->prefix()."propal as p";
  2495. $sql .= ", ".$this->db->prefix()."societe as s";
  2496. if (empty($user->rights->societe->client->voir) && !$socid) {
  2497. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2498. }
  2499. $sql .= " WHERE p.rowid = pd.fk_propal";
  2500. $sql .= " AND p.fk_soc = s.rowid";
  2501. $sql .= " AND p.entity IN (".getEntity('propal').")";
  2502. $sql .= " AND pd.fk_product = ".((int) $this->id);
  2503. if (empty($user->rights->societe->client->voir) && !$socid) {
  2504. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2505. }
  2506. //$sql.= " AND pr.fk_statut != 0";
  2507. if ($socid > 0) {
  2508. $sql .= " AND p.fk_soc = ".((int) $socid);
  2509. }
  2510. $result = $this->db->query($sql);
  2511. if ($result) {
  2512. $obj = $this->db->fetch_object($result);
  2513. $this->stats_propale['customers'] = $obj->nb_customers;
  2514. $this->stats_propale['nb'] = $obj->nb;
  2515. $this->stats_propale['rows'] = $obj->nb_rows;
  2516. $this->stats_propale['qty'] = $obj->qty ? $obj->qty : 0;
  2517. // if it's a virtual product, maybe it is in proposal by extension
  2518. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2519. $TFather = $this->getFather();
  2520. if (is_array($TFather) && !empty($TFather)) {
  2521. foreach ($TFather as &$fatherData) {
  2522. $pFather = new Product($this->db);
  2523. $pFather->id = $fatherData['id'];
  2524. $qtyCoef = $fatherData['qty'];
  2525. if ($fatherData['incdec']) {
  2526. $pFather->load_stats_propale($socid);
  2527. $this->stats_propale['customers'] += $pFather->stats_propale['customers'];
  2528. $this->stats_propale['nb'] += $pFather->stats_propale['nb'];
  2529. $this->stats_propale['rows'] += $pFather->stats_propale['rows'];
  2530. $this->stats_propale['qty'] += $pFather->stats_propale['qty'] * $qtyCoef;
  2531. }
  2532. }
  2533. }
  2534. }
  2535. $parameters = array('socid' => $socid);
  2536. $reshook = $hookmanager->executeHooks('loadStatsCustomerProposal', $parameters, $this, $action);
  2537. if ($reshook > 0) {
  2538. $this->stats_propale = $hookmanager->resArray['stats_propale'];
  2539. }
  2540. return 1;
  2541. } else {
  2542. $this->error = $this->db->error();
  2543. return -1;
  2544. }
  2545. }
  2546. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2547. /**
  2548. * Charge tableau des stats propale pour le produit/service
  2549. *
  2550. * @param int $socid Id thirdparty
  2551. * @return int Array of stats in $this->stats_proposal_supplier, <0 if ko or >0 if ok
  2552. */
  2553. public function load_stats_proposal_supplier($socid = 0)
  2554. {
  2555. // phpcs:enable
  2556. global $conf, $user, $hookmanager, $action;
  2557. $sql = "SELECT COUNT(DISTINCT p.fk_soc) as nb_suppliers, COUNT(DISTINCT p.rowid) as nb,";
  2558. $sql .= " COUNT(pd.rowid) as nb_rows, SUM(pd.qty) as qty";
  2559. $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as pd";
  2560. $sql .= ", ".$this->db->prefix()."supplier_proposal as p";
  2561. $sql .= ", ".$this->db->prefix()."societe as s";
  2562. if (empty($user->rights->societe->client->voir) && !$socid) {
  2563. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2564. }
  2565. $sql .= " WHERE p.rowid = pd.fk_supplier_proposal";
  2566. $sql .= " AND p.fk_soc = s.rowid";
  2567. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  2568. $sql .= " AND pd.fk_product = ".((int) $this->id);
  2569. if (empty($user->rights->societe->client->voir) && !$socid) {
  2570. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2571. }
  2572. //$sql.= " AND pr.fk_statut != 0";
  2573. if ($socid > 0) {
  2574. $sql .= " AND p.fk_soc = ".((int) $socid);
  2575. }
  2576. $result = $this->db->query($sql);
  2577. if ($result) {
  2578. $obj = $this->db->fetch_object($result);
  2579. $this->stats_proposal_supplier['suppliers'] = $obj->nb_suppliers;
  2580. $this->stats_proposal_supplier['nb'] = $obj->nb;
  2581. $this->stats_proposal_supplier['rows'] = $obj->nb_rows;
  2582. $this->stats_proposal_supplier['qty'] = $obj->qty ? $obj->qty : 0;
  2583. $parameters = array('socid' => $socid);
  2584. $reshook = $hookmanager->executeHooks('loadStatsSupplierProposal', $parameters, $this, $action);
  2585. if ($reshook > 0) {
  2586. $this->stats_proposal_supplier = $hookmanager->resArray['stats_proposal_supplier'];
  2587. }
  2588. return 1;
  2589. } else {
  2590. $this->error = $this->db->error();
  2591. return -1;
  2592. }
  2593. }
  2594. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2595. /**
  2596. * Charge tableau des stats commande client pour le produit/service
  2597. *
  2598. * @param int $socid Id societe pour filtrer sur une societe
  2599. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2600. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2601. * @return integer Array of stats in $this->stats_commande (nb=nb of order, qty=qty ordered), <0 if ko or >0 if ok
  2602. */
  2603. public function load_stats_commande($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2604. {
  2605. // phpcs:enable
  2606. global $conf, $user, $hookmanager;
  2607. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2608. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2609. $sql .= " FROM ".$this->db->prefix()."commandedet as cd";
  2610. $sql .= ", ".$this->db->prefix()."commande as c";
  2611. $sql .= ", ".$this->db->prefix()."societe as s";
  2612. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2613. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2614. }
  2615. $sql .= " WHERE c.rowid = cd.fk_commande";
  2616. $sql .= " AND c.fk_soc = s.rowid";
  2617. $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'commande').")";
  2618. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2619. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2620. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2621. }
  2622. if ($socid > 0) {
  2623. $sql .= " AND c.fk_soc = ".((int) $socid);
  2624. }
  2625. if ($filtrestatut <> '') {
  2626. $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")";
  2627. }
  2628. $result = $this->db->query($sql);
  2629. if ($result) {
  2630. $obj = $this->db->fetch_object($result);
  2631. $this->stats_commande['customers'] = $obj->nb_customers;
  2632. $this->stats_commande['nb'] = $obj->nb;
  2633. $this->stats_commande['rows'] = $obj->nb_rows;
  2634. $this->stats_commande['qty'] = $obj->qty ? $obj->qty : 0;
  2635. // if it's a virtual product, maybe it is in order by extension
  2636. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2637. $TFather = $this->getFather();
  2638. if (is_array($TFather) && !empty($TFather)) {
  2639. foreach ($TFather as &$fatherData) {
  2640. $pFather = new Product($this->db);
  2641. $pFather->id = $fatherData['id'];
  2642. $qtyCoef = $fatherData['qty'];
  2643. if ($fatherData['incdec']) {
  2644. $pFather->load_stats_commande($socid, $filtrestatut);
  2645. $this->stats_commande['customers'] += $pFather->stats_commande['customers'];
  2646. $this->stats_commande['nb'] += $pFather->stats_commande['nb'];
  2647. $this->stats_commande['rows'] += $pFather->stats_commande['rows'];
  2648. $this->stats_commande['qty'] += $pFather->stats_commande['qty'] * $qtyCoef;
  2649. }
  2650. }
  2651. }
  2652. }
  2653. // If stock decrease is on invoice validation, the theorical stock continue to
  2654. // count the orders to ship in theorical stock when some are already removed b invoice validation.
  2655. // If option DECREASE_ONLY_UNINVOICEDPRODUCTS is on, we make a compensation.
  2656. if (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  2657. if (!empty($conf->global->DECREASE_ONLY_UNINVOICEDPRODUCTS)) {
  2658. $adeduire = 0;
  2659. $sql = "SELECT sum(fd.qty) as count FROM ".$this->db->prefix()."facturedet fd ";
  2660. $sql .= " JOIN ".$this->db->prefix()."facture f ON fd.fk_facture = f.rowid ";
  2661. $sql .= " JOIN ".$this->db->prefix()."element_element el ON el.fk_target = f.rowid and el.targettype = 'facture' and sourcetype = 'commande'";
  2662. $sql .= " JOIN ".$this->db->prefix()."commande c ON el.fk_source = c.rowid ";
  2663. $sql .= " WHERE c.fk_statut IN (".$this->db->sanitize($filtrestatut).") AND c.facture = 0 AND fd.fk_product = ".((int) $this->id);
  2664. dol_syslog(__METHOD__.":: sql $sql", LOG_NOTICE);
  2665. $resql = $this->db->query($sql);
  2666. if ($resql) {
  2667. if ($this->db->num_rows($resql) > 0) {
  2668. $obj = $this->db->fetch_object($resql);
  2669. $adeduire += $obj->count;
  2670. }
  2671. }
  2672. $this->stats_commande['qty'] -= $adeduire;
  2673. }
  2674. }
  2675. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2676. $reshook = $hookmanager->executeHooks('loadStatsCustomerOrder', $parameters, $this, $action);
  2677. if ($reshook > 0) {
  2678. $this->stats_commande = $hookmanager->resArray['stats_commande'];
  2679. }
  2680. return 1;
  2681. } else {
  2682. $this->error = $this->db->error();
  2683. return -1;
  2684. }
  2685. }
  2686. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2687. /**
  2688. * Charge tableau des stats commande fournisseur pour le produit/service
  2689. *
  2690. * @param int $socid Id societe pour filtrer sur une societe
  2691. * @param string $filtrestatut Id des statuts pour filtrer sur des statuts
  2692. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2693. * @return int Array of stats in $this->stats_commande_fournisseur, <0 if ko or >0 if ok
  2694. */
  2695. public function load_stats_commande_fournisseur($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2696. {
  2697. // phpcs:enable
  2698. global $conf, $user, $hookmanager, $action;
  2699. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_suppliers, COUNT(DISTINCT c.rowid) as nb,";
  2700. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2701. $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as cd";
  2702. $sql .= ", ".$this->db->prefix()."commande_fournisseur as c";
  2703. $sql .= ", ".$this->db->prefix()."societe as s";
  2704. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2705. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2706. }
  2707. $sql .= " WHERE c.rowid = cd.fk_commande";
  2708. $sql .= " AND c.fk_soc = s.rowid";
  2709. $sql .= " AND c.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
  2710. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2711. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2712. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2713. }
  2714. if ($socid > 0) {
  2715. $sql .= " AND c.fk_soc = ".((int) $socid);
  2716. }
  2717. if ($filtrestatut != '') {
  2718. $sql .= " AND c.fk_statut in (".$this->db->sanitize($filtrestatut).")"; // Peut valoir 0
  2719. }
  2720. $result = $this->db->query($sql);
  2721. if ($result) {
  2722. $obj = $this->db->fetch_object($result);
  2723. $this->stats_commande_fournisseur['suppliers'] = $obj->nb_suppliers;
  2724. $this->stats_commande_fournisseur['nb'] = $obj->nb;
  2725. $this->stats_commande_fournisseur['rows'] = $obj->nb_rows;
  2726. $this->stats_commande_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
  2727. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2728. $reshook = $hookmanager->executeHooks('loadStatsSupplierOrder', $parameters, $this, $action);
  2729. if ($reshook > 0) {
  2730. $this->stats_commande_fournisseur = $hookmanager->resArray['stats_commande_fournisseur'];
  2731. }
  2732. return 1;
  2733. } else {
  2734. $this->error = $this->db->error().' sql='.$sql;
  2735. return -1;
  2736. }
  2737. }
  2738. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2739. /**
  2740. * Charge tableau des stats expedition client pour le produit/service
  2741. *
  2742. * @param int $socid Id societe pour filtrer sur une societe
  2743. * @param string $filtrestatut [=''] Ids order status separated by comma
  2744. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2745. * @param string $filterShipmentStatus [=''] Ids shipment status separated by comma
  2746. * @return int Array of stats in $this->stats_expedition, <0 if ko or >0 if ok
  2747. */
  2748. public function load_stats_sending($socid = 0, $filtrestatut = '', $forVirtualStock = 0, $filterShipmentStatus = '')
  2749. {
  2750. // phpcs:enable
  2751. global $conf, $user, $hookmanager;
  2752. $sql = "SELECT COUNT(DISTINCT e.fk_soc) as nb_customers, COUNT(DISTINCT e.rowid) as nb,";
  2753. $sql .= " COUNT(ed.rowid) as nb_rows, SUM(ed.qty) as qty";
  2754. $sql .= " FROM ".$this->db->prefix()."expeditiondet as ed";
  2755. $sql .= ", ".$this->db->prefix()."commandedet as cd";
  2756. $sql .= ", ".$this->db->prefix()."commande as c";
  2757. $sql .= ", ".$this->db->prefix()."expedition as e";
  2758. $sql .= ", ".$this->db->prefix()."societe as s";
  2759. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2760. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2761. }
  2762. $sql .= " WHERE e.rowid = ed.fk_expedition";
  2763. $sql .= " AND c.rowid = cd.fk_commande";
  2764. $sql .= " AND e.fk_soc = s.rowid";
  2765. $sql .= " AND e.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'expedition').")";
  2766. $sql .= " AND ed.fk_origin_line = cd.rowid";
  2767. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2768. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2769. $sql .= " AND e.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2770. }
  2771. if ($socid > 0) {
  2772. $sql .= " AND e.fk_soc = ".((int) $socid);
  2773. }
  2774. if ($filtrestatut <> '') {
  2775. $sql .= " AND c.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
  2776. }
  2777. if (!empty($filterShipmentStatus)) {
  2778. $sql .= " AND e.fk_statut IN (".$this->db->sanitize($filterShipmentStatus).")";
  2779. }
  2780. $result = $this->db->query($sql);
  2781. if ($result) {
  2782. $obj = $this->db->fetch_object($result);
  2783. $this->stats_expedition['customers'] = $obj->nb_customers;
  2784. $this->stats_expedition['nb'] = $obj->nb;
  2785. $this->stats_expedition['rows'] = $obj->nb_rows;
  2786. $this->stats_expedition['qty'] = $obj->qty ? $obj->qty : 0;
  2787. // if it's a virtual product, maybe it is in sending by extension
  2788. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2789. $TFather = $this->getFather();
  2790. if (is_array($TFather) && !empty($TFather)) {
  2791. foreach ($TFather as &$fatherData) {
  2792. $pFather = new Product($this->db);
  2793. $pFather->id = $fatherData['id'];
  2794. $qtyCoef = $fatherData['qty'];
  2795. if ($fatherData['incdec']) {
  2796. $pFather->load_stats_sending($socid, $filtrestatut, $forVirtualStock);
  2797. $this->stats_expedition['customers'] += $pFather->stats_expedition['customers'];
  2798. $this->stats_expedition['nb'] += $pFather->stats_expedition['nb'];
  2799. $this->stats_expedition['rows'] += $pFather->stats_expedition['rows'];
  2800. $this->stats_expedition['qty'] += $pFather->stats_expedition['qty'] * $qtyCoef;
  2801. }
  2802. }
  2803. }
  2804. }
  2805. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock, 'filterShipmentStatus' => $filterShipmentStatus);
  2806. $reshook = $hookmanager->executeHooks('loadStatsSending', $parameters, $this, $action);
  2807. if ($reshook > 0) {
  2808. $this->stats_expedition = $hookmanager->resArray['stats_expedition'];
  2809. }
  2810. return 1;
  2811. } else {
  2812. $this->error = $this->db->error();
  2813. return -1;
  2814. }
  2815. }
  2816. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2817. /**
  2818. * Charge tableau des stats réception fournisseur pour le produit/service
  2819. *
  2820. * @param int $socid Id societe pour filtrer sur une societe
  2821. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2822. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2823. * @return int Array of stats in $this->stats_reception, <0 if ko or >0 if ok
  2824. */
  2825. public function load_stats_reception($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2826. {
  2827. // phpcs:enable
  2828. global $conf, $user, $hookmanager, $action;
  2829. $sql = "SELECT COUNT(DISTINCT cf.fk_soc) as nb_suppliers, COUNT(DISTINCT cf.rowid) as nb,";
  2830. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  2831. $sql .= " FROM ".$this->db->prefix()."commande_fournisseur_dispatch as fd";
  2832. $sql .= ", ".$this->db->prefix()."commande_fournisseur as cf";
  2833. $sql .= ", ".$this->db->prefix()."societe as s";
  2834. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2835. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2836. }
  2837. $sql .= " WHERE cf.rowid = fd.fk_commande";
  2838. $sql .= " AND cf.fk_soc = s.rowid";
  2839. $sql .= " AND cf.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'supplier_order').")";
  2840. $sql .= " AND fd.fk_product = ".((int) $this->id);
  2841. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2842. $sql .= " AND cf.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2843. }
  2844. if ($socid > 0) {
  2845. $sql .= " AND cf.fk_soc = ".((int) $socid);
  2846. }
  2847. if ($filtrestatut <> '') {
  2848. $sql .= " AND cf.fk_statut IN (".$this->db->sanitize($filtrestatut).")";
  2849. }
  2850. $result = $this->db->query($sql);
  2851. if ($result) {
  2852. $obj = $this->db->fetch_object($result);
  2853. $this->stats_reception['suppliers'] = $obj->nb_suppliers;
  2854. $this->stats_reception['nb'] = $obj->nb;
  2855. $this->stats_reception['rows'] = $obj->nb_rows;
  2856. $this->stats_reception['qty'] = $obj->qty ? $obj->qty : 0;
  2857. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2858. $reshook = $hookmanager->executeHooks('loadStatsReception', $parameters, $this, $action);
  2859. if ($reshook > 0) {
  2860. $this->stats_reception = $hookmanager->resArray['stats_reception'];
  2861. }
  2862. return 1;
  2863. } else {
  2864. $this->error = $this->db->error();
  2865. return -1;
  2866. }
  2867. }
  2868. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2869. /**
  2870. * Charge tableau des stats production pour le produit/service
  2871. *
  2872. * @param int $socid Id societe pour filtrer sur une societe
  2873. * @param string $filtrestatut Id statut pour filtrer sur un statut
  2874. * @param int $forVirtualStock Ignore rights filter for virtual stock calculation.
  2875. * @return integer Array of stats in $this->stats_mrptoproduce (nb=nb of order, qty=qty ordered), <0 if ko or >0 if ok
  2876. */
  2877. public function load_stats_inproduction($socid = 0, $filtrestatut = '', $forVirtualStock = 0)
  2878. {
  2879. // phpcs:enable
  2880. global $conf, $user, $hookmanager;
  2881. $sql = "SELECT COUNT(DISTINCT m.fk_soc) as nb_customers, COUNT(DISTINCT m.rowid) as nb,";
  2882. $sql .= " COUNT(mp.rowid) as nb_rows, SUM(mp.qty) as qty, role";
  2883. $sql .= " FROM ".$this->db->prefix()."mrp_production as mp";
  2884. $sql .= ", ".$this->db->prefix()."mrp_mo as m";
  2885. $sql .= " LEFT JOIN ".$this->db->prefix()."societe as s ON s.rowid = m.fk_soc";
  2886. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2887. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2888. }
  2889. $sql .= " WHERE m.rowid = mp.fk_mo";
  2890. $sql .= " AND m.entity IN (".getEntity($forVirtualStock && !empty($conf->global->STOCK_CALCULATE_VIRTUAL_STOCK_TRANSVERSE_MODE) ? 'stock' : 'mrp').")";
  2891. $sql .= " AND mp.fk_product = ".((int) $this->id);
  2892. if (empty($user->rights->societe->client->voir) && !$socid && !$forVirtualStock) {
  2893. $sql .= " AND m.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2894. }
  2895. if ($socid > 0) {
  2896. $sql .= " AND m.fk_soc = ".((int) $socid);
  2897. }
  2898. if ($filtrestatut <> '') {
  2899. $sql .= " AND m.status IN (".$this->db->sanitize($filtrestatut).")";
  2900. }
  2901. $sql .= " GROUP BY role";
  2902. $this->stats_mrptoconsume['customers'] = 0;
  2903. $this->stats_mrptoconsume['nb'] = 0;
  2904. $this->stats_mrptoconsume['rows'] = 0;
  2905. $this->stats_mrptoconsume['qty'] = 0;
  2906. $this->stats_mrptoproduce['customers'] = 0;
  2907. $this->stats_mrptoproduce['nb'] = 0;
  2908. $this->stats_mrptoproduce['rows'] = 0;
  2909. $this->stats_mrptoproduce['qty'] = 0;
  2910. $result = $this->db->query($sql);
  2911. if ($result) {
  2912. while ($obj = $this->db->fetch_object($result)) {
  2913. if ($obj->role == 'toconsume') {
  2914. $this->stats_mrptoconsume['customers'] += $obj->nb_customers;
  2915. $this->stats_mrptoconsume['nb'] += $obj->nb;
  2916. $this->stats_mrptoconsume['rows'] += $obj->nb_rows;
  2917. $this->stats_mrptoconsume['qty'] += ($obj->qty ? $obj->qty : 0);
  2918. }
  2919. if ($obj->role == 'consumed') {
  2920. //$this->stats_mrptoconsume['customers'] += $obj->nb_customers;
  2921. //$this->stats_mrptoconsume['nb'] += $obj->nb;
  2922. //$this->stats_mrptoconsume['rows'] += $obj->nb_rows;
  2923. $this->stats_mrptoconsume['qty'] -= ($obj->qty ? $obj->qty : 0);
  2924. }
  2925. if ($obj->role == 'toproduce') {
  2926. $this->stats_mrptoproduce['customers'] += $obj->nb_customers;
  2927. $this->stats_mrptoproduce['nb'] += $obj->nb;
  2928. $this->stats_mrptoproduce['rows'] += $obj->nb_rows;
  2929. $this->stats_mrptoproduce['qty'] += ($obj->qty ? $obj->qty : 0);
  2930. }
  2931. if ($obj->role == 'produced') {
  2932. //$this->stats_mrptoproduce['customers'] += $obj->nb_customers;
  2933. //$this->stats_mrptoproduce['nb'] += $obj->nb;
  2934. //$this->stats_mrptoproduce['rows'] += $obj->nb_rows;
  2935. $this->stats_mrptoproduce['qty'] -= ($obj->qty ? $obj->qty : 0);
  2936. }
  2937. }
  2938. // Clean data
  2939. if ($this->stats_mrptoconsume['qty'] < 0) {
  2940. $this->stats_mrptoconsume['qty'] = 0;
  2941. }
  2942. if ($this->stats_mrptoproduce['qty'] < 0) {
  2943. $this->stats_mrptoproduce['qty'] = 0;
  2944. }
  2945. $parameters = array('socid' => $socid, 'filtrestatut' => $filtrestatut, 'forVirtualStock' => $forVirtualStock);
  2946. $reshook = $hookmanager->executeHooks('loadStatsInProduction', $parameters, $this, $action);
  2947. if ($reshook > 0) {
  2948. $this->stats_mrptoproduce = $hookmanager->resArray['stats_mrptoproduce'];
  2949. }
  2950. return 1;
  2951. } else {
  2952. $this->error = $this->db->error();
  2953. return -1;
  2954. }
  2955. }
  2956. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  2957. /**
  2958. * Charge tableau des stats contrat pour le produit/service
  2959. *
  2960. * @param int $socid Id societe
  2961. * @return int Array of stats in $this->stats_contrat, <0 if ko or >0 if ok
  2962. */
  2963. public function load_stats_contrat($socid = 0)
  2964. {
  2965. // phpcs:enable
  2966. global $conf, $user, $hookmanager;
  2967. $sql = "SELECT COUNT(DISTINCT c.fk_soc) as nb_customers, COUNT(DISTINCT c.rowid) as nb,";
  2968. $sql .= " COUNT(cd.rowid) as nb_rows, SUM(cd.qty) as qty";
  2969. $sql .= " FROM ".$this->db->prefix()."contratdet as cd";
  2970. $sql .= ", ".$this->db->prefix()."contrat as c";
  2971. $sql .= ", ".$this->db->prefix()."societe as s";
  2972. if (empty($user->rights->societe->client->voir) && !$socid) {
  2973. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  2974. }
  2975. $sql .= " WHERE c.rowid = cd.fk_contrat";
  2976. $sql .= " AND c.fk_soc = s.rowid";
  2977. $sql .= " AND c.entity IN (".getEntity('contract').")";
  2978. $sql .= " AND cd.fk_product = ".((int) $this->id);
  2979. if (empty($user->rights->societe->client->voir) && !$socid) {
  2980. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  2981. }
  2982. //$sql.= " AND c.statut != 0";
  2983. if ($socid > 0) {
  2984. $sql .= " AND c.fk_soc = ".((int) $socid);
  2985. }
  2986. $result = $this->db->query($sql);
  2987. if ($result) {
  2988. $obj = $this->db->fetch_object($result);
  2989. $this->stats_contrat['customers'] = $obj->nb_customers;
  2990. $this->stats_contrat['nb'] = $obj->nb;
  2991. $this->stats_contrat['rows'] = $obj->nb_rows;
  2992. $this->stats_contrat['qty'] = $obj->qty ? $obj->qty : 0;
  2993. // if it's a virtual product, maybe it is in contract by extension
  2994. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  2995. $TFather = $this->getFather();
  2996. if (is_array($TFather) && !empty($TFather)) {
  2997. foreach ($TFather as &$fatherData) {
  2998. $pFather = new Product($this->db);
  2999. $pFather->id = $fatherData['id'];
  3000. $qtyCoef = $fatherData['qty'];
  3001. if ($fatherData['incdec']) {
  3002. $pFather->load_stats_contrat($socid);
  3003. $this->stats_contrat['customers'] += $pFather->stats_contrat['customers'];
  3004. $this->stats_contrat['nb'] += $pFather->stats_contrat['nb'];
  3005. $this->stats_contrat['rows'] += $pFather->stats_contrat['rows'];
  3006. $this->stats_contrat['qty'] += $pFather->stats_contrat['qty'] * $qtyCoef;
  3007. }
  3008. }
  3009. }
  3010. }
  3011. $parameters = array('socid' => $socid);
  3012. $reshook = $hookmanager->executeHooks('loadStatsContract', $parameters, $this, $action);
  3013. if ($reshook > 0) {
  3014. $this->stats_contrat = $hookmanager->resArray['stats_contrat'];
  3015. }
  3016. return 1;
  3017. } else {
  3018. $this->error = $this->db->error().' sql='.$sql;
  3019. return -1;
  3020. }
  3021. }
  3022. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3023. /**
  3024. * Charge tableau des stats facture pour le produit/service
  3025. *
  3026. * @param int $socid Id societe
  3027. * @return int Array of stats in $this->stats_facture, <0 if ko or >0 if ok
  3028. */
  3029. public function load_stats_facture($socid = 0)
  3030. {
  3031. // phpcs:enable
  3032. global $db, $conf, $user, $hookmanager;
  3033. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_customers, COUNT(DISTINCT f.rowid) as nb,";
  3034. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(".$this->db->ifsql('f.type != 2', 'fd.qty', 'fd.qty * -1').") as qty";
  3035. $sql .= " FROM ".$this->db->prefix()."facturedet as fd";
  3036. $sql .= ", ".$this->db->prefix()."facture as f";
  3037. $sql .= ", ".$this->db->prefix()."societe as s";
  3038. if (empty($user->rights->societe->client->voir) && !$socid) {
  3039. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3040. }
  3041. $sql .= " WHERE f.rowid = fd.fk_facture";
  3042. $sql .= " AND f.fk_soc = s.rowid";
  3043. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3044. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3045. if (empty($user->rights->societe->client->voir) && !$socid) {
  3046. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3047. }
  3048. //$sql.= " AND f.fk_statut != 0";
  3049. if ($socid > 0) {
  3050. $sql .= " AND f.fk_soc = ".((int) $socid);
  3051. }
  3052. $result = $this->db->query($sql);
  3053. if ($result) {
  3054. $obj = $this->db->fetch_object($result);
  3055. $this->stats_facture['customers'] = $obj->nb_customers;
  3056. $this->stats_facture['nb'] = $obj->nb;
  3057. $this->stats_facture['rows'] = $obj->nb_rows;
  3058. $this->stats_facture['qty'] = $obj->qty ? $obj->qty : 0;
  3059. // if it's a virtual product, maybe it is in invoice by extension
  3060. if (!empty($conf->global->PRODUCT_STATS_WITH_PARENT_PROD_IF_INCDEC)) {
  3061. $TFather = $this->getFather();
  3062. if (is_array($TFather) && !empty($TFather)) {
  3063. foreach ($TFather as &$fatherData) {
  3064. $pFather = new Product($this->db);
  3065. $pFather->id = $fatherData['id'];
  3066. $qtyCoef = $fatherData['qty'];
  3067. if ($fatherData['incdec']) {
  3068. $pFather->load_stats_facture($socid);
  3069. $this->stats_facture['customers'] += $pFather->stats_facture['customers'];
  3070. $this->stats_facture['nb'] += $pFather->stats_facture['nb'];
  3071. $this->stats_facture['rows'] += $pFather->stats_facture['rows'];
  3072. $this->stats_facture['qty'] += $pFather->stats_facture['qty'] * $qtyCoef;
  3073. }
  3074. }
  3075. }
  3076. }
  3077. $parameters = array('socid' => $socid);
  3078. $reshook = $hookmanager->executeHooks('loadStatsCustomerInvoice', $parameters, $this, $action);
  3079. if ($reshook > 0) {
  3080. $this->stats_facture = $hookmanager->resArray['stats_facture'];
  3081. }
  3082. return 1;
  3083. } else {
  3084. $this->error = $this->db->error();
  3085. return -1;
  3086. }
  3087. }
  3088. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3089. /**
  3090. * Charge tableau des stats facture pour le produit/service
  3091. *
  3092. * @param int $socid Id societe
  3093. * @return int Array of stats in $this->stats_facture_fournisseur, <0 if ko or >0 if ok
  3094. */
  3095. public function load_stats_facture_fournisseur($socid = 0)
  3096. {
  3097. // phpcs:enable
  3098. global $conf, $user, $hookmanager, $action;
  3099. $sql = "SELECT COUNT(DISTINCT f.fk_soc) as nb_suppliers, COUNT(DISTINCT f.rowid) as nb,";
  3100. $sql .= " COUNT(fd.rowid) as nb_rows, SUM(fd.qty) as qty";
  3101. $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as fd";
  3102. $sql .= ", ".$this->db->prefix()."facture_fourn as f";
  3103. $sql .= ", ".$this->db->prefix()."societe as s";
  3104. if (empty($user->rights->societe->client->voir) && !$socid) {
  3105. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3106. }
  3107. $sql .= " WHERE f.rowid = fd.fk_facture_fourn";
  3108. $sql .= " AND f.fk_soc = s.rowid";
  3109. $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
  3110. $sql .= " AND fd.fk_product = ".((int) $this->id);
  3111. if (empty($user->rights->societe->client->voir) && !$socid) {
  3112. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3113. }
  3114. //$sql.= " AND f.fk_statut != 0";
  3115. if ($socid > 0) {
  3116. $sql .= " AND f.fk_soc = ".((int) $socid);
  3117. }
  3118. $result = $this->db->query($sql);
  3119. if ($result) {
  3120. $obj = $this->db->fetch_object($result);
  3121. $this->stats_facture_fournisseur['suppliers'] = $obj->nb_suppliers;
  3122. $this->stats_facture_fournisseur['nb'] = $obj->nb;
  3123. $this->stats_facture_fournisseur['rows'] = $obj->nb_rows;
  3124. $this->stats_facture_fournisseur['qty'] = $obj->qty ? $obj->qty : 0;
  3125. $parameters = array('socid' => $socid);
  3126. $reshook = $hookmanager->executeHooks('loadStatsSupplierInvoice', $parameters, $this, $action);
  3127. if ($reshook > 0) {
  3128. $this->stats_facture_fournisseur = $hookmanager->resArray['stats_facture_fournisseur'];
  3129. }
  3130. return 1;
  3131. } else {
  3132. $this->error = $this->db->error();
  3133. return -1;
  3134. }
  3135. }
  3136. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3137. /**
  3138. * Return an array formated for showing graphs
  3139. *
  3140. * @param string $sql Request to execute
  3141. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3142. * @param int $year Year (0=current year, -1=all years)
  3143. * @return array|int <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3144. */
  3145. private function _get_stats($sql, $mode, $year = 0)
  3146. {
  3147. // phpcs:enable
  3148. $tab = array();
  3149. $resql = $this->db->query($sql);
  3150. if ($resql) {
  3151. $num = $this->db->num_rows($resql);
  3152. $i = 0;
  3153. while ($i < $num) {
  3154. $arr = $this->db->fetch_array($resql);
  3155. $keyfortab = (string) $arr[1];
  3156. if ($year == -1) {
  3157. $keyfortab = substr($keyfortab, -2);
  3158. }
  3159. if ($mode == 'byunit') {
  3160. $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[0]; // 1st field
  3161. } elseif ($mode == 'bynumber') {
  3162. $tab[$keyfortab] = (empty($tab[$keyfortab]) ? 0 : $tab[$keyfortab]) + $arr[2]; // 3rd field
  3163. }
  3164. $i++;
  3165. }
  3166. } else {
  3167. $this->error = $this->db->error().' sql='.$sql;
  3168. return -1;
  3169. }
  3170. if (empty($year)) {
  3171. $year = strftime('%Y', time());
  3172. $month = strftime('%m', time());
  3173. } elseif ($year == -1) {
  3174. $year = '';
  3175. $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
  3176. } else {
  3177. $month = 12; // We imagine we are at end of year, so we get last 12 month before, so all correct year.
  3178. }
  3179. $result = array();
  3180. for ($j = 0; $j < 12; $j++) {
  3181. // $ids is 'D', 'N', 'O', 'S', ... (First letter of month in user language)
  3182. $idx = ucfirst(dol_trunc(dol_print_date(dol_mktime(12, 0, 0, $month, 1, 1970), "%b"), 1, 'right', 'UTF-8', 1));
  3183. //print $idx.'-'.$year.'-'.$month.'<br>';
  3184. $result[$j] = array($idx, isset($tab[$year.$month]) ? $tab[$year.$month] : 0);
  3185. // $result[$j] = array($monthnum,isset($tab[$year.$month])?$tab[$year.$month]:0);
  3186. $month = "0".($month - 1);
  3187. if (dol_strlen($month) == 3) {
  3188. $month = substr($month, 1);
  3189. }
  3190. if ($month == 0) {
  3191. $month = 12;
  3192. $year = $year - 1;
  3193. }
  3194. }
  3195. return array_reverse($result);
  3196. }
  3197. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3198. /**
  3199. * Return nb of units or customers invoices in which product is included
  3200. *
  3201. * @param int $socid Limit count on a particular third party id
  3202. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3203. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3204. * @param int $year Year (0=last 12 month, -1=all years)
  3205. * @param string $morefilter More sql filters
  3206. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3207. */
  3208. public function get_nb_vente($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3209. {
  3210. // phpcs:enable
  3211. global $conf;
  3212. global $user;
  3213. $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
  3214. if ($mode == 'bynumber') {
  3215. $sql .= ", count(DISTINCT f.rowid)";
  3216. }
  3217. $sql .= " FROM ".$this->db->prefix()."facturedet as d, ".$this->db->prefix()."facture as f, ".$this->db->prefix()."societe as s";
  3218. if ($filteronproducttype >= 0) {
  3219. $sql .= ", ".$this->db->prefix()."product as p";
  3220. }
  3221. if (empty($user->rights->societe->client->voir) && !$socid) {
  3222. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3223. }
  3224. $sql .= " WHERE f.rowid = d.fk_facture";
  3225. if ($this->id > 0) {
  3226. $sql .= " AND d.fk_product = ".((int) $this->id);
  3227. } else {
  3228. $sql .= " AND d.fk_product > 0";
  3229. }
  3230. if ($filteronproducttype >= 0) {
  3231. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3232. }
  3233. $sql .= " AND f.fk_soc = s.rowid";
  3234. $sql .= " AND f.entity IN (".getEntity('invoice').")";
  3235. if (empty($user->rights->societe->client->voir) && !$socid) {
  3236. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3237. }
  3238. if ($socid > 0) {
  3239. $sql .= " AND f.fk_soc = $socid";
  3240. }
  3241. $sql .= $morefilter;
  3242. $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
  3243. $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
  3244. return $this->_get_stats($sql, $mode, $year);
  3245. }
  3246. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3247. /**
  3248. * Return nb of units or supplier invoices in which product is included
  3249. *
  3250. * @param int $socid Limit count on a particular third party id
  3251. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3252. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3253. * @param int $year Year (0=last 12 month, -1=all years)
  3254. * @param string $morefilter More sql filters
  3255. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3256. */
  3257. public function get_nb_achat($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3258. {
  3259. // phpcs:enable
  3260. global $conf;
  3261. global $user;
  3262. $sql = "SELECT sum(d.qty), date_format(f.datef, '%Y%m')";
  3263. if ($mode == 'bynumber') {
  3264. $sql .= ", count(DISTINCT f.rowid)";
  3265. }
  3266. $sql .= " FROM ".$this->db->prefix()."facture_fourn_det as d, ".$this->db->prefix()."facture_fourn as f, ".$this->db->prefix()."societe as s";
  3267. if ($filteronproducttype >= 0) {
  3268. $sql .= ", ".$this->db->prefix()."product as p";
  3269. }
  3270. if (empty($user->rights->societe->client->voir) && !$socid) {
  3271. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3272. }
  3273. $sql .= " WHERE f.rowid = d.fk_facture_fourn";
  3274. if ($this->id > 0) {
  3275. $sql .= " AND d.fk_product = ".((int) $this->id);
  3276. } else {
  3277. $sql .= " AND d.fk_product > 0";
  3278. }
  3279. if ($filteronproducttype >= 0) {
  3280. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3281. }
  3282. $sql .= " AND f.fk_soc = s.rowid";
  3283. $sql .= " AND f.entity IN (".getEntity('facture_fourn').")";
  3284. if (empty($user->rights->societe->client->voir) && !$socid) {
  3285. $sql .= " AND f.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3286. }
  3287. if ($socid > 0) {
  3288. $sql .= " AND f.fk_soc = $socid";
  3289. }
  3290. $sql .= $morefilter;
  3291. $sql .= " GROUP BY date_format(f.datef,'%Y%m')";
  3292. $sql .= " ORDER BY date_format(f.datef,'%Y%m') DESC";
  3293. return $this->_get_stats($sql, $mode, $year);
  3294. }
  3295. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3296. /**
  3297. * Return nb of units in proposals in which product is included
  3298. *
  3299. * @param int $socid Limit count on a particular third party id
  3300. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3301. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3302. * @param int $year Year (0=last 12 month, -1=all years)
  3303. * @param string $morefilter More sql filters
  3304. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3305. */
  3306. public function get_nb_propal($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3307. {
  3308. // phpcs:enable
  3309. global $conf, $user;
  3310. $sql = "SELECT sum(d.qty), date_format(p.datep, '%Y%m')";
  3311. if ($mode == 'bynumber') {
  3312. $sql .= ", count(DISTINCT p.rowid)";
  3313. }
  3314. $sql .= " FROM ".$this->db->prefix()."propaldet as d, ".$this->db->prefix()."propal as p, ".$this->db->prefix()."societe as s";
  3315. if ($filteronproducttype >= 0) {
  3316. $sql .= ", ".$this->db->prefix()."product as prod";
  3317. }
  3318. if (empty($user->rights->societe->client->voir) && !$socid) {
  3319. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3320. }
  3321. $sql .= " WHERE p.rowid = d.fk_propal";
  3322. if ($this->id > 0) {
  3323. $sql .= " AND d.fk_product = ".((int) $this->id);
  3324. } else {
  3325. $sql .= " AND d.fk_product > 0";
  3326. }
  3327. if ($filteronproducttype >= 0) {
  3328. $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
  3329. }
  3330. $sql .= " AND p.fk_soc = s.rowid";
  3331. $sql .= " AND p.entity IN (".getEntity('propal').")";
  3332. if (empty($user->rights->societe->client->voir) && !$socid) {
  3333. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3334. }
  3335. if ($socid > 0) {
  3336. $sql .= " AND p.fk_soc = ".((int) $socid);
  3337. }
  3338. $sql .= $morefilter;
  3339. $sql .= " GROUP BY date_format(p.datep,'%Y%m')";
  3340. $sql .= " ORDER BY date_format(p.datep,'%Y%m') DESC";
  3341. return $this->_get_stats($sql, $mode, $year);
  3342. }
  3343. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3344. /**
  3345. * Return nb of units in proposals in which product is included
  3346. *
  3347. * @param int $socid Limit count on a particular third party id
  3348. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3349. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3350. * @param int $year Year (0=last 12 month, -1=all years)
  3351. * @param string $morefilter More sql filters
  3352. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3353. */
  3354. public function get_nb_propalsupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3355. {
  3356. // phpcs:enable
  3357. global $conf;
  3358. global $user;
  3359. $sql = "SELECT sum(d.qty), date_format(p.date_valid, '%Y%m')";
  3360. if ($mode == 'bynumber') {
  3361. $sql .= ", count(DISTINCT p.rowid)";
  3362. }
  3363. $sql .= " FROM ".$this->db->prefix()."supplier_proposaldet as d, ".$this->db->prefix()."supplier_proposal as p, ".$this->db->prefix()."societe as s";
  3364. if ($filteronproducttype >= 0) {
  3365. $sql .= ", ".$this->db->prefix()."product as prod";
  3366. }
  3367. if (empty($user->rights->societe->client->voir) && !$socid) {
  3368. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3369. }
  3370. $sql .= " WHERE p.rowid = d.fk_supplier_proposal";
  3371. if ($this->id > 0) {
  3372. $sql .= " AND d.fk_product = ".((int) $this->id);
  3373. } else {
  3374. $sql .= " AND d.fk_product > 0";
  3375. }
  3376. if ($filteronproducttype >= 0) {
  3377. $sql .= " AND prod.rowid = d.fk_product AND prod.fk_product_type = ".((int) $filteronproducttype);
  3378. }
  3379. $sql .= " AND p.fk_soc = s.rowid";
  3380. $sql .= " AND p.entity IN (".getEntity('supplier_proposal').")";
  3381. if (empty($user->rights->societe->client->voir) && !$socid) {
  3382. $sql .= " AND p.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3383. }
  3384. if ($socid > 0) {
  3385. $sql .= " AND p.fk_soc = ".((int) $socid);
  3386. }
  3387. $sql .= $morefilter;
  3388. $sql .= " GROUP BY date_format(p.date_valid,'%Y%m')";
  3389. $sql .= " ORDER BY date_format(p.date_valid,'%Y%m') DESC";
  3390. return $this->_get_stats($sql, $mode, $year);
  3391. }
  3392. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3393. /**
  3394. * Return nb of units in orders in which product is included
  3395. *
  3396. * @param int $socid Limit count on a particular third party id
  3397. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3398. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3399. * @param int $year Year (0=last 12 month, -1=all years)
  3400. * @param string $morefilter More sql filters
  3401. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3402. */
  3403. public function get_nb_order($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3404. {
  3405. // phpcs:enable
  3406. global $conf, $user;
  3407. $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
  3408. if ($mode == 'bynumber') {
  3409. $sql .= ", count(DISTINCT c.rowid)";
  3410. }
  3411. $sql .= " FROM ".$this->db->prefix()."commandedet as d, ".$this->db->prefix()."commande as c, ".$this->db->prefix()."societe as s";
  3412. if ($filteronproducttype >= 0) {
  3413. $sql .= ", ".$this->db->prefix()."product as p";
  3414. }
  3415. if (empty($user->rights->societe->client->voir) && !$socid) {
  3416. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3417. }
  3418. $sql .= " WHERE c.rowid = d.fk_commande";
  3419. if ($this->id > 0) {
  3420. $sql .= " AND d.fk_product = ".((int) $this->id);
  3421. } else {
  3422. $sql .= " AND d.fk_product > 0";
  3423. }
  3424. if ($filteronproducttype >= 0) {
  3425. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3426. }
  3427. $sql .= " AND c.fk_soc = s.rowid";
  3428. $sql .= " AND c.entity IN (".getEntity('commande').")";
  3429. if (empty($user->rights->societe->client->voir) && !$socid) {
  3430. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3431. }
  3432. if ($socid > 0) {
  3433. $sql .= " AND c.fk_soc = ".((int) $socid);
  3434. }
  3435. $sql .= $morefilter;
  3436. $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
  3437. $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
  3438. return $this->_get_stats($sql, $mode, $year);
  3439. }
  3440. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3441. /**
  3442. * Return nb of units in orders in which product is included
  3443. *
  3444. * @param int $socid Limit count on a particular third party id
  3445. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3446. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3447. * @param int $year Year (0=last 12 month, -1=all years)
  3448. * @param string $morefilter More sql filters
  3449. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3450. */
  3451. public function get_nb_ordersupplier($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3452. {
  3453. // phpcs:enable
  3454. global $conf, $user;
  3455. $sql = "SELECT sum(d.qty), date_format(c.date_commande, '%Y%m')";
  3456. if ($mode == 'bynumber') {
  3457. $sql .= ", count(DISTINCT c.rowid)";
  3458. }
  3459. $sql .= " FROM ".$this->db->prefix()."commande_fournisseurdet as d, ".$this->db->prefix()."commande_fournisseur as c, ".$this->db->prefix()."societe as s";
  3460. if ($filteronproducttype >= 0) {
  3461. $sql .= ", ".$this->db->prefix()."product as p";
  3462. }
  3463. if (empty($user->rights->societe->client->voir) && !$socid) {
  3464. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3465. }
  3466. $sql .= " WHERE c.rowid = d.fk_commande";
  3467. if ($this->id > 0) {
  3468. $sql .= " AND d.fk_product = ".((int) $this->id);
  3469. } else {
  3470. $sql .= " AND d.fk_product > 0";
  3471. }
  3472. if ($filteronproducttype >= 0) {
  3473. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3474. }
  3475. $sql .= " AND c.fk_soc = s.rowid";
  3476. $sql .= " AND c.entity IN (".getEntity('supplier_order').")";
  3477. if (empty($user->rights->societe->client->voir) && !$socid) {
  3478. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3479. }
  3480. if ($socid > 0) {
  3481. $sql .= " AND c.fk_soc = ".((int) $socid);
  3482. }
  3483. $sql .= $morefilter;
  3484. $sql .= " GROUP BY date_format(c.date_commande,'%Y%m')";
  3485. $sql .= " ORDER BY date_format(c.date_commande,'%Y%m') DESC";
  3486. return $this->_get_stats($sql, $mode, $year);
  3487. }
  3488. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3489. /**
  3490. * Return nb of units in orders in which product is included
  3491. *
  3492. * @param int $socid Limit count on a particular third party id
  3493. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3494. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3495. * @param int $year Year (0=last 12 month, -1=all years)
  3496. * @param string $morefilter More sql filters
  3497. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3498. */
  3499. public function get_nb_contract($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3500. {
  3501. // phpcs:enable
  3502. global $conf, $user;
  3503. $sql = "SELECT sum(d.qty), date_format(c.date_contrat, '%Y%m')";
  3504. if ($mode == 'bynumber') {
  3505. $sql .= ", count(DISTINCT c.rowid)";
  3506. }
  3507. $sql .= " FROM ".$this->db->prefix()."contratdet as d, ".$this->db->prefix()."contrat as c, ".$this->db->prefix()."societe as s";
  3508. if ($filteronproducttype >= 0) {
  3509. $sql .= ", ".$this->db->prefix()."product as p";
  3510. }
  3511. if (empty($user->rights->societe->client->voir) && !$socid) {
  3512. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3513. }
  3514. $sql .= " WHERE c.entity IN (".getEntity('contract').")";
  3515. $sql .= " AND c.rowid = d.fk_contrat";
  3516. if ($this->id > 0) {
  3517. $sql .= " AND d.fk_product = ".((int) $this->id);
  3518. } else {
  3519. $sql .= " AND d.fk_product > 0";
  3520. }
  3521. if ($filteronproducttype >= 0) {
  3522. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3523. }
  3524. $sql .= " AND c.fk_soc = s.rowid";
  3525. if (empty($user->rights->societe->client->voir) && !$socid) {
  3526. $sql .= " AND c.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3527. }
  3528. if ($socid > 0) {
  3529. $sql .= " AND c.fk_soc = ".((int) $socid);
  3530. }
  3531. $sql .= $morefilter;
  3532. $sql .= " GROUP BY date_format(c.date_contrat,'%Y%m')";
  3533. $sql .= " ORDER BY date_format(c.date_contrat,'%Y%m') DESC";
  3534. return $this->_get_stats($sql, $mode, $year);
  3535. }
  3536. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3537. /**
  3538. * Return nb of units in orders in which product is included
  3539. *
  3540. * @param int $socid Limit count on a particular third party id
  3541. * @param string $mode 'byunit'=number of unit, 'bynumber'=nb of entities
  3542. * @param int $filteronproducttype 0=To filter on product only, 1=To filter on services only
  3543. * @param int $year Year (0=last 12 month, -1=all years)
  3544. * @param string $morefilter More sql filters
  3545. * @return array <0 if KO, result[month]=array(valuex,valuey) where month is 0 to 11
  3546. */
  3547. public function get_nb_mos($socid, $mode, $filteronproducttype = -1, $year = 0, $morefilter = '')
  3548. {
  3549. // phpcs:enable
  3550. global $conf, $user;
  3551. $sql = "SELECT sum(d.qty), date_format(d.date_valid, '%Y%m')";
  3552. if ($mode == 'bynumber') {
  3553. $sql .= ", count(DISTINCT d.rowid)";
  3554. }
  3555. $sql .= " FROM ".$this->db->prefix()."mrp_mo as d LEFT JOIN ".$this->db->prefix()."societe as s ON d.fk_soc = s.rowid";
  3556. if ($filteronproducttype >= 0) {
  3557. $sql .= ", ".$this->db->prefix()."product as p";
  3558. }
  3559. if (empty($user->rights->societe->client->voir) && !$socid) {
  3560. $sql .= ", ".$this->db->prefix()."societe_commerciaux as sc";
  3561. }
  3562. $sql .= " WHERE d.entity IN (".getEntity('mo').")";
  3563. $sql .= " AND d.status > 0";
  3564. if ($this->id > 0) {
  3565. $sql .= " AND d.fk_product = ".((int) $this->id);
  3566. } else {
  3567. $sql .= " AND d.fk_product > 0";
  3568. }
  3569. if ($filteronproducttype >= 0) {
  3570. $sql .= " AND p.rowid = d.fk_product AND p.fk_product_type = ".((int) $filteronproducttype);
  3571. }
  3572. if (empty($user->rights->societe->client->voir) && !$socid) {
  3573. $sql .= " AND d.fk_soc = sc.fk_soc AND sc.fk_user = ".((int) $user->id);
  3574. }
  3575. if ($socid > 0) {
  3576. $sql .= " AND d.fk_soc = ".((int) $socid);
  3577. }
  3578. $sql .= $morefilter;
  3579. $sql .= " GROUP BY date_format(d.date_valid,'%Y%m')";
  3580. $sql .= " ORDER BY date_format(d.date_valid,'%Y%m') DESC";
  3581. return $this->_get_stats($sql, $mode, $year);
  3582. }
  3583. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3584. /**
  3585. * Link a product/service to a parent product/service
  3586. *
  3587. * @param int $id_pere Id of parent product/service
  3588. * @param int $id_fils Id of child product/service
  3589. * @param int $qty Quantity
  3590. * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease
  3591. * @return int < 0 if KO, > 0 if OK
  3592. */
  3593. public function add_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
  3594. {
  3595. // phpcs:enable
  3596. // Clean parameters
  3597. if (!is_numeric($id_pere)) {
  3598. $id_pere = 0;
  3599. }
  3600. if (!is_numeric($id_fils)) {
  3601. $id_fils = 0;
  3602. }
  3603. if (!is_numeric($incdec)) {
  3604. $incdec = 0;
  3605. }
  3606. $result = $this->del_sousproduit($id_pere, $id_fils);
  3607. if ($result < 0) {
  3608. return $result;
  3609. }
  3610. // Check not already father of id_pere (to avoid father -> child -> father links)
  3611. $sql = "SELECT fk_product_pere from ".$this->db->prefix()."product_association";
  3612. $sql .= " WHERE fk_product_pere = ".((int) $id_fils)." AND fk_product_fils = ".((int) $id_pere);
  3613. if (!$this->db->query($sql)) {
  3614. dol_print_error($this->db);
  3615. return -1;
  3616. } else {
  3617. //Selection of the highest row
  3618. $sql = "SELECT MAX(rang) as max_rank FROM ".$this->db->prefix()."product_association";
  3619. $sql .= " WHERE fk_product_pere = ".((int) $id_pere);
  3620. $resql = $this->db->query($sql);
  3621. if ($resql > 0) {
  3622. $obj = $this->db->fetch_object($resql);
  3623. $rank = $obj->max_rank + 1;
  3624. //Addition of a product with the highest rank +1
  3625. $sql = "INSERT INTO ".$this->db->prefix()."product_association(fk_product_pere,fk_product_fils,qty,incdec,rang)";
  3626. $sql .= " VALUES (".((int) $id_pere).", ".((int) $id_fils).", ".price2num($qty, 'MS').", ".price2num($incdec, 'MS').", ".((int) $rank).")";
  3627. if (! $this->db->query($sql)) {
  3628. dol_print_error($this->db);
  3629. return -1;
  3630. } else {
  3631. return 1;
  3632. }
  3633. } else {
  3634. dol_print_error($this->db);
  3635. return -1;
  3636. }
  3637. }
  3638. }
  3639. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3640. /**
  3641. * Modify composed product
  3642. *
  3643. * @param int $id_pere Id of parent product/service
  3644. * @param int $id_fils Id of child product/service
  3645. * @param int $qty Quantity
  3646. * @param int $incdec 1=Increase/decrease stock of child when parent stock increase/decrease
  3647. * @return int < 0 if KO, > 0 if OK
  3648. */
  3649. public function update_sousproduit($id_pere, $id_fils, $qty, $incdec = 1)
  3650. {
  3651. // phpcs:enable
  3652. // Clean parameters
  3653. if (!is_numeric($id_pere)) {
  3654. $id_pere = 0;
  3655. }
  3656. if (!is_numeric($id_fils)) {
  3657. $id_fils = 0;
  3658. }
  3659. if (!is_numeric($incdec)) {
  3660. $incdec = 1;
  3661. }
  3662. if (!is_numeric($qty)) {
  3663. $qty = 1;
  3664. }
  3665. $sql = 'UPDATE '.$this->db->prefix().'product_association SET ';
  3666. $sql .= 'qty = '.price2num($qty, 'MS');
  3667. $sql .= ',incdec = '.price2num($incdec, 'MS');
  3668. $sql .= ' WHERE fk_product_pere = '.((int) $id_pere).' AND fk_product_fils = '.((int) $id_fils);
  3669. if (!$this->db->query($sql)) {
  3670. dol_print_error($this->db);
  3671. return -1;
  3672. } else {
  3673. return 1;
  3674. }
  3675. }
  3676. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3677. /**
  3678. * Remove a link between a subproduct and a parent product/service
  3679. *
  3680. * @param int $fk_parent Id of parent product (child will no more be linked to it)
  3681. * @param int $fk_child Id of child product
  3682. * @return int < 0 if KO, > 0 if OK
  3683. */
  3684. public function del_sousproduit($fk_parent, $fk_child)
  3685. {
  3686. // phpcs:enable
  3687. if (!is_numeric($fk_parent)) {
  3688. $fk_parent = 0;
  3689. }
  3690. if (!is_numeric($fk_child)) {
  3691. $fk_child = 0;
  3692. }
  3693. $sql = "DELETE FROM ".$this->db->prefix()."product_association";
  3694. $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
  3695. $sql .= " AND fk_product_fils = ".((int) $fk_child);
  3696. dol_syslog(get_class($this).'::del_sousproduit', LOG_DEBUG);
  3697. if (!$this->db->query($sql)) {
  3698. dol_print_error($this->db);
  3699. return -1;
  3700. }
  3701. // Updated ranks so that none are missing
  3702. $sqlrank = "SELECT rowid, rang FROM ".$this->db->prefix()."product_association";
  3703. $sqlrank.= " WHERE fk_product_pere = ".((int) $fk_parent);
  3704. $sqlrank.= " ORDER BY rang";
  3705. $resqlrank = $this->db->query($sqlrank);
  3706. if ($resqlrank) {
  3707. $cpt = 0;
  3708. while ($objrank = $this->db->fetch_object($resqlrank)) {
  3709. $cpt++;
  3710. $sql = "UPDATE ".$this->db->prefix()."product_association";
  3711. $sql.= " SET rang = ".((int) $cpt);
  3712. $sql.= " WHERE rowid = ".((int) $objrank->rowid);
  3713. if (! $this->db->query($sql)) {
  3714. dol_print_error($this->db);
  3715. return -1;
  3716. }
  3717. }
  3718. }
  3719. return 1;
  3720. }
  3721. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3722. /**
  3723. * Check if it is a sub-product into a kit
  3724. *
  3725. * @param int $fk_parent Id of parent kit product
  3726. * @param int $fk_child Id of child product
  3727. * @return int <0 if KO, >0 if OK
  3728. */
  3729. public function is_sousproduit($fk_parent, $fk_child)
  3730. {
  3731. // phpcs:enable
  3732. $sql = "SELECT fk_product_pere, qty, incdec";
  3733. $sql .= " FROM ".$this->db->prefix()."product_association";
  3734. $sql .= " WHERE fk_product_pere = ".((int) $fk_parent);
  3735. $sql .= " AND fk_product_fils = ".((int) $fk_child);
  3736. $result = $this->db->query($sql);
  3737. if ($result) {
  3738. $num = $this->db->num_rows($result);
  3739. if ($num > 0) {
  3740. $obj = $this->db->fetch_object($result);
  3741. $this->is_sousproduit_qty = $obj->qty;
  3742. $this->is_sousproduit_incdec = $obj->incdec;
  3743. return true;
  3744. } else {
  3745. return false;
  3746. }
  3747. } else {
  3748. dol_print_error($this->db);
  3749. return -1;
  3750. }
  3751. }
  3752. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3753. /**
  3754. * Add a supplier price for the product.
  3755. * Note: Duplicate ref is accepted for different quantity only, or for different companies.
  3756. *
  3757. * @param User $user User that make link
  3758. * @param int $id_fourn Supplier id
  3759. * @param string $ref_fourn Supplier ref
  3760. * @param float $quantity Quantity minimum for price
  3761. * @return int < 0 if KO, 0 if link already exists for this product, > 0 if OK
  3762. */
  3763. public function add_fournisseur($user, $id_fourn, $ref_fourn, $quantity)
  3764. {
  3765. // phpcs:enable
  3766. global $conf;
  3767. $now = dol_now();
  3768. dol_syslog(get_class($this)."::add_fournisseur id_fourn = ".$id_fourn." ref_fourn=".$ref_fourn." quantity=".$quantity, LOG_DEBUG);
  3769. // Clean parameters
  3770. $quantity = price2num($quantity, 'MS');
  3771. if ($ref_fourn) {
  3772. $sql = "SELECT rowid, fk_product";
  3773. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  3774. $sql .= " WHERE fk_soc = ".((int) $id_fourn);
  3775. $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
  3776. $sql .= " AND fk_product <> ".((int) $this->id);
  3777. $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
  3778. $resql = $this->db->query($sql);
  3779. if ($resql) {
  3780. $obj = $this->db->fetch_object($resql);
  3781. if ($obj) {
  3782. // If the supplier ref already exists but for another product (duplicate ref is accepted for different quantity only or different companies)
  3783. $this->product_id_already_linked = $obj->fk_product;
  3784. return -3;
  3785. }
  3786. $this->db->free($resql);
  3787. }
  3788. }
  3789. $sql = "SELECT rowid";
  3790. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  3791. $sql .= " WHERE fk_soc = ".((int) $id_fourn);
  3792. if ($ref_fourn) {
  3793. $sql .= " AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
  3794. } else {
  3795. $sql .= " AND (ref_fourn = '' OR ref_fourn IS NULL)";
  3796. }
  3797. $sql .= " AND quantity = ".((float) $quantity);
  3798. $sql .= " AND fk_product = ".((int) $this->id);
  3799. $sql .= " AND entity IN (".getEntity('productsupplierprice').")";
  3800. $resql = $this->db->query($sql);
  3801. if ($resql) {
  3802. $obj = $this->db->fetch_object($resql);
  3803. // The reference supplier does not exist, we create it for this product.
  3804. if (empty($obj)) {
  3805. $sql = "INSERT INTO ".$this->db->prefix()."product_fournisseur_price(";
  3806. $sql .= "datec";
  3807. $sql .= ", entity";
  3808. $sql .= ", fk_product";
  3809. $sql .= ", fk_soc";
  3810. $sql .= ", ref_fourn";
  3811. $sql .= ", quantity";
  3812. $sql .= ", fk_user";
  3813. $sql .= ", tva_tx";
  3814. $sql .= ") VALUES (";
  3815. $sql .= "'".$this->db->idate($now)."'";
  3816. $sql .= ", ".$conf->entity;
  3817. $sql .= ", ".$this->id;
  3818. $sql .= ", ".$id_fourn;
  3819. $sql .= ", '".$this->db->escape($ref_fourn)."'";
  3820. $sql .= ", ".$quantity;
  3821. $sql .= ", ".$user->id;
  3822. $sql .= ", 0";
  3823. $sql .= ")";
  3824. if ($this->db->query($sql)) {
  3825. $this->product_fourn_price_id = $this->db->last_insert_id($this->db->prefix()."product_fournisseur_price");
  3826. return 1;
  3827. } else {
  3828. $this->error = $this->db->lasterror();
  3829. return -1;
  3830. }
  3831. } else {
  3832. // If the supplier price already exists for this product and quantity
  3833. $this->product_fourn_price_id = $obj->rowid;
  3834. return 0;
  3835. }
  3836. } else {
  3837. $this->error = $this->db->lasterror();
  3838. return -2;
  3839. }
  3840. }
  3841. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3842. /**
  3843. * Return list of suppliers providing the product or service
  3844. *
  3845. * @return array Array of vendor ids
  3846. */
  3847. public function list_suppliers()
  3848. {
  3849. // phpcs:enable
  3850. global $conf;
  3851. $list = array();
  3852. $sql = "SELECT DISTINCT p.fk_soc";
  3853. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price as p";
  3854. $sql .= " WHERE p.fk_product = ".((int) $this->id);
  3855. $sql .= " AND p.entity = ".((int) $conf->entity);
  3856. $result = $this->db->query($sql);
  3857. if ($result) {
  3858. $num = $this->db->num_rows($result);
  3859. $i = 0;
  3860. while ($i < $num) {
  3861. $obj = $this->db->fetch_object($result);
  3862. $list[$i] = $obj->fk_soc;
  3863. $i++;
  3864. }
  3865. }
  3866. return $list;
  3867. }
  3868. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3869. /**
  3870. * Recopie les prix d'un produit/service sur un autre
  3871. *
  3872. * @param int $fromId Id product source
  3873. * @param int $toId Id product target
  3874. * @return int < 0 if KO, > 0 if OK
  3875. */
  3876. public function clone_price($fromId, $toId)
  3877. {
  3878. global $conf, $user;
  3879. $now = dol_now();
  3880. $this->db->begin();
  3881. // prices
  3882. $sql = "INSERT INTO ".$this->db->prefix()."product_price (";
  3883. $sql .= " entity";
  3884. $sql .= ", fk_product";
  3885. $sql .= ", date_price";
  3886. $sql .= ", price_level";
  3887. $sql .= ", price";
  3888. $sql .= ", price_ttc";
  3889. $sql .= ", price_min";
  3890. $sql .= ", price_min_ttc";
  3891. $sql .= ", price_base_type";
  3892. $sql .= ", default_vat_code";
  3893. $sql .= ", tva_tx";
  3894. $sql .= ", recuperableonly";
  3895. $sql .= ", localtax1_tx";
  3896. $sql .= ", localtax1_type";
  3897. $sql .= ", localtax2_tx";
  3898. $sql .= ", localtax2_type";
  3899. $sql .= ", fk_user_author";
  3900. $sql .= ", tosell";
  3901. $sql .= ", price_by_qty";
  3902. $sql .= ", fk_price_expression";
  3903. $sql .= ", fk_multicurrency";
  3904. $sql .= ", multicurrency_code";
  3905. $sql .= ", multicurrency_tx";
  3906. $sql .= ", multicurrency_price";
  3907. $sql .= ", multicurrency_price_ttc";
  3908. $sql .= ")";
  3909. $sql .= " SELECT";
  3910. $sql .= " entity";
  3911. $sql .= ", ".$toId;
  3912. $sql .= ", '".$this->db->idate($now)."'";
  3913. $sql .= ", price_level";
  3914. $sql .= ", price";
  3915. $sql .= ", price_ttc";
  3916. $sql .= ", price_min";
  3917. $sql .= ", price_min_ttc";
  3918. $sql .= ", price_base_type";
  3919. $sql .= ", default_vat_code";
  3920. $sql .= ", tva_tx";
  3921. $sql .= ", recuperableonly";
  3922. $sql .= ", localtax1_tx";
  3923. $sql .= ", localtax1_type";
  3924. $sql .= ", localtax2_tx";
  3925. $sql .= ", localtax2_type";
  3926. $sql .= ", ".$user->id;
  3927. $sql .= ", tosell";
  3928. $sql .= ", price_by_qty";
  3929. $sql .= ", fk_price_expression";
  3930. $sql .= ", fk_multicurrency";
  3931. $sql .= ", multicurrency_code";
  3932. $sql .= ", multicurrency_tx";
  3933. $sql .= ", multicurrency_price";
  3934. $sql .= ", multicurrency_price_ttc";
  3935. $sql .= " FROM ".$this->db->prefix()."product_price";
  3936. $sql .= " WHERE fk_product = ".((int) $fromId);
  3937. $sql .= " ORDER BY date_price DESC";
  3938. if ($conf->global->PRODUIT_MULTIPRICES_LIMIT > 0) {
  3939. $sql .= " LIMIT ".$conf->global->PRODUIT_MULTIPRICES_LIMIT;
  3940. }
  3941. dol_syslog(__METHOD__, LOG_DEBUG);
  3942. $resql = $this->db->query($sql);
  3943. if (!$resql) {
  3944. $this->db->rollback();
  3945. return -1;
  3946. }
  3947. $this->db->commit();
  3948. return 1;
  3949. }
  3950. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3951. /**
  3952. * Clone links between products
  3953. *
  3954. * @param int $fromId Product id
  3955. * @param int $toId Product id
  3956. * @return int <0 if KO, >0 if OK
  3957. */
  3958. public function clone_associations($fromId, $toId)
  3959. {
  3960. // phpcs:enable
  3961. $this->db->begin();
  3962. $sql = 'INSERT INTO '.$this->db->prefix().'product_association (fk_product_pere, fk_product_fils, qty)';
  3963. $sql .= " SELECT ".$toId.", fk_product_fils, qty FROM ".$this->db->prefix()."product_association";
  3964. $sql .= " WHERE fk_product_pere = ".((int) $fromId);
  3965. dol_syslog(get_class($this).'::clone_association', LOG_DEBUG);
  3966. if (!$this->db->query($sql)) {
  3967. $this->db->rollback();
  3968. return -1;
  3969. }
  3970. $this->db->commit();
  3971. return 1;
  3972. }
  3973. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  3974. /**
  3975. * Recopie les fournisseurs et prix fournisseurs d'un produit/service sur un autre
  3976. *
  3977. * @param int $fromId Id produit source
  3978. * @param int $toId Id produit cible
  3979. * @return int < 0 si erreur, > 0 si ok
  3980. */
  3981. public function clone_fournisseurs($fromId, $toId)
  3982. {
  3983. // phpcs:enable
  3984. $this->db->begin();
  3985. $now = dol_now();
  3986. // les fournisseurs
  3987. /*$sql = "INSERT ".$this->db->prefix()."product_fournisseur ("
  3988. . " datec, fk_product, fk_soc, ref_fourn, fk_user_author )"
  3989. . " SELECT '".$this->db->idate($now)."', ".$toId.", fk_soc, ref_fourn, fk_user_author"
  3990. . " FROM ".$this->db->prefix()."product_fournisseur"
  3991. . " WHERE fk_product = ".((int) $fromId);
  3992. if ( ! $this->db->query($sql ) )
  3993. {
  3994. $this->db->rollback();
  3995. return -1;
  3996. }*/
  3997. // les prix de fournisseurs.
  3998. $sql = "INSERT ".$this->db->prefix()."product_fournisseur_price (";
  3999. $sql .= " datec, fk_product, fk_soc, price, quantity, fk_user)";
  4000. $sql .= " SELECT '".$this->db->idate($now)."', ".((int) $toId).", fk_soc, price, quantity, fk_user";
  4001. $sql .= " FROM ".$this->db->prefix()."product_fournisseur_price";
  4002. $sql .= " WHERE fk_product = ".((int) $fromId);
  4003. dol_syslog(get_class($this).'::clone_fournisseurs', LOG_DEBUG);
  4004. $resql = $this->db->query($sql);
  4005. if (!$resql) {
  4006. $this->db->rollback();
  4007. return -1;
  4008. } else {
  4009. $this->db->commit();
  4010. return 1;
  4011. }
  4012. }
  4013. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4014. /**
  4015. * Fonction recursive uniquement utilisee par get_arbo_each_prod, recompose l'arborescence des sousproduits
  4016. * Define value of this->res
  4017. *
  4018. * @param array $prod Products array
  4019. * @param string $compl_path Directory path of parents to add before
  4020. * @param int $multiply Because each sublevel must be multiplicated by parent nb
  4021. * @param int $level Init level
  4022. * @param int $id_parent Id parent
  4023. * @param int $ignore_stock_load Ignore stock load
  4024. * @return void
  4025. */
  4026. public function fetch_prod_arbo($prod, $compl_path = '', $multiply = 1, $level = 1, $id_parent = 0, $ignore_stock_load = 0)
  4027. {
  4028. // phpcs:enable
  4029. global $conf, $langs;
  4030. $tmpproduct = null;
  4031. //var_dump($prod);
  4032. foreach ($prod as $id_product => $desc_pere) { // $id_product is 0 (first call starting with root top) or an id of a sub_product
  4033. if (is_array($desc_pere)) { // If desc_pere is an array, this means it's a child
  4034. $id = (!empty($desc_pere[0]) ? $desc_pere[0] : '');
  4035. $nb = (!empty($desc_pere[1]) ? $desc_pere[1] : '');
  4036. $type = (!empty($desc_pere[2]) ? $desc_pere[2] : '');
  4037. $label = (!empty($desc_pere[3]) ? $desc_pere[3] : '');
  4038. $incdec = (!empty($desc_pere[4]) ? $desc_pere[4] : 0);
  4039. if ($multiply < 1) {
  4040. $multiply = 1;
  4041. }
  4042. //print "XXX We add id=".$id." - label=".$label." - nb=".$nb." - multiply=".$multiply." fullpath=".$compl_path.$label."\n";
  4043. if (is_null($tmpproduct)) {
  4044. $tmpproduct = new Product($this->db); // So we initialize tmpproduct only once for all loop.
  4045. }
  4046. $tmpproduct->fetch($id); // Load product to get ->ref
  4047. if (empty($ignore_stock_load) && ($tmpproduct->isProduct() || !empty($conf->global->STOCK_SUPPORTS_SERVICES))) {
  4048. $tmpproduct->load_stock('nobatch,novirtual'); // Load stock to get true ->stock_reel
  4049. }
  4050. $this->res[] = array(
  4051. 'id'=>$id, // Id product
  4052. 'id_parent'=>$id_parent,
  4053. 'ref'=>$tmpproduct->ref, // Ref product
  4054. 'nb'=>$nb, // Nb of units that compose parent product
  4055. 'nb_total'=>$nb * $multiply, // Nb of units for all nb of product
  4056. 'stock'=>$tmpproduct->stock_reel, // Stock
  4057. 'stock_alert'=>$tmpproduct->seuil_stock_alerte, // Stock alert
  4058. 'label'=>$label,
  4059. 'fullpath'=>$compl_path.$label, // Label
  4060. 'type'=>$type, // Nb of units that compose parent product
  4061. 'desiredstock'=>$tmpproduct->desiredstock,
  4062. 'level'=>$level,
  4063. 'incdec'=>$incdec,
  4064. 'entity'=>$tmpproduct->entity
  4065. );
  4066. // Recursive call if there is childs to child
  4067. if (is_array($desc_pere['childs'])) {
  4068. //print 'YYY We go down for '.$desc_pere[3]." -> \n";
  4069. $this->fetch_prod_arbo($desc_pere['childs'], $compl_path.$desc_pere[3]." -> ", $desc_pere[1] * $multiply, $level + 1, $id, $ignore_stock_load);
  4070. }
  4071. }
  4072. }
  4073. }
  4074. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4075. /**
  4076. * Build the tree of subproducts into an array ->res and return it.
  4077. * this->sousprods must have been loaded by this->get_sousproduits_arbo()
  4078. *
  4079. * @param int $multiply Because each sublevel must be multiplicated by parent nb
  4080. * @param int $ignore_stock_load Ignore stock load
  4081. * @return array $this->res
  4082. */
  4083. public function get_arbo_each_prod($multiply = 1, $ignore_stock_load = 0)
  4084. {
  4085. // phpcs:enable
  4086. $this->res = array();
  4087. if (isset($this->sousprods) && is_array($this->sousprods)) {
  4088. foreach ($this->sousprods as $prod_name => $desc_product) {
  4089. if (is_array($desc_product)) {
  4090. $this->fetch_prod_arbo($desc_product, "", $multiply, 1, $this->id, $ignore_stock_load);
  4091. }
  4092. }
  4093. }
  4094. //var_dump($this->res);
  4095. return $this->res;
  4096. }
  4097. /**
  4098. * Count all parent and children products for current product (first level only)
  4099. *
  4100. * @param int $mode 0=Both parent and child, -1=Parents only, 1=Children only
  4101. * @return int Nb of father + child
  4102. * @see getFather(), get_sousproduits_arbo()
  4103. */
  4104. public function hasFatherOrChild($mode = 0)
  4105. {
  4106. $nb = 0;
  4107. $sql = "SELECT COUNT(pa.rowid) as nb";
  4108. $sql .= " FROM ".$this->db->prefix()."product_association as pa";
  4109. if ($mode == 0) {
  4110. $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id)." OR pa.fk_product_pere = ".((int) $this->id);
  4111. } elseif ($mode == -1) {
  4112. $sql .= " WHERE pa.fk_product_fils = ".((int) $this->id); // We are a child, so we found lines that link to parents (can have several parents)
  4113. } elseif ($mode == 1) {
  4114. $sql .= " WHERE pa.fk_product_pere = ".((int) $this->id); // We are a parent, so we found lines that link to children (can have several children)
  4115. }
  4116. $resql = $this->db->query($sql);
  4117. if ($resql) {
  4118. $obj = $this->db->fetch_object($resql);
  4119. if ($obj) {
  4120. $nb = $obj->nb;
  4121. }
  4122. } else {
  4123. return -1;
  4124. }
  4125. return $nb;
  4126. }
  4127. /**
  4128. * Return if a product has variants or not
  4129. *
  4130. * @return int Number of variants
  4131. */
  4132. public function hasVariants()
  4133. {
  4134. $nb = 0;
  4135. $sql = "SELECT count(rowid) as nb FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_parent = ".((int) $this->id);
  4136. $sql .= " AND entity IN (".getEntity('product').")";
  4137. $resql = $this->db->query($sql);
  4138. if ($resql) {
  4139. $obj = $this->db->fetch_object($resql);
  4140. if ($obj) {
  4141. $nb = $obj->nb;
  4142. }
  4143. }
  4144. return $nb;
  4145. }
  4146. /**
  4147. * Return if loaded product is a variant
  4148. *
  4149. * @return int
  4150. */
  4151. public function isVariant()
  4152. {
  4153. global $conf;
  4154. if (!empty($conf->variants->enabled)) {
  4155. $sql = "SELECT rowid FROM ".$this->db->prefix()."product_attribute_combination WHERE fk_product_child = ".((int) $this->id)." AND entity IN (".getEntity('product').")";
  4156. $query = $this->db->query($sql);
  4157. if ($query) {
  4158. if (!$this->db->num_rows($query)) {
  4159. return false;
  4160. }
  4161. return true;
  4162. } else {
  4163. dol_print_error($this->db);
  4164. return -1;
  4165. }
  4166. } else {
  4167. return false;
  4168. }
  4169. }
  4170. /**
  4171. * Return all parent products for current product (first level only)
  4172. *
  4173. * @return array Array of product
  4174. * @see hasFatherOrChild()
  4175. */
  4176. public function getFather()
  4177. {
  4178. $sql = "SELECT p.rowid, p.label as label, p.ref as ref, pa.fk_product_pere as id, p.fk_product_type, pa.qty, pa.incdec, p.entity";
  4179. $sql .= ", p.tosell as status, p.tobuy as status_buy";
  4180. $sql .= " FROM ".$this->db->prefix()."product_association as pa,";
  4181. $sql .= " ".$this->db->prefix()."product as p";
  4182. $sql .= " WHERE p.rowid = pa.fk_product_pere";
  4183. $sql .= " AND pa.fk_product_fils = ".((int) $this->id);
  4184. $res = $this->db->query($sql);
  4185. if ($res) {
  4186. $prods = array();
  4187. while ($record = $this->db->fetch_array($res)) {
  4188. // $record['id'] = $record['rowid'] = id of father
  4189. $prods[$record['id']]['id'] = $record['rowid'];
  4190. $prods[$record['id']]['ref'] = $record['ref'];
  4191. $prods[$record['id']]['label'] = $record['label'];
  4192. $prods[$record['id']]['qty'] = $record['qty'];
  4193. $prods[$record['id']]['incdec'] = $record['incdec'];
  4194. $prods[$record['id']]['fk_product_type'] = $record['fk_product_type'];
  4195. $prods[$record['id']]['entity'] = $record['entity'];
  4196. $prods[$record['id']]['status'] = $record['status'];
  4197. $prods[$record['id']]['status_buy'] = $record['status_buy'];
  4198. }
  4199. return $prods;
  4200. } else {
  4201. dol_print_error($this->db);
  4202. return -1;
  4203. }
  4204. }
  4205. /**
  4206. * Return childs of product $id
  4207. *
  4208. * @param int $id Id of product to search childs of
  4209. * @param int $firstlevelonly Return only direct child
  4210. * @param int $level Level of recursing call (start to 1)
  4211. * @return array Return array(prodid=>array(0=prodid, 1=>qty, 2=>product type, 3=>label, 4=>incdec, 5=>product ref)
  4212. */
  4213. public function getChildsArbo($id, $firstlevelonly = 0, $level = 1)
  4214. {
  4215. global $alreadyfound;
  4216. if (empty($id)) {
  4217. return array();
  4218. }
  4219. $sql = "SELECT p.rowid, p.ref, p.label as label, p.fk_product_type,";
  4220. $sql .= " pa.qty as qty, pa.fk_product_fils as id, pa.incdec,";
  4221. $sql .= " pa.rowid as fk_association, pa.rang";
  4222. $sql .= " FROM ".$this->db->prefix()."product as p,";
  4223. $sql .= " ".$this->db->prefix()."product_association as pa";
  4224. $sql .= " WHERE p.rowid = pa.fk_product_fils";
  4225. $sql .= " AND pa.fk_product_pere = ".((int) $id);
  4226. $sql .= " AND pa.fk_product_fils <> ".((int) $id); // This should not happens, it is to avoid infinite loop if it happens
  4227. $sql.= " ORDER BY pa.rang";
  4228. dol_syslog(get_class($this).'::getChildsArbo id='.$id.' level='.$level, LOG_DEBUG);
  4229. if ($level == 1) {
  4230. $alreadyfound = array($id=>1); // We init array of found object to start of tree, so if we found it later (should not happened), we stop immediatly
  4231. }
  4232. // Protection against infinite loop
  4233. if ($level > 30) {
  4234. return array();
  4235. }
  4236. $res = $this->db->query($sql);
  4237. if ($res) {
  4238. $prods = array();
  4239. while ($rec = $this->db->fetch_array($res)) {
  4240. if (!empty($alreadyfound[$rec['rowid']])) {
  4241. dol_syslog(get_class($this).'::getChildsArbo the product id='.$rec['rowid'].' was already found at a higher level in tree. We discard to avoid infinite loop', LOG_WARNING);
  4242. continue;
  4243. }
  4244. $alreadyfound[$rec['rowid']] = 1;
  4245. $prods[$rec['rowid']] = array(
  4246. 0=>$rec['rowid'],
  4247. 1=>$rec['qty'],
  4248. 2=>$rec['fk_product_type'],
  4249. 3=>$this->db->escape($rec['label']),
  4250. 4=>$rec['incdec'],
  4251. 5=>$rec['ref'],
  4252. 6=>$rec['fk_association'],
  4253. 7=>$rec['rang']
  4254. );
  4255. //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty'],2=>$rec['fk_product_type']);
  4256. //$prods[$this->db->escape($rec['label'])]= array(0=>$rec['id'],1=>$rec['qty']);
  4257. if (empty($firstlevelonly)) {
  4258. $listofchilds = $this->getChildsArbo($rec['rowid'], 0, $level + 1);
  4259. foreach ($listofchilds as $keyChild => $valueChild) {
  4260. $prods[$rec['rowid']]['childs'][$keyChild] = $valueChild;
  4261. }
  4262. }
  4263. }
  4264. return $prods;
  4265. } else {
  4266. dol_print_error($this->db);
  4267. return -1;
  4268. }
  4269. }
  4270. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4271. /**
  4272. * Return tree of all subproducts for product. Tree contains array of array(0=prodid, 1=>qty, 2=>product type, 3=>label, 4=>incdec, 5=>product ref)
  4273. * Set this->sousprods
  4274. *
  4275. * @return void
  4276. */
  4277. public function get_sousproduits_arbo()
  4278. {
  4279. // phpcs:enable
  4280. $parent = array();
  4281. foreach ($this->getChildsArbo($this->id) as $keyChild => $valueChild) { // Warning. getChildsArbo can call getChildsArbo recursively. Starting point is $value[0]=id of product
  4282. $parent[$this->label][$keyChild] = $valueChild;
  4283. }
  4284. foreach ($parent as $key => $value) { // key=label, value is array of childs
  4285. $this->sousprods[$key] = $value;
  4286. }
  4287. }
  4288. /**
  4289. * Return clicable link of object (with eventually picto)
  4290. *
  4291. * @param int $withpicto Add picto into link
  4292. * @param string $option Where point the link ('stock', 'composition', 'category', 'supplier', '')
  4293. * @param int $maxlength Maxlength of ref
  4294. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  4295. * @param int $notooltip No tooltip
  4296. * @return string String with URL
  4297. */
  4298. public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0)
  4299. {
  4300. global $conf, $langs, $hookmanager;
  4301. include_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
  4302. $result = ''; $label = '';
  4303. $newref = $this->ref;
  4304. if ($maxlength) {
  4305. $newref = dol_trunc($newref, $maxlength, 'middle');
  4306. }
  4307. if (!empty($this->entity)) {
  4308. $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
  4309. if ($this->nbphoto > 0) {
  4310. $label .= '<div class="photointooltip floatright">';
  4311. $label .= $tmpphoto;
  4312. $label .= '</div>';
  4313. //$label .= '<div style="clear: both;"></div>';
  4314. }
  4315. }
  4316. if ($this->type == Product::TYPE_PRODUCT) {
  4317. $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
  4318. } elseif ($this->type == Product::TYPE_SERVICE) {
  4319. $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
  4320. }
  4321. if (isset($this->status) && isset($this->status_buy)) {
  4322. $label .= ' '.$this->getLibStatut(5, 0);
  4323. $label .= ' '.$this->getLibStatut(5, 1);
  4324. }
  4325. if (!empty($this->ref)) {
  4326. $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.$this->ref;
  4327. }
  4328. if (!empty($this->label)) {
  4329. $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
  4330. }
  4331. if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  4332. if (!empty($conf->productbatch->enabled)) {
  4333. $langs->load("productbatch");
  4334. $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
  4335. }
  4336. }
  4337. if (!empty($conf->barcode->enabled)) {
  4338. $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
  4339. }
  4340. if ($this->type == Product::TYPE_PRODUCT) {
  4341. if ($this->weight) {
  4342. $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
  4343. }
  4344. $labelsize = "";
  4345. if ($this->length) {
  4346. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
  4347. }
  4348. if ($this->width) {
  4349. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
  4350. }
  4351. if ($this->height) {
  4352. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
  4353. }
  4354. if ($labelsize) {
  4355. $label .= "<br>".$labelsize;
  4356. }
  4357. $labelsurfacevolume = "";
  4358. if ($this->surface) {
  4359. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
  4360. }
  4361. if ($this->volume) {
  4362. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
  4363. }
  4364. if ($labelsurfacevolume) {
  4365. $label .= "<br>".$labelsurfacevolume;
  4366. }
  4367. }
  4368. if (!empty($this->pmp) && $this->pmp) {
  4369. $label .= "<br><b>".$langs->trans("PMPValue").'</b>: '.price($this->pmp, 0, '', 1, -1, -1, $conf->currency);
  4370. }
  4371. if (!empty($conf->accounting->enabled) && $this->status) {
  4372. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  4373. $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
  4374. $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
  4375. $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
  4376. }
  4377. if (!empty($conf->accounting->enabled) && $this->status_buy) {
  4378. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  4379. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
  4380. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
  4381. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
  4382. }
  4383. $linkclose = '';
  4384. if (empty($notooltip)) {
  4385. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  4386. $label = $langs->trans("ShowProduct");
  4387. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  4388. }
  4389. $linkclose .= ' title="'.dol_escape_htmltag($label, 1, 1).'"';
  4390. $linkclose .= ' class="nowraponall classfortooltip"';
  4391. } else {
  4392. $linkclose = ' class="nowraponall"';
  4393. }
  4394. if ($option == 'supplier' || $option == 'category') {
  4395. $url = DOL_URL_ROOT.'/product/fournisseurs.php?id='.$this->id;
  4396. } elseif ($option == 'stock') {
  4397. $url = DOL_URL_ROOT.'/product/stock/product.php?id='.$this->id;
  4398. } elseif ($option == 'composition') {
  4399. $url = DOL_URL_ROOT.'/product/composition/card.php?id='.$this->id;
  4400. } else {
  4401. $url = DOL_URL_ROOT.'/product/card.php?id='.$this->id;
  4402. }
  4403. if ($option !== 'nolink') {
  4404. // Add param to save lastsearch_values or not
  4405. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  4406. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  4407. $add_save_lastsearch_values = 1;
  4408. }
  4409. if ($add_save_lastsearch_values) {
  4410. $url .= '&save_lastsearch_values=1';
  4411. }
  4412. }
  4413. $linkstart = '<a href="'.$url.'"';
  4414. $linkstart .= $linkclose.'>';
  4415. $linkend = '</a>';
  4416. $result .= $linkstart;
  4417. if ($withpicto) {
  4418. if ($this->type == Product::TYPE_PRODUCT) {
  4419. $result .= (img_object(($notooltip ? '' : $label), 'product', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
  4420. }
  4421. if ($this->type == Product::TYPE_SERVICE) {
  4422. $result .= (img_object(($notooltip ? '' : $label), 'service', ($notooltip ? 'class="paddingright"' : 'class="paddingright classfortooltip"'), 0, 0, $notooltip ? 0 : 1));
  4423. }
  4424. }
  4425. $result .= $newref;
  4426. $result .= $linkend;
  4427. global $action;
  4428. $hookmanager->initHooks(array('productdao'));
  4429. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  4430. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  4431. if ($reshook > 0) {
  4432. $result = $hookmanager->resPrint;
  4433. } else {
  4434. $result .= $hookmanager->resPrint;
  4435. }
  4436. return $result;
  4437. }
  4438. /**
  4439. * Create a document onto disk according to template module.
  4440. *
  4441. * @param string $modele Force model to use ('' to not force)
  4442. * @param Translate $outputlangs Object langs to use for output
  4443. * @param int $hidedetails Hide details of lines
  4444. * @param int $hidedesc Hide description
  4445. * @param int $hideref Hide ref
  4446. * @return int 0 if KO, 1 if OK
  4447. */
  4448. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  4449. {
  4450. global $conf, $user, $langs;
  4451. $langs->load("products");
  4452. $outputlangs->load("products");
  4453. // Positionne le modele sur le nom du modele a utiliser
  4454. if (!dol_strlen($modele)) {
  4455. if (!empty($conf->global->PRODUCT_ADDON_PDF)) {
  4456. $modele = $conf->global->PRODUCT_ADDON_PDF;
  4457. } else {
  4458. $modele = 'strato';
  4459. }
  4460. }
  4461. $modelpath = "core/modules/product/doc/";
  4462. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  4463. }
  4464. /**
  4465. * Return label of status of object
  4466. *
  4467. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  4468. * @param int $type 0=Sell, 1=Buy, 2=Batch Number management
  4469. * @return string Label of status
  4470. */
  4471. public function getLibStatut($mode = 0, $type = 0)
  4472. {
  4473. switch ($type) {
  4474. case 0:
  4475. return $this->LibStatut($this->status, $mode, $type);
  4476. case 1:
  4477. return $this->LibStatut($this->status_buy, $mode, $type);
  4478. case 2:
  4479. return $this->LibStatut($this->status_batch, $mode, $type);
  4480. default:
  4481. //Simulate previous behavior but should return an error string
  4482. return $this->LibStatut($this->status_buy, $mode, $type);
  4483. }
  4484. }
  4485. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4486. /**
  4487. * Return label of a given status
  4488. *
  4489. * @param int $status Statut
  4490. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  4491. * @param int $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4492. * @return string Label of status
  4493. */
  4494. public function LibStatut($status, $mode = 0, $type = 0)
  4495. {
  4496. // phpcs:enable
  4497. global $conf, $langs;
  4498. $labelStatus = $labelStatusShort = '';
  4499. $langs->load('products');
  4500. if (!empty($conf->productbatch->enabled)) {
  4501. $langs->load("productbatch");
  4502. }
  4503. if ($type == 2) {
  4504. switch ($mode) {
  4505. case 0:
  4506. $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatch') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial')));
  4507. return dolGetStatus($label);
  4508. case 1:
  4509. $label = ($status == 0 ? $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort') : ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort')));
  4510. return dolGetStatus($label);
  4511. case 2:
  4512. return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 1, 2);
  4513. case 3:
  4514. return dolGetStatus($langs->transnoentitiesnoconv('ProductStatusNotOnBatch'), '', '', empty($status) ? 'status5' : 'status4', 3, 'dot');
  4515. case 4:
  4516. return $this->LibStatut($status, 3, 2).' '.$this->LibStatut($status, 0, 2);
  4517. case 5:
  4518. return $this->LibStatut($status, 1, 2).' '.$this->LibStatut($status, 3, 2);
  4519. default:
  4520. return dolGetStatus($langs->transnoentitiesnoconv('Unknown'));
  4521. }
  4522. }
  4523. $statuttrans = empty($status) ? 'status5' : 'status4';
  4524. if ($status == 0) {
  4525. // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4526. if ($type == 0) {
  4527. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnSellShort');
  4528. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnSell');
  4529. } elseif ($type == 1) {
  4530. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBuyShort');
  4531. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBuy');
  4532. } elseif ($type == 2) {
  4533. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusNotOnBatch');
  4534. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusNotOnBatchShort');
  4535. }
  4536. } elseif ($status == 1) {
  4537. // $type 0=Status "to sell", 1=Status "to buy", 2=Status "to Batch"
  4538. if ($type == 0) {
  4539. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSellShort');
  4540. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSell');
  4541. } elseif ($type == 1) {
  4542. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnBuyShort');
  4543. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnBuy');
  4544. } elseif ($type == 2) {
  4545. $labelStatus = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatch') : $langs->transnoentitiesnoconv('ProductStatusOnSerial'));
  4546. $labelStatusShort = ($status == 1 ? $langs->transnoentitiesnoconv('ProductStatusOnBatchShort') : $langs->transnoentitiesnoconv('ProductStatusOnSerialShort'));
  4547. }
  4548. } elseif ( $type == 2 && $status == 2 ) {
  4549. $labelStatus = $langs->transnoentitiesnoconv('ProductStatusOnSerial');
  4550. $labelStatusShort = $langs->transnoentitiesnoconv('ProductStatusOnSerialShort');
  4551. }
  4552. if ($mode > 6) {
  4553. return dolGetStatus($langs->transnoentitiesnoconv('Unknown'), '', '', 'status0', 0);
  4554. } else {
  4555. return dolGetStatus($labelStatus, $labelStatusShort, '', $statuttrans, $mode);
  4556. }
  4557. }
  4558. /**
  4559. * Retour label of nature of product
  4560. *
  4561. * @return string Label
  4562. */
  4563. public function getLibFinished()
  4564. {
  4565. global $langs;
  4566. $langs->load('products');
  4567. if (isset($this->finished) && $this->finished >= 0) {
  4568. $sql = "SELECT label, code FROM ".$this->db->prefix()."c_product_nature where code = ".((int) $this->finished)." AND active=1";
  4569. $resql = $this->db->query($sql);
  4570. if ($resql && $this->db->num_rows($resql) > 0) {
  4571. $res = $this->db->fetch_array($resql);
  4572. $label = $langs->trans($res['label']);
  4573. $this->db->free($resql);
  4574. return $label;
  4575. } else {
  4576. $this->error = $this->db->error().' sql='.$sql;
  4577. dol_syslog(__METHOD__.' Error '.$this->error, LOG_ERR);
  4578. return -1;
  4579. }
  4580. }
  4581. return '';
  4582. }
  4583. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4584. /**
  4585. * Adjust stock in a warehouse for product
  4586. *
  4587. * @param User $user user asking change
  4588. * @param int $id_entrepot id of warehouse
  4589. * @param double $nbpiece nb of units (should be always positive, use $movement to decide if we add or remove)
  4590. * @param int $movement 0 = add, 1 = remove
  4591. * @param string $label Label of stock movement
  4592. * @param double $price Unit price HT of product, used to calculate average weighted price (PMP in french). If 0, average weighted price is not changed.
  4593. * @param string $inventorycode Inventory code
  4594. * @param string $origin_element Origin element type
  4595. * @param int $origin_id Origin id of element
  4596. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  4597. * @param array $extrafields Array of extrafields
  4598. * @return int <0 if KO, >0 if OK
  4599. */
  4600. public function correct_stock($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
  4601. {
  4602. // phpcs:enable
  4603. if ($id_entrepot) {
  4604. $this->db->begin();
  4605. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  4606. if ($nbpiece < 0) {
  4607. if (!$movement) {
  4608. $movement = 1;
  4609. }
  4610. $nbpiece = abs($nbpiece);
  4611. }
  4612. $op[0] = "+".trim($nbpiece);
  4613. $op[1] = "-".trim($nbpiece);
  4614. $movementstock = new MouvementStock($this->db);
  4615. $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->origin_id
  4616. $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', '', '', '', false, 0, $disablestockchangeforsubproduct);
  4617. if ($result >= 0) {
  4618. if ($extrafields) {
  4619. $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
  4620. $movementstock->array_options = $array_options;
  4621. $movementstock->insertExtraFields();
  4622. }
  4623. $this->db->commit();
  4624. return 1;
  4625. } else {
  4626. $this->error = $movementstock->error;
  4627. $this->errors = $movementstock->errors;
  4628. $this->db->rollback();
  4629. return -1;
  4630. }
  4631. }
  4632. }
  4633. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4634. /**
  4635. * Adjust stock in a warehouse for product with batch number
  4636. *
  4637. * @param User $user user asking change
  4638. * @param int $id_entrepot id of warehouse
  4639. * @param double $nbpiece nb of units (should be always positive, use $movement to decide if we add or remove)
  4640. * @param int $movement 0 = add, 1 = remove
  4641. * @param string $label Label of stock movement
  4642. * @param double $price Price to use for stock eval
  4643. * @param integer $dlc eat-by date
  4644. * @param integer $dluo sell-by date
  4645. * @param string $lot Lot number
  4646. * @param string $inventorycode Inventory code
  4647. * @param string $origin_element Origin element type
  4648. * @param int $origin_id Origin id of element
  4649. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  4650. * @param array $extrafields Array of extrafields
  4651. * @return int <0 if KO, >0 if OK
  4652. */
  4653. public function correct_stock_batch($user, $id_entrepot, $nbpiece, $movement, $label = '', $price = 0, $dlc = '', $dluo = '', $lot = '', $inventorycode = '', $origin_element = '', $origin_id = null, $disablestockchangeforsubproduct = 0, $extrafields = null)
  4654. {
  4655. // phpcs:enable
  4656. if ($id_entrepot) {
  4657. $this->db->begin();
  4658. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
  4659. if ($nbpiece < 0) {
  4660. if (!$movement) {
  4661. $movement = 1;
  4662. }
  4663. $nbpiece = abs($nbpiece);
  4664. }
  4665. $op[0] = "+".trim($nbpiece);
  4666. $op[1] = "-".trim($nbpiece);
  4667. $movementstock = new MouvementStock($this->db);
  4668. $movementstock->setOrigin($origin_element, $origin_id); // Set ->origin_type and ->fk_origin
  4669. $result = $movementstock->_create($user, $this->id, $id_entrepot, $op[$movement], $movement, $price, $label, $inventorycode, '', $dlc, $dluo, $lot, false, 0, $disablestockchangeforsubproduct);
  4670. if ($result >= 0) {
  4671. if ($extrafields) {
  4672. $array_options = $extrafields->getOptionalsFromPost('stock_mouvement');
  4673. $movementstock->array_options = $array_options;
  4674. $movementstock->insertExtraFields();
  4675. }
  4676. $this->db->commit();
  4677. return 1;
  4678. } else {
  4679. $this->error = $movementstock->error;
  4680. $this->errors = $movementstock->errors;
  4681. $this->db->rollback();
  4682. return -1;
  4683. }
  4684. }
  4685. }
  4686. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4687. /**
  4688. * Load information about stock of a product into ->stock_reel, ->stock_warehouse[] (including stock_warehouse[idwarehouse]->detail_batch for batch products)
  4689. * This function need a lot of load. If you use it on list, use a cache to execute it once for each product id.
  4690. * If ENTREPOT_EXTRA_STATUS is set, filtering on warehouse status is possible.
  4691. *
  4692. * @param string $option '' = Load all stock info, also from closed and internal warehouses, 'nobatch', 'novirtual'
  4693. * You can also filter on 'warehouseclosed', 'warehouseopen', 'warehouseinternal'
  4694. * @param int $includedraftpoforvirtual Include draft status of PO for virtual stock calculation
  4695. * @return int < 0 if KO, > 0 if OK
  4696. * @see load_virtual_stock(), loadBatchInfo()
  4697. */
  4698. public function load_stock($option = '', $includedraftpoforvirtual = null)
  4699. {
  4700. // phpcs:enable
  4701. global $conf;
  4702. $this->stock_reel = 0;
  4703. $this->stock_warehouse = array();
  4704. $this->stock_theorique = 0;
  4705. // Set filter on warehouse status
  4706. $warehouseStatus = array();
  4707. if (preg_match('/warehouseclosed/', $option)) {
  4708. $warehouseStatus[Entrepot::STATUS_CLOSED] = Entrepot::STATUS_CLOSED;
  4709. }
  4710. if (preg_match('/warehouseopen/', $option)) {
  4711. $warehouseStatus[Entrepot::STATUS_OPEN_ALL] = Entrepot::STATUS_OPEN_ALL;
  4712. }
  4713. if (preg_match('/warehouseinternal/', $option)) {
  4714. if (!empty($conf->global->ENTREPOT_EXTRA_STATUS)) {
  4715. $warehouseStatus[Entrepot::STATUS_OPEN_INTERNAL] = Entrepot::STATUS_OPEN_INTERNAL;
  4716. } else {
  4717. $warehouseStatus[Entrepot::STATUS_OPEN_ALL] = Entrepot::STATUS_OPEN_ALL;
  4718. }
  4719. }
  4720. $sql = "SELECT ps.rowid, ps.reel, ps.fk_entrepot";
  4721. $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
  4722. $sql .= ", ".$this->db->prefix()."entrepot as w";
  4723. $sql .= " WHERE w.entity IN (".getEntity('stock').")";
  4724. $sql .= " AND w.rowid = ps.fk_entrepot";
  4725. $sql .= " AND ps.fk_product = ".((int) $this->id);
  4726. if (count($warehouseStatus)) {
  4727. $sql .= " AND w.statut IN (".$this->db->sanitize(implode(',', $warehouseStatus)).")";
  4728. }
  4729. $sql .= " ORDER BY ps.reel ".(!empty($conf->global->DO_NOT_TRY_TO_DEFRAGMENT_STOCKS_WAREHOUSE)?'DESC':'ASC'); // Note : qty ASC is important for expedition card, to avoid stock fragmentation;
  4730. dol_syslog(get_class($this)."::load_stock", LOG_DEBUG);
  4731. $result = $this->db->query($sql);
  4732. if ($result) {
  4733. $num = $this->db->num_rows($result);
  4734. $i = 0;
  4735. if ($num > 0) {
  4736. while ($i < $num) {
  4737. $row = $this->db->fetch_object($result);
  4738. $this->stock_warehouse[$row->fk_entrepot] = new stdClass();
  4739. $this->stock_warehouse[$row->fk_entrepot]->real = $row->reel;
  4740. $this->stock_warehouse[$row->fk_entrepot]->id = $row->rowid;
  4741. if ((!preg_match('/nobatch/', $option)) && $this->hasbatch()) {
  4742. $this->stock_warehouse[$row->fk_entrepot]->detail_batch = Productbatch::findAll($this->db, $row->rowid, 1, $this->id);
  4743. }
  4744. $this->stock_reel += $row->reel;
  4745. $i++;
  4746. }
  4747. }
  4748. $this->db->free($result);
  4749. if (!preg_match('/novirtual/', $option)) {
  4750. $this->load_virtual_stock($includedraftpoforvirtual); // This also load all arrays stats_xxx...
  4751. }
  4752. return 1;
  4753. } else {
  4754. $this->error = $this->db->lasterror();
  4755. return -1;
  4756. }
  4757. }
  4758. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4759. /**
  4760. * Load value ->stock_theorique of a product. Property this->id must be defined.
  4761. * This function need a lot of load. If you use it on list, use a cache to execute it one for each product id.
  4762. *
  4763. * @param int $includedraftpoforvirtual Include draft status and not yet approved Purchase Orders for virtual stock calculation
  4764. * @return int < 0 if KO, > 0 if OK
  4765. * @see load_stock(), loadBatchInfo()
  4766. */
  4767. public function load_virtual_stock($includedraftpoforvirtual = null)
  4768. {
  4769. // phpcs:enable
  4770. global $conf, $hookmanager, $action;
  4771. $stock_commande_client = 0;
  4772. $stock_commande_fournisseur = 0;
  4773. $stock_sending_client = 0;
  4774. $stock_reception_fournisseur = 0;
  4775. $stock_inproduction = 0;
  4776. //dol_syslog("load_virtual_stock");
  4777. if (!empty($conf->commande->enabled)) {
  4778. $result = $this->load_stats_commande(0, '1,2', 1);
  4779. if ($result < 0) {
  4780. dol_print_error($this->db, $this->error);
  4781. }
  4782. $stock_commande_client = $this->stats_commande['qty'];
  4783. }
  4784. if (!empty($conf->expedition->enabled)) {
  4785. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  4786. $filterShipmentStatus = '';
  4787. if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT)) {
  4788. $filterShipmentStatus = Expedition::STATUS_VALIDATED.','.Expedition::STATUS_CLOSED;
  4789. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
  4790. $filterShipmentStatus = Expedition::STATUS_CLOSED;
  4791. }
  4792. $result = $this->load_stats_sending(0, '1,2', 1, $filterShipmentStatus);
  4793. if ($result < 0) {
  4794. dol_print_error($this->db, $this->error);
  4795. }
  4796. $stock_sending_client = $this->stats_expedition['qty'];
  4797. }
  4798. if ((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled)) {
  4799. $filterStatus = empty($conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK) ? '3,4' : $conf->global->SUPPLIER_ORDER_STATUS_FOR_VIRTUAL_STOCK;
  4800. if (isset($includedraftpoforvirtual)) {
  4801. $filterStatus = '0,1,2,'.$filterStatus; // 1,2 may have already been inside $filterStatus but it is better to have twice than missing $filterStatus does not include them
  4802. }
  4803. $result = $this->load_stats_commande_fournisseur(0, $filterStatus, 1);
  4804. if ($result < 0) {
  4805. dol_print_error($this->db, $this->error);
  4806. }
  4807. $stock_commande_fournisseur = $this->stats_commande_fournisseur['qty'];
  4808. }
  4809. if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && empty($conf->reception->enabled)) {
  4810. // Case module reception is not used
  4811. $filterStatus = '4';
  4812. if (isset($includedraftpoforvirtual)) {
  4813. $filterStatus = '0,'.$filterStatus;
  4814. }
  4815. $result = $this->load_stats_reception(0, $filterStatus, 1);
  4816. if ($result < 0) {
  4817. dol_print_error($this->db, $this->error);
  4818. }
  4819. $stock_reception_fournisseur = $this->stats_reception['qty'];
  4820. }
  4821. if (((!empty($conf->fournisseur->enabled) && empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)) || !empty($conf->supplier_order->enabled) || !empty($conf->supplier_invoice->enabled)) && !empty($conf->reception->enabled)) {
  4822. // Case module reception is used
  4823. $filterStatus = '4';
  4824. if (isset($includedraftpoforvirtual)) {
  4825. $filterStatus = '0,'.$filterStatus;
  4826. }
  4827. $result = $this->load_stats_reception(0, $filterStatus, 1); // Use same tables than when module reception is not used.
  4828. if ($result < 0) {
  4829. dol_print_error($this->db, $this->error);
  4830. }
  4831. $stock_reception_fournisseur = $this->stats_reception['qty'];
  4832. }
  4833. if (!empty($conf->mrp->enabled)) {
  4834. $result = $this->load_stats_inproduction(0, '1,2', 1);
  4835. if ($result < 0) {
  4836. dol_print_error($this->db, $this->error);
  4837. }
  4838. $stock_inproduction = $this->stats_mrptoproduce['qty'] - $this->stats_mrptoconsume['qty'];
  4839. }
  4840. $this->stock_theorique = $this->stock_reel + $stock_inproduction;
  4841. // Stock decrease mode
  4842. if (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE)) {
  4843. $this->stock_theorique -= ($stock_commande_client - $stock_sending_client);
  4844. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER)) {
  4845. $this->stock_theorique += 0;
  4846. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_BILL)) {
  4847. $this->stock_theorique -= $stock_commande_client;
  4848. }
  4849. // Stock Increase mode
  4850. if (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE)) {
  4851. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  4852. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER)) {
  4853. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  4854. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER)) {
  4855. $this->stock_theorique -= $stock_reception_fournisseur;
  4856. } elseif (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL)) {
  4857. $this->stock_theorique += ($stock_commande_fournisseur - $stock_reception_fournisseur);
  4858. }
  4859. if (!is_object($hookmanager)) {
  4860. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  4861. $hookmanager = new HookManager($this->db);
  4862. }
  4863. $hookmanager->initHooks(array('productdao'));
  4864. $parameters = array('id'=>$this->id, 'includedraftpoforvirtual' => $includedraftpoforvirtual);
  4865. // Note that $action and $object may have been modified by some hooks
  4866. $reshook = $hookmanager->executeHooks('loadvirtualstock', $parameters, $this, $action);
  4867. if ($reshook > 0) {
  4868. $this->stock_theorique = $hookmanager->resArray['stock_theorique'];
  4869. }
  4870. return 1;
  4871. }
  4872. /**
  4873. * Load existing information about a serial
  4874. *
  4875. * @param string $batch Lot/serial number
  4876. * @return array Array with record into product_batch
  4877. * @see load_stock(), load_virtual_stock()
  4878. */
  4879. public function loadBatchInfo($batch)
  4880. {
  4881. $result = array();
  4882. $sql = "SELECT pb.batch, pb.eatby, pb.sellby, SUM(pb.qty) AS qty FROM ".$this->db->prefix()."product_batch as pb, ".$this->db->prefix()."product_stock as ps";
  4883. $sql .= " WHERE pb.fk_product_stock = ps.rowid AND ps.fk_product = ".((int) $this->id)." AND pb.batch = '".$this->db->escape($batch)."'";
  4884. $sql .= " GROUP BY pb.batch, pb.eatby, pb.sellby";
  4885. dol_syslog(get_class($this)."::loadBatchInfo load first entry found for lot/serial = ".$batch, LOG_DEBUG);
  4886. $resql = $this->db->query($sql);
  4887. if ($resql) {
  4888. $num = $this->db->num_rows($resql);
  4889. $i = 0;
  4890. while ($i < $num) {
  4891. $obj = $this->db->fetch_object($resql);
  4892. $result[] = array('batch'=>$batch, 'eatby'=>$this->db->jdate($obj->eatby), 'sellby'=>$this->db->jdate($obj->sellby), 'qty'=>$obj->qty);
  4893. $i++;
  4894. }
  4895. return $result;
  4896. } else {
  4897. dol_print_error($this->db);
  4898. $this->db->rollback();
  4899. return array();
  4900. }
  4901. }
  4902. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4903. /**
  4904. * Move an uploaded file described into $file array into target directory $sdir.
  4905. *
  4906. * @param string $sdir Target directory
  4907. * @param string $file Array of file info of file to upload: array('name'=>..., 'tmp_name'=>...)
  4908. * @return int <0 if KO, >0 if OK
  4909. */
  4910. public function add_photo($sdir, $file)
  4911. {
  4912. // phpcs:enable
  4913. global $conf;
  4914. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4915. $result = 0;
  4916. $dir = $sdir;
  4917. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  4918. $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos";
  4919. } else {
  4920. $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product').dol_sanitizeFileName($this->ref);
  4921. }
  4922. dol_mkdir($dir);
  4923. $dir_osencoded = $dir;
  4924. if (is_dir($dir_osencoded)) {
  4925. $originImage = $dir.'/'.$file['name'];
  4926. // Cree fichier en taille origine
  4927. $result = dol_move_uploaded_file($file['tmp_name'], $originImage, 1);
  4928. if (file_exists(dol_osencode($originImage))) {
  4929. // Create thumbs
  4930. $this->addThumbs($originImage);
  4931. }
  4932. }
  4933. if (is_numeric($result) && $result > 0) {
  4934. return 1;
  4935. } else {
  4936. return -1;
  4937. }
  4938. }
  4939. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4940. /**
  4941. * Return if at least one photo is available
  4942. *
  4943. * @param string $sdir Directory to scan
  4944. * @return boolean True if at least one photo is available, False if not
  4945. */
  4946. public function is_photo_available($sdir)
  4947. {
  4948. // phpcs:enable
  4949. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4950. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  4951. global $conf;
  4952. $dir = $sdir;
  4953. if (!empty($conf->global->PRODUCT_USE_OLD_PATH_FOR_PHOTO)) {
  4954. $dir .= '/'.get_exdir($this->id, 2, 0, 0, $this, 'product').$this->id."/photos/";
  4955. } else {
  4956. $dir .= '/'.get_exdir(0, 0, 0, 0, $this, 'product');
  4957. }
  4958. $nbphoto = 0;
  4959. $dir_osencoded = dol_osencode($dir);
  4960. if (file_exists($dir_osencoded)) {
  4961. $handle = opendir($dir_osencoded);
  4962. if (is_resource($handle)) {
  4963. while (($file = readdir($handle)) !== false) {
  4964. if (!utf8_check($file)) {
  4965. $file = utf8_encode($file); // To be sure data is stored in UTF8 in memory
  4966. }
  4967. if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
  4968. return true;
  4969. }
  4970. }
  4971. }
  4972. }
  4973. return false;
  4974. }
  4975. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  4976. /**
  4977. * Return an array with all photos of product found on disk. There is no sorting criteria.
  4978. *
  4979. * @param string $dir Directory to scan
  4980. * @param int $nbmax Number maxium of photos (0=no maximum)
  4981. * @return array Array of photos
  4982. */
  4983. public function liste_photos($dir, $nbmax = 0)
  4984. {
  4985. // phpcs:enable
  4986. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  4987. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  4988. $nbphoto = 0;
  4989. $tabobj = array();
  4990. $dir_osencoded = dol_osencode($dir);
  4991. $handle = @opendir($dir_osencoded);
  4992. if (is_resource($handle)) {
  4993. while (($file = readdir($handle)) !== false) {
  4994. if (!utf8_check($file)) {
  4995. $file = utf8_encode($file); // readdir returns ISO
  4996. }
  4997. if (dol_is_file($dir.$file) && image_format_supported($file) >= 0) {
  4998. $nbphoto++;
  4999. // We forge name of thumb.
  5000. $photo = $file;
  5001. $photo_vignette = '';
  5002. $regs = array();
  5003. if (preg_match('/('.$this->regeximgext.')$/i', $photo, $regs)) {
  5004. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $photo).'_small'.$regs[0];
  5005. }
  5006. $dirthumb = $dir.'thumbs/';
  5007. // Objet
  5008. $obj = array();
  5009. $obj['photo'] = $photo;
  5010. if ($photo_vignette && dol_is_file($dirthumb.$photo_vignette)) {
  5011. $obj['photo_vignette'] = 'thumbs/'.$photo_vignette;
  5012. } else {
  5013. $obj['photo_vignette'] = "";
  5014. }
  5015. $tabobj[$nbphoto - 1] = $obj;
  5016. // Do we have to continue with next photo ?
  5017. if ($nbmax && $nbphoto >= $nbmax) {
  5018. break;
  5019. }
  5020. }
  5021. }
  5022. closedir($handle);
  5023. }
  5024. return $tabobj;
  5025. }
  5026. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5027. /**
  5028. * Delete a photo and its thumbs
  5029. *
  5030. * @param string $file Path to image file
  5031. * @return void
  5032. */
  5033. public function delete_photo($file)
  5034. {
  5035. // phpcs:enable
  5036. include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  5037. include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
  5038. $dir = dirname($file).'/'; // Chemin du dossier contenant l'image d'origine
  5039. $dirthumb = $dir.'/thumbs/'; // Chemin du dossier contenant la vignette
  5040. $filename = preg_replace('/'.preg_quote($dir, '/').'/i', '', $file); // Nom du fichier
  5041. // On efface l'image d'origine
  5042. dol_delete_file($file, 0, 0, 0, $this); // For triggers
  5043. // Si elle existe, on efface la vignette
  5044. if (preg_match('/('.$this->regeximgext.')$/i', $filename, $regs)) {
  5045. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_small'.$regs[0];
  5046. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  5047. dol_delete_file($dirthumb.$photo_vignette);
  5048. }
  5049. $photo_vignette = preg_replace('/'.$regs[0].'/i', '', $filename).'_mini'.$regs[0];
  5050. if (file_exists(dol_osencode($dirthumb.$photo_vignette))) {
  5051. dol_delete_file($dirthumb.$photo_vignette);
  5052. }
  5053. }
  5054. }
  5055. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5056. /**
  5057. * Load size of image file
  5058. *
  5059. * @param string $file Path to file
  5060. * @return void
  5061. */
  5062. public function get_image_size($file)
  5063. {
  5064. // phpcs:enable
  5065. $file_osencoded = dol_osencode($file);
  5066. $infoImg = getimagesize($file_osencoded); // Get information on image
  5067. $this->imgWidth = $infoImg[0]; // Largeur de l'image
  5068. $this->imgHeight = $infoImg[1]; // Hauteur de l'image
  5069. }
  5070. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5071. /**
  5072. * Load indicators this->nb for the dashboard
  5073. *
  5074. * @return int <0 if KO, >0 if OK
  5075. */
  5076. public function load_state_board()
  5077. {
  5078. // phpcs:enable
  5079. global $conf, $user, $hookmanager;
  5080. $this->nb = array();
  5081. $sql = "SELECT count(p.rowid) as nb, fk_product_type";
  5082. $sql .= " FROM ".$this->db->prefix()."product as p";
  5083. $sql .= ' WHERE p.entity IN ('.getEntity($this->element, 1).')';
  5084. // Add where from hooks
  5085. if (is_object($hookmanager)) {
  5086. $parameters = array();
  5087. $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters); // Note that $action and $object may have been modified by hook
  5088. $sql .= $hookmanager->resPrint;
  5089. }
  5090. $sql .= ' GROUP BY fk_product_type';
  5091. $resql = $this->db->query($sql);
  5092. if ($resql) {
  5093. while ($obj = $this->db->fetch_object($resql)) {
  5094. if ($obj->fk_product_type == 1) {
  5095. $this->nb["services"] = $obj->nb;
  5096. } else {
  5097. $this->nb["products"] = $obj->nb;
  5098. }
  5099. }
  5100. $this->db->free($resql);
  5101. return 1;
  5102. } else {
  5103. dol_print_error($this->db);
  5104. $this->error = $this->db->error();
  5105. return -1;
  5106. }
  5107. }
  5108. /**
  5109. * Return if object is a product
  5110. *
  5111. * @return boolean True if it's a product
  5112. */
  5113. public function isProduct()
  5114. {
  5115. return ($this->type == Product::TYPE_PRODUCT ? true : false);
  5116. }
  5117. /**
  5118. * Return if object is a product
  5119. *
  5120. * @return boolean True if it's a service
  5121. */
  5122. public function isService()
  5123. {
  5124. return ($this->type == Product::TYPE_SERVICE ? true : false);
  5125. }
  5126. /**
  5127. * Return if object have a constraint on mandatory_period
  5128. *
  5129. * @return boolean True if mandatory_period setted to 1
  5130. */
  5131. public function isMandatoryPeriod()
  5132. {
  5133. return ($this->mandatory_period == 1 ? true : false);
  5134. }
  5135. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5136. /**
  5137. * Get a barcode from the module to generate barcode values.
  5138. * Return value is stored into this->barcode
  5139. *
  5140. * @param Product $object Object product or service
  5141. * @param string $type Barcode type (ean, isbn, ...)
  5142. * @return string
  5143. */
  5144. public function get_barcode($object, $type = '')
  5145. {
  5146. // phpcs:enable
  5147. global $conf;
  5148. $result = '';
  5149. if (!empty($conf->global->BARCODE_PRODUCT_ADDON_NUM)) {
  5150. $dirsociete = array_merge(array('/core/modules/barcode/'), $conf->modules_parts['barcode']);
  5151. foreach ($dirsociete as $dirroot) {
  5152. $res = dol_include_once($dirroot.$conf->global->BARCODE_PRODUCT_ADDON_NUM.'.php');
  5153. if ($res) {
  5154. break;
  5155. }
  5156. }
  5157. $var = $conf->global->BARCODE_PRODUCT_ADDON_NUM;
  5158. $mod = new $var;
  5159. $result = $mod->getNextValue($object, $type);
  5160. dol_syslog(get_class($this)."::get_barcode barcode=".$result." module=".$var);
  5161. }
  5162. return $result;
  5163. }
  5164. /**
  5165. * Initialise an instance with random values.
  5166. * Used to build previews or test instances.
  5167. * id must be 0 if object instance is a specimen.
  5168. *
  5169. * @return void
  5170. */
  5171. public function initAsSpecimen()
  5172. {
  5173. global $user, $langs, $conf, $mysoc;
  5174. $now = dol_now();
  5175. // Initialize parameters
  5176. $this->specimen = 1;
  5177. $this->id = 0;
  5178. $this->ref = 'PRODUCT_SPEC';
  5179. $this->label = 'PRODUCT SPECIMEN';
  5180. $this->description = 'This is description of this product specimen that was created the '.dol_print_date($now, 'dayhourlog').'.';
  5181. $this->specimen = 1;
  5182. $this->country_id = 1;
  5183. $this->tosell = 1;
  5184. $this->tobuy = 1;
  5185. $this->tobatch = 0;
  5186. $this->note = 'This is a comment (private)';
  5187. $this->date_creation = $now;
  5188. $this->date_modification = $now;
  5189. $this->weight = 4;
  5190. $this->weight_units = 3;
  5191. $this->length = 5;
  5192. $this->length_units = 1;
  5193. $this->width = 6;
  5194. $this->width_units = 0;
  5195. $this->height = null;
  5196. $this->height_units = null;
  5197. $this->surface = 30;
  5198. $this->surface_units = 0;
  5199. $this->volume = 300;
  5200. $this->volume_units = 0;
  5201. $this->barcode = -1; // Create barcode automatically
  5202. }
  5203. /**
  5204. * Returns the text label from units dictionary
  5205. *
  5206. * @param string $type Label type (long or short)
  5207. * @return string|int <0 if ko, label if ok
  5208. */
  5209. public function getLabelOfUnit($type = 'long')
  5210. {
  5211. global $langs;
  5212. if (!$this->fk_unit) {
  5213. return '';
  5214. }
  5215. $langs->load('products');
  5216. $label_type = 'label';
  5217. if ($type == 'short') {
  5218. $label_type = 'short_label';
  5219. }
  5220. $sql = "SELECT ".$label_type.", code from ".$this->db->prefix()."c_units where rowid = ".((int) $this->fk_unit);
  5221. $resql = $this->db->query($sql);
  5222. if ($resql && $this->db->num_rows($resql) > 0) {
  5223. $res = $this->db->fetch_array($resql);
  5224. $label = ($label_type == 'short_label' ? $res[$label_type] : 'unit'.$res['code']);
  5225. $this->db->free($resql);
  5226. return $label;
  5227. } else {
  5228. $this->error = $this->db->error();
  5229. dol_syslog(get_class($this)."::getLabelOfUnit Error ".$this->error, LOG_ERR);
  5230. return -1;
  5231. }
  5232. }
  5233. /**
  5234. * Return if object has a sell-by date or eat-by date
  5235. *
  5236. * @return boolean True if it's has
  5237. */
  5238. public function hasbatch()
  5239. {
  5240. return ($this->status_batch > 0 ? true : false);
  5241. }
  5242. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  5243. /**
  5244. * Return minimum product recommended price
  5245. *
  5246. * @return int Minimum recommanded price that is higher price among all suppliers * PRODUCT_MINIMUM_RECOMMENDED_PRICE
  5247. */
  5248. public function min_recommended_price()
  5249. {
  5250. // phpcs:enable
  5251. global $conf;
  5252. $maxpricesupplier = 0;
  5253. if (!empty($conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE)) {
  5254. include_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  5255. $product_fourn = new ProductFournisseur($this->db);
  5256. $product_fourn_list = $product_fourn->list_product_fournisseur_price($this->id, '', '');
  5257. if (is_array($product_fourn_list) && count($product_fourn_list) > 0) {
  5258. foreach ($product_fourn_list as $productfourn) {
  5259. if ($productfourn->fourn_unitprice > $maxpricesupplier) {
  5260. $maxpricesupplier = $productfourn->fourn_unitprice;
  5261. }
  5262. }
  5263. $maxpricesupplier *= $conf->global->PRODUCT_MINIMUM_RECOMMENDED_PRICE;
  5264. }
  5265. }
  5266. return $maxpricesupplier;
  5267. }
  5268. /**
  5269. * Sets object to supplied categories.
  5270. *
  5271. * Deletes object from existing categories not supplied.
  5272. * Adds it to non existing supplied categories.
  5273. * Existing categories are left untouch.
  5274. *
  5275. * @param int[]|int $categories Category or categories IDs
  5276. * @return void
  5277. */
  5278. public function setCategories($categories)
  5279. {
  5280. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  5281. return parent::setCategoriesCommon($categories, Categorie::TYPE_PRODUCT);
  5282. }
  5283. /**
  5284. * Function used to replace a thirdparty id with another one.
  5285. *
  5286. * @param DoliDB $db Database handler
  5287. * @param int $origin_id Old thirdparty id
  5288. * @param int $dest_id New thirdparty id
  5289. * @return bool
  5290. */
  5291. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  5292. {
  5293. $tables = array(
  5294. 'product_customer_price',
  5295. 'product_customer_price_log'
  5296. );
  5297. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  5298. }
  5299. /**
  5300. * Generates prices for a product based on product multiprice generation rules
  5301. *
  5302. * @param User $user User that updates the prices
  5303. * @param float $baseprice Base price
  5304. * @param string $price_type Base price type
  5305. * @param float $price_vat VAT % tax
  5306. * @param int $npr NPR
  5307. * @param string $psq ¿?
  5308. * @return int -1 KO, 1 OK
  5309. */
  5310. public function generateMultiprices(User $user, $baseprice, $price_type, $price_vat, $npr, $psq)
  5311. {
  5312. global $conf, $db;
  5313. $sql = "SELECT rowid, level, fk_level, var_percent, var_min_percent FROM ".$this->db->prefix()."product_pricerules";
  5314. $query = $this->db->query($sql);
  5315. $rules = array();
  5316. while ($result = $this->db->fetch_object($query)) {
  5317. $rules[$result->level] = $result;
  5318. }
  5319. //Because prices can be based on other level's prices, we temporarily store them
  5320. $prices = array(
  5321. 1 => $baseprice
  5322. );
  5323. for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
  5324. $price = $baseprice;
  5325. $price_min = $baseprice;
  5326. //We have to make sure it does exist and it is > 0
  5327. //First price level only allows changing min_price
  5328. if ($i > 1 && isset($rules[$i]->var_percent) && $rules[$i]->var_percent) {
  5329. $price = $prices[$rules[$i]->fk_level] * (1 + ($rules[$i]->var_percent / 100));
  5330. }
  5331. $prices[$i] = $price;
  5332. //We have to make sure it does exist and it is > 0
  5333. if (isset($rules[$i]->var_min_percent) && $rules[$i]->var_min_percent) {
  5334. $price_min = $price * (1 - ($rules[$i]->var_min_percent / 100));
  5335. }
  5336. //Little check to make sure the price is modified before triggering generation
  5337. $check_amount = (($price == $this->multiprices[$i]) && ($price_min == $this->multiprices_min[$i]));
  5338. $check_type = ($baseprice == $this->multiprices_base_type[$i]);
  5339. if ($check_amount && $check_type) {
  5340. continue;
  5341. }
  5342. if ($this->updatePrice($price, $price_type, $user, $price_vat, $price_min, $i, $npr, $psq, true) < 0) {
  5343. return -1;
  5344. }
  5345. }
  5346. return 1;
  5347. }
  5348. /**
  5349. * Returns the rights used for this class
  5350. *
  5351. * @return Object
  5352. */
  5353. public function getRights()
  5354. {
  5355. global $user;
  5356. if ($this->isProduct()) {
  5357. return $user->rights->produit;
  5358. } else {
  5359. return $user->rights->service;
  5360. }
  5361. }
  5362. /**
  5363. * Load information for tab info
  5364. *
  5365. * @param int $id Id of thirdparty to load
  5366. * @return void
  5367. */
  5368. public function info($id)
  5369. {
  5370. $sql = "SELECT p.rowid, p.ref, p.datec as date_creation, p.tms as date_modification,";
  5371. $sql .= " p.fk_user_author, p.fk_user_modif";
  5372. $sql .= " FROM ".$this->db->prefix().$this->table_element." as p";
  5373. $sql .= " WHERE p.rowid = ".((int) $id);
  5374. $result = $this->db->query($sql);
  5375. if ($result) {
  5376. if ($this->db->num_rows($result)) {
  5377. $obj = $this->db->fetch_object($result);
  5378. $this->id = $obj->rowid;
  5379. if ($obj->fk_user_author) {
  5380. $cuser = new User($this->db);
  5381. $cuser->fetch($obj->fk_user_author);
  5382. $this->user_creation = $cuser;
  5383. }
  5384. if ($obj->fk_user_modif) {
  5385. $muser = new User($this->db);
  5386. $muser->fetch($obj->fk_user_modif);
  5387. $this->user_modification = $muser;
  5388. }
  5389. $this->ref = $obj->ref;
  5390. $this->date_creation = $this->db->jdate($obj->date_creation);
  5391. $this->date_modification = $this->db->jdate($obj->date_modification);
  5392. }
  5393. $this->db->free($result);
  5394. } else {
  5395. dol_print_error($this->db);
  5396. }
  5397. }
  5398. }
  5399. /**
  5400. * Class to manage products or services.
  5401. * Do not use 'Service' as class name since it is already used by APIs.
  5402. */
  5403. class ProductService extends Product
  5404. {
  5405. public $picto = 'service';
  5406. }