product.class.php 157 KB

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