product.class.php 199 KB

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