product.class.php 165 KB

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