fournisseur.product.class.php 54 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331
  1. <?php
  2. /* Copyright (C) 2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2006-2011 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2009-2014 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
  6. * Copyright (C) 2012 Christophe Battarel <christophe.battarel@altairis.fr>
  7. * Copyright (C) 2015 Marcos García <marcosgdf@gmail.com>
  8. * Copyright (C) 2016 Charlie Benke <charlie@patas-monkey.com>
  9. * Copyright (C) 2019-2021 Frédéric France <frederic.france@netlogic.fr>
  10. * Copyright (C) 2020 Pierre Ardoin <mapiolca@me.com>
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/fourn/class/fournisseur.product.class.php
  27. * \ingroup produit
  28. * \brief File of class to manage predefined suppliers products
  29. */
  30. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  31. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
  32. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
  33. require_once DOL_DOCUMENT_ROOT.'/product/class/productfournisseurprice.class.php';
  34. /**
  35. * Class to manage predefined suppliers products
  36. */
  37. class ProductFournisseur extends Product
  38. {
  39. /**
  40. * @var DoliDB Database handler.
  41. */
  42. public $db;
  43. /**
  44. * @var string Error code (or message)
  45. */
  46. public $error = '';
  47. public $product_fourn_price_id; // id of ligne product-supplier
  48. /**
  49. * @var int ID
  50. */
  51. public $id;
  52. /**
  53. * @deprecated
  54. * @see $ref_supplier
  55. */
  56. public $fourn_ref;
  57. public $delivery_time_days;
  58. public $ref_supplier; // ref supplier (can be set by get_buyprice)
  59. public $desc_supplier;
  60. public $vatrate_supplier; // default vat rate for this supplier/qty/product (can be set by get_buyprice)
  61. public $product_id;
  62. public $product_ref;
  63. public $fourn_id; //supplier id
  64. public $fourn_qty; // quantity for price (can be set by get_buyprice)
  65. public $fourn_pu; // unit price for quantity (can be set by get_buyprice)
  66. public $fourn_price; // price for quantity
  67. public $fourn_remise_percent; // discount for quantity (percent)
  68. public $fourn_remise; // discount for quantity (amount)
  69. public $product_fourn_id; // product-supplier id
  70. public $product_fourn_entity;
  71. /**
  72. * @var int ID user_id - user who created/updated supplier price
  73. */
  74. public $user_id;
  75. /**
  76. * @var int ID availability delay - visible/used if option FOURN_PRODUCT_AVAILABILITY is on (duplicate information compared to delivery delay)
  77. */
  78. public $fk_availability;
  79. public $fourn_unitprice;
  80. public $fourn_unitprice_with_discount; // not saved into database
  81. public $fourn_tva_tx;
  82. public $fourn_tva_npr;
  83. /**
  84. * @var int ID
  85. */
  86. public $fk_supplier_price_expression;
  87. public $supplier_reputation; // reputation of supplier
  88. public $reputations = array(); // list of available supplier reputations
  89. // Multicurreny
  90. public $fourn_multicurrency_id;
  91. public $fourn_multicurrency_code;
  92. public $fourn_multicurrency_tx;
  93. public $fourn_multicurrency_price;
  94. public $fourn_multicurrency_unitprice;
  95. /**
  96. * @deprecated
  97. * @see $supplier_barcode
  98. */
  99. public $fourn_barcode;
  100. /**
  101. * @var string $supplier_barcode - Supplier barcode
  102. */
  103. public $supplier_barcode;
  104. /**
  105. * @deprecated
  106. * @see $supplier_fk_barcode_type
  107. */
  108. public $fourn_fk_barcode_type;
  109. /**
  110. * @var string $supplier_fk_barcode_type - Supplier barcode type
  111. */
  112. public $supplier_fk_barcode_type;
  113. public $packaging;
  114. /**
  115. * Constructor
  116. *
  117. * @param DoliDB $db Database handler
  118. */
  119. public function __construct($db)
  120. {
  121. global $langs;
  122. $this->db = $db;
  123. $langs->load("suppliers");
  124. $this->reputations = array('-1'=>'', 'FAVORITE'=>$langs->trans('Favorite'), 'NOTTHGOOD'=>$langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER'=>$langs->trans('DoNotOrderThisProductToThisSupplier'));
  125. }
  126. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  127. /**
  128. * Remove all prices for this couple supplier-product
  129. *
  130. * @param int $id_fourn Supplier Id
  131. * @return int < 0 if error, > 0 if ok
  132. */
  133. public function remove_fournisseur($id_fourn)
  134. {
  135. // phpcs:enable
  136. $ok = 1;
  137. $this->db->begin();
  138. $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
  139. $sql .= " WHERE fk_product = ".((int) $this->id)." AND fk_soc = ".((int) $id_fourn);
  140. dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG);
  141. $resql2 = $this->db->query($sql);
  142. if (!$resql2) {
  143. $this->error = $this->db->lasterror();
  144. $ok = 0;
  145. }
  146. if ($ok) {
  147. $this->db->commit();
  148. return 1;
  149. } else {
  150. $this->db->rollback();
  151. return -1;
  152. }
  153. }
  154. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  155. /**
  156. * Remove a price for a couple supplier-product
  157. *
  158. * @param int $rowid Line id of price
  159. * @return int <0 if KO, >0 if OK
  160. */
  161. public function remove_product_fournisseur_price($rowid)
  162. {
  163. // phpcs:enable
  164. global $conf, $user;
  165. $error = 0;
  166. $this->db->begin();
  167. // Call trigger
  168. $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_DELETE', $user);
  169. if ($result < 0) {
  170. $error++;
  171. }
  172. // End call triggers
  173. if (empty($error)) {
  174. $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
  175. $sql .= " WHERE rowid = ".((int) $rowid);
  176. dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG);
  177. $resql = $this->db->query($sql);
  178. if (!$resql) {
  179. $this->error = $this->db->lasterror();
  180. $error++;
  181. }
  182. }
  183. if (empty($error)) {
  184. $this->db->commit();
  185. return 1;
  186. } else {
  187. $this->db->rollback();
  188. return -1;
  189. }
  190. }
  191. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  192. /**
  193. * Modify the purchase price for a supplier
  194. *
  195. * @param float $qty Min quantity for which price is valid
  196. * @param float $buyprice Purchase price for the quantity min
  197. * @param User $user Object user user made changes
  198. * @param string $price_base_type HT or TTC
  199. * @param Societe $fourn Supplier
  200. * @param int $availability Product availability
  201. * @param string $ref_fourn Supplier ref
  202. * @param float $tva_tx New VAT Rate (For example 8.5. Should not be a string)
  203. * @param string $charges costs affering to product
  204. * @param float $remise_percent Discount regarding qty (percent)
  205. * @param float $remise Discount regarding qty (amount)
  206. * @param int $newnpr Set NPR or not
  207. * @param int $delivery_time_days Delay in days for delivery (max). May be '' if not defined.
  208. * @param string $supplier_reputation Reputation with this product to the defined supplier (empty, FAVORITE, DONOTORDER)
  209. * @param array $localtaxes_array Array with localtaxes info array('0'=>type1,'1'=>rate1,'2'=>type2,'3'=>rate2) (loaded by getLocalTaxesFromRate(vatrate, 0, ...) function).
  210. * @param string $newdefaultvatcode Default vat code
  211. * @param float $multicurrency_buyprice Purchase price for the quantity min in currency
  212. * @param string $multicurrency_price_base_type HT or TTC in currency
  213. * @param float $multicurrency_tx Rate currency
  214. * @param string $multicurrency_code Currency code
  215. * @param string $desc_fourn Custom description for product_fourn_price
  216. * @param string $barcode Barcode
  217. * @param int $fk_barcode_type Barcode type
  218. * @param array $options Extrafields of product fourn price
  219. * @return int <0 if KO, >=0 if OK
  220. */
  221. public function update_buyprice($qty, $buyprice, $user, $price_base_type, $fourn, $availability, $ref_fourn, $tva_tx, $charges = 0, $remise_percent = 0, $remise = 0, $newnpr = 0, $delivery_time_days = 0, $supplier_reputation = '', $localtaxes_array = array(), $newdefaultvatcode = '', $multicurrency_buyprice = 0, $multicurrency_price_base_type = 'HT', $multicurrency_tx = 1, $multicurrency_code = '', $desc_fourn = '', $barcode = '', $fk_barcode_type = '', $options = array())
  222. {
  223. // phpcs:enable
  224. global $conf, $langs;
  225. //global $mysoc;
  226. // Clean parameter
  227. if (empty($qty)) {
  228. $qty = 0;
  229. }
  230. if (empty($buyprice)) {
  231. $buyprice = 0;
  232. }
  233. if (empty($charges)) {
  234. $charges = 0;
  235. }
  236. if (empty($availability)) {
  237. $availability = 0;
  238. }
  239. if (empty($remise_percent)) {
  240. $remise_percent = 0;
  241. }
  242. if (empty($supplier_reputation) || $supplier_reputation == -1) {
  243. $supplier_reputation = '';
  244. }
  245. if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) {
  246. $delivery_time_days = '';
  247. }
  248. if ($price_base_type == 'TTC') {
  249. $ttx = $tva_tx;
  250. $buyprice = $buyprice / (1 + ($ttx / 100));
  251. }
  252. // Multicurrency
  253. $multicurrency_unitBuyPrice = null;
  254. $fk_multicurrency = null;
  255. if (!empty($conf->multicurrency->enabled)) {
  256. if (empty($multicurrency_tx)) {
  257. $multicurrency_tx = 1;
  258. }
  259. if (empty($multicurrency_buyprice)) {
  260. $multicurrency_buyprice = 0;
  261. }
  262. if ($multicurrency_price_base_type == 'TTC') {
  263. $ttx = $tva_tx;
  264. $multicurrency_buyprice = $multicurrency_buyprice / (1 + ($ttx / 100));
  265. }
  266. $multicurrency_buyprice = price2num($multicurrency_buyprice, 'MU');
  267. $multicurrency_unitBuyPrice = price2num($multicurrency_buyprice / $qty, 'MU');
  268. $buyprice = $multicurrency_buyprice / $multicurrency_tx;
  269. $fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $multicurrency_code);
  270. }
  271. $buyprice = price2num($buyprice, 'MU');
  272. $charges = price2num($charges, 'MU');
  273. $qty = price2num($qty, 'MS');
  274. $unitBuyPrice = price2num($buyprice / $qty, 'MU');
  275. // We can have a puchase ref that need to buy 100 min for a given price and with a packaging of 50.
  276. //$packaging = price2num(((empty($this->packaging) || $this->packaging < $qty) ? $qty : $this->packaging), 'MS');
  277. $packaging = price2num((empty($this->packaging) ? $qty : $this->packaging), 'MS');
  278. $error = 0;
  279. $now = dol_now();
  280. $newvat = $tva_tx;
  281. if (count($localtaxes_array) > 0) {
  282. $localtaxtype1 = $localtaxes_array['0'];
  283. $localtax1 = $localtaxes_array['1'];
  284. $localtaxtype2 = $localtaxes_array['2'];
  285. $localtax2 = $localtaxes_array['3'];
  286. } else { // old method. deprecated because ot can't retrieve type
  287. $localtaxtype1 = '0';
  288. $localtax1 = get_localtax($newvat, 1);
  289. $localtaxtype2 = '0';
  290. $localtax2 = get_localtax($newvat, 2);
  291. }
  292. if (empty($localtax1)) {
  293. $localtax1 = 0; // If = '' then = 0
  294. }
  295. if (empty($localtax2)) {
  296. $localtax2 = 0; // If = '' then = 0
  297. }
  298. // Check parameters
  299. if ($buyprice != '' && !is_numeric($buyprice)) {
  300. }
  301. $this->db->begin();
  302. if ($this->product_fourn_price_id > 0) {
  303. // check if price already logged, if not first log current price
  304. $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id);
  305. if (is_array($logPrices) && count($logPrices) == 0) {
  306. $currentPfp = new self($this->db);
  307. $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id);
  308. if ($result > 0 && $currentPfp->fourn_price != 0) {
  309. $currentPfpUser = new User($this->db);
  310. $result = $currentPfpUser->fetch($currentPfp->user_id);
  311. if ($result > 0) {
  312. $currentPfp->logPrice(
  313. $currentPfpUser,
  314. $currentPfp->date_creation,
  315. $currentPfp->fourn_price,
  316. $currentPfp->fourn_qty,
  317. $currentPfp->fourn_multicurrency_price,
  318. $currentPfp->fourn_multicurrency_unitprice,
  319. $currentPfp->fourn_multicurrency_tx,
  320. $currentPfp->fourn_multicurrency_id,
  321. $currentPfp->fourn_multicurrency_code
  322. );
  323. }
  324. }
  325. }
  326. $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
  327. $sql .= " SET fk_user = ".((int) $user->id)." ,";
  328. $sql .= " ref_fourn = '".$this->db->escape($ref_fourn)."',";
  329. $sql .= " desc_fourn = '".$this->db->escape($desc_fourn)."',";
  330. $sql .= " price = ".((float) $buyprice).",";
  331. $sql .= " quantity = ".((float) $qty).",";
  332. $sql .= " remise_percent = ".((float) $remise_percent).",";
  333. $sql .= " remise = ".((float) $remise).",";
  334. $sql .= " unitprice = ".((float) $unitBuyPrice).",";
  335. $sql .= " fk_availability = ".((int) $availability).",";
  336. $sql .= " multicurrency_price = ".(isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
  337. $sql .= " multicurrency_unitprice = ".(isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
  338. $sql .= " multicurrency_tx = ".(isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
  339. $sql .= " fk_multicurrency = ".(isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
  340. $sql .= " multicurrency_code = ".(isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
  341. $sql .= " entity = ".$conf->entity.",";
  342. $sql .= " tva_tx = ".price2num($tva_tx).",";
  343. // TODO Add localtax1 and localtax2
  344. //$sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').",";
  345. //$sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').",";
  346. //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$this->db->escape($localtaxtype1)."'":"'0'").",";
  347. //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$this->db->escape($localtaxtype2)."'":"'0'").",";
  348. $sql .= " default_vat_code=".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
  349. $sql .= " info_bits = ".((int) $newnpr).",";
  350. $sql .= " charges = ".((float) $charges).","; // deprecated
  351. $sql .= " delivery_time_days = ".($delivery_time_days != '' ? ((int) $delivery_time_days) : 'null').",";
  352. $sql .= " supplier_reputation = ".(empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
  353. $sql .= " barcode = ".(empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
  354. $sql .= " fk_barcode_type = ".(empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'");
  355. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  356. $sql .= ", packaging = ".(empty($packaging) ? 1 : $packaging);
  357. }
  358. $sql .= " WHERE rowid = ".((int) $this->product_fourn_price_id);
  359. if (!$error) {
  360. if (!empty($options) && is_array($options)) {
  361. $productfournisseurprice = new ProductFournisseurPrice($this->db);
  362. $res = $productfournisseurprice->fetch($this->product_fourn_price_id);
  363. if ($res > 0) {
  364. foreach ($options as $key=>$value) {
  365. $productfournisseurprice->array_options[$key] = $value;
  366. }
  367. $res = $productfournisseurprice->update($user);
  368. if ($res < 0) {
  369. $this->error = $productfournisseurprice->error;
  370. $this->errors = $productfournisseurprice->errors;
  371. $error++;
  372. }
  373. }
  374. }
  375. }
  376. // TODO Add price_base_type and price_ttc
  377. dol_syslog(get_class($this).'::update_buyprice update knowing id of line = product_fourn_price_id = '.$this->product_fourn_price_id, LOG_DEBUG);
  378. $resql = $this->db->query($sql);
  379. if ($resql) {
  380. // Call trigger
  381. $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_MODIFY', $user);
  382. if ($result < 0) {
  383. $error++;
  384. }
  385. // End call triggers
  386. if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) {
  387. $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
  388. if ($result < 0) {
  389. $error++;
  390. }
  391. }
  392. if (empty($error)) {
  393. $this->db->commit();
  394. return $this->product_fourn_price_id;
  395. } else {
  396. $this->db->rollback();
  397. return -1;
  398. }
  399. } else {
  400. $this->error = $this->db->error()." sql=".$sql;
  401. $this->db->rollback();
  402. return -2;
  403. }
  404. } else {
  405. dol_syslog(get_class($this).'::update_buyprice without knowing id of line, so we delete from company, quantity and supplier_ref and insert again', LOG_DEBUG);
  406. // Delete price for this quantity
  407. $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
  408. $sql .= " WHERE fk_soc = ".((int) $fourn->id)." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".((float) $qty)." AND entity = ".((int) $conf->entity);
  409. $resql = $this->db->query($sql);
  410. if ($resql) {
  411. // Add price for this quantity to supplier
  412. $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price(";
  413. $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
  414. $sql .= "datec, fk_product, fk_soc, ref_fourn, desc_fourn, fk_user, price, quantity, remise_percent, remise, unitprice, tva_tx, charges, fk_availability, default_vat_code, info_bits, entity, delivery_time_days, supplier_reputation, barcode, fk_barcode_type";
  415. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  416. $sql .= ", packaging";
  417. }
  418. $sql .= ") values(";
  419. $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
  420. $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
  421. $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
  422. $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
  423. $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
  424. $sql .= " '".$this->db->idate($now)."',";
  425. $sql .= " ".((int) $this->id).",";
  426. $sql .= " ".((int) $fourn->id).",";
  427. $sql .= " '".$this->db->escape($ref_fourn)."',";
  428. $sql .= " '".$this->db->escape($desc_fourn)."',";
  429. $sql .= " ".((int) $user->id).",";
  430. $sql .= " ".price2num($buyprice).",";
  431. $sql .= " ".((float) $qty).",";
  432. $sql .= " ".((float) $remise_percent).",";
  433. $sql .= " ".((float) $remise).",";
  434. $sql .= " ".price2num($unitBuyPrice).",";
  435. $sql .= " ".price2num($tva_tx).",";
  436. $sql .= " ".price2num($charges).",";
  437. $sql .= " ".((int) $availability).",";
  438. $sql .= " ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
  439. $sql .= " ".((int) $newnpr).",";
  440. $sql .= $conf->entity.",";
  441. $sql .= ($delivery_time_days != '' ? ((int) $delivery_time_days) : 'null').",";
  442. $sql .= (empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
  443. $sql .= (empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
  444. $sql .= (empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape($fk_barcode_type)."'");
  445. if (!empty($conf->global->PRODUCT_USE_SUPPLIER_PACKAGING)) {
  446. $sql .= ", ".(empty($this->packaging) ? '1' : "'".$this->db->escape($this->packaging)."'");
  447. }
  448. $sql .= ")";
  449. $this->product_fourn_price_id = 0;
  450. $resql = $this->db->query($sql);
  451. if ($resql) {
  452. $this->product_fourn_price_id = $this->db->last_insert_id(MAIN_DB_PREFIX."product_fournisseur_price");
  453. } else {
  454. $this->error = $this->db->lasterror();
  455. $error++;
  456. }
  457. if (!$error) {
  458. if (!empty($options) && is_array($options)) {
  459. $productfournisseurprice = new ProductFournisseurPrice($this->db);
  460. $res = $productfournisseurprice->fetch($this->product_fourn_price_id);
  461. if ($res > 0) {
  462. foreach ($options as $key=>$value) {
  463. $productfournisseurprice->array_options[$key] = $value;
  464. }
  465. $res = $productfournisseurprice->update($user);
  466. if ($res < 0) {
  467. $this->error = $productfournisseurprice->error;
  468. $this->errors = $productfournisseurprice->errors;
  469. $error++;
  470. }
  471. }
  472. }
  473. }
  474. if (!$error && empty($conf->global->PRODUCT_PRICE_SUPPLIER_NO_LOG)) {
  475. // Add record into log table
  476. // $this->product_fourn_price_id must be set
  477. $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, $multicurrency_unitBuyPrice, $multicurrency_tx, $fk_multicurrency, $multicurrency_code);
  478. if ($result < 0) {
  479. $error++;
  480. }
  481. }
  482. if (!$error) {
  483. // Call trigger
  484. $result = $this->call_trigger('SUPPLIER_PRODUCT_BUYPRICE_CREATE', $user);
  485. if ($result < 0) {
  486. $error++;
  487. }
  488. // End call triggers
  489. if (empty($error)) {
  490. $this->db->commit();
  491. return $this->product_fourn_price_id;
  492. } else {
  493. $this->db->rollback();
  494. return -1;
  495. }
  496. } else {
  497. $this->error = $this->db->lasterror()." sql=".$sql;
  498. $this->db->rollback();
  499. return -2;
  500. }
  501. } else {
  502. $this->error = $this->db->lasterror()." sql=".$sql;
  503. $this->db->rollback();
  504. return -1;
  505. }
  506. }
  507. }
  508. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  509. /**
  510. * Loads the price information of a provider
  511. *
  512. * @param int $rowid Line id
  513. * @param int $ignore_expression Ignores the math expression for calculating price and uses the db value instead
  514. * @return int < 0 if KO, 0 if OK but not found, > 0 if OK
  515. */
  516. public function fetch_product_fournisseur_price($rowid, $ignore_expression = 0)
  517. {
  518. // phpcs:enable
  519. global $conf;
  520. $sql = "SELECT pfp.rowid, pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.default_vat_code, pfp.info_bits as fourn_tva_npr, pfp.fk_availability,";
  521. $sql .= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,";
  522. $sql .= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,";
  523. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
  524. $sql .= " pfp.barcode, pfp.fk_barcode_type, pfp.packaging,";
  525. $sql .= " p.ref as product_ref, p.tosell as status, p.tobuy as status_buy";
  526. $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."product as p";
  527. $sql .= " WHERE pfp.rowid = ".(int) $rowid;
  528. $sql .= " AND pfp.fk_product = p.rowid";
  529. dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG);
  530. $resql = $this->db->query($sql);
  531. if ($resql) {
  532. $obj = $this->db->fetch_object($resql);
  533. if ($obj) {
  534. $this->product_fourn_price_id = $rowid;
  535. $this->id = $obj->fk_product;
  536. $this->fk_product = $obj->fk_product;
  537. $this->product_id = $obj->fk_product;
  538. $this->product_ref = $obj->product_ref;
  539. $this->status = $obj->status;
  540. $this->status_buy = $obj->status_buy;
  541. $this->fourn_id = $obj->fk_soc;
  542. $this->fourn_ref = $obj->ref_fourn; // deprecated
  543. $this->ref_supplier = $obj->ref_fourn;
  544. $this->desc_supplier = $obj->desc_fourn;
  545. $this->fourn_price = $obj->price;
  546. $this->fourn_charges = $obj->charges; // deprecated
  547. $this->fourn_qty = $obj->quantity;
  548. $this->fourn_remise_percent = $obj->remise_percent;
  549. $this->fourn_remise = $obj->remise;
  550. $this->fourn_unitprice = $obj->unitprice;
  551. $this->fourn_tva_tx = $obj->tva_tx;
  552. $this->fourn_tva_npr = $obj->fourn_tva_npr;
  553. // Add also localtaxes
  554. $this->fk_availability = $obj->fk_availability;
  555. $this->delivery_time_days = $obj->delivery_time_days;
  556. $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
  557. $this->supplier_reputation = $obj->supplier_reputation;
  558. $this->default_vat_code = $obj->default_vat_code;
  559. $this->user_id = $obj->fk_user;
  560. $this->date_creation = $this->db->jdate($obj->datec);
  561. $this->fourn_multicurrency_price = $obj->multicurrency_price;
  562. $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
  563. $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
  564. $this->fourn_multicurrency_id = $obj->fk_multicurrency;
  565. $this->fourn_multicurrency_code = $obj->multicurrency_code;
  566. if (!empty($conf->barcode->enabled)) {
  567. $this->fourn_barcode = $obj->barcode; // deprecated
  568. $this->fourn_fk_barcode_type = $obj->fk_barcode_type; // deprecated
  569. $this->supplier_barcode = $obj->barcode;
  570. $this->supplier_fk_barcode_type = $obj->fk_barcode_type;
  571. }
  572. $this->packaging = $obj->packaging;
  573. if (empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) {
  574. $priceparser = new PriceParser($this->db);
  575. $price_result = $priceparser->parseProductSupplier($this);
  576. if ($price_result >= 0) {
  577. $this->fourn_price = $price_result;
  578. //recalculation of unitprice, as probably the price changed...
  579. if ($this->fourn_qty != 0) {
  580. $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU');
  581. } else {
  582. $this->fourn_unitprice = "";
  583. }
  584. }
  585. }
  586. return 1;
  587. } else {
  588. return 0;
  589. }
  590. } else {
  591. $this->error = $this->db->lasterror();
  592. return -1;
  593. }
  594. }
  595. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  596. /**
  597. * List all supplier prices of a product
  598. *
  599. * @param int $prodid Id of product
  600. * @param string $sortfield Sort field
  601. * @param string $sortorder Sort order
  602. * @param int $limit Limit
  603. * @param int $offset Offset
  604. * @param int $socid Filter on a third party id
  605. * @return array Array of ProductFournisseur with new properties to define supplier price
  606. */
  607. public function list_product_fournisseur_price($prodid, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0, $socid = 0)
  608. {
  609. // phpcs:enable
  610. global $conf;
  611. $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id, p.ref as product_ref, p.tosell as status, p.tobuy as status_buy, ";
  612. $sql .= " pfp.rowid as product_fourn_pri_id, pfp.entity, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product as product_fourn_id, pfp.fk_supplier_price_expression,";
  613. $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.remise_percent, pfp.remise, pfp.tva_tx, pfp.fk_availability, pfp.charges, pfp.info_bits, pfp.delivery_time_days, pfp.supplier_reputation,";
  614. $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,";
  615. $sql .= " pfp.barcode, pfp.fk_barcode_type, pfp.packaging";
  616. $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."societe as s";
  617. $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
  618. $sql .= " AND pfp.fk_soc = s.rowid AND pfp.fk_product = p.rowid";
  619. $sql .= ($socid > 0 ? ' AND pfp.fk_soc = '.((int) $socid) : '');
  620. $sql .= " AND s.status = 1"; // only enabled company selected
  621. $sql .= " AND pfp.fk_product = ".((int) $prodid);
  622. if (empty($sortfield)) {
  623. $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price";
  624. } else {
  625. $sql .= $this->db->order($sortfield, $sortorder);
  626. }
  627. $sql .= $this->db->plimit($limit, $offset);
  628. dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG);
  629. $resql = $this->db->query($sql);
  630. if ($resql) {
  631. $retarray = array();
  632. while ($record = $this->db->fetch_array($resql)) {
  633. //define base attribute
  634. $prodfourn = new ProductFournisseur($this->db);
  635. $prodfourn->product_ref = $record["product_ref"];
  636. $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"];
  637. $prodfourn->status = $record["status"];
  638. $prodfourn->status_buy = $record["status_buy"];
  639. $prodfourn->product_fourn_id = $record["product_fourn_id"];
  640. $prodfourn->product_fourn_entity = $record["entity"];
  641. $prodfourn->ref_supplier = $record["ref_fourn"];
  642. $prodfourn->fourn_ref = $record["ref_fourn"];
  643. $prodfourn->desc_supplier = $record["desc_fourn"];
  644. $prodfourn->fourn_price = $record["price"];
  645. $prodfourn->fourn_qty = $record["quantity"];
  646. $prodfourn->fourn_remise_percent = $record["remise_percent"];
  647. $prodfourn->fourn_remise = $record["remise"];
  648. $prodfourn->fourn_unitprice = $record["unitprice"];
  649. $prodfourn->fourn_charges = $record["charges"]; // deprecated
  650. $prodfourn->fourn_tva_tx = $record["tva_tx"];
  651. $prodfourn->fourn_id = $record["fourn_id"];
  652. $prodfourn->fourn_name = $record["supplier_name"];
  653. $prodfourn->fk_availability = $record["fk_availability"];
  654. $prodfourn->delivery_time_days = $record["delivery_time_days"];
  655. $prodfourn->id = $prodid;
  656. $prodfourn->fourn_tva_npr = $record["info_bits"];
  657. $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
  658. $prodfourn->supplier_reputation = $record["supplier_reputation"];
  659. $prodfourn->fourn_date_creation = $this->db->jdate($record['datec']);
  660. $prodfourn->fourn_date_modification = $this->db->jdate($record['tms']);
  661. $prodfourn->fourn_multicurrency_price = $record["multicurrency_price"];
  662. $prodfourn->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
  663. $prodfourn->fourn_multicurrency_tx = $record["multicurrency_tx"];
  664. $prodfourn->fourn_multicurrency_id = $record["fk_multicurrency"];
  665. $prodfourn->fourn_multicurrency_code = $record["multicurrency_code"];
  666. $prodfourn->packaging = $record["packaging"];
  667. if (!empty($conf->barcode->enabled)) {
  668. $prodfourn->supplier_barcode = $record["barcode"];
  669. $prodfourn->supplier_fk_barcode_type = $record["fk_barcode_type"];
  670. }
  671. if (!empty($conf->dynamicprices->enabled) && !empty($prodfourn->fk_supplier_price_expression)) {
  672. $priceparser = new PriceParser($this->db);
  673. $price_result = $priceparser->parseProductSupplier($prodfourn);
  674. if ($price_result >= 0) {
  675. $prodfourn->fourn_price = $price_result;
  676. $prodfourn->fourn_unitprice = null; //force recalculation of unitprice, as probably the price changed...
  677. }
  678. }
  679. if (!isset($prodfourn->fourn_unitprice)) {
  680. if ($prodfourn->fourn_qty != 0) {
  681. $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU');
  682. } else {
  683. $prodfourn->fourn_unitprice = "";
  684. }
  685. }
  686. $retarray[] = $prodfourn;
  687. }
  688. $this->db->free($resql);
  689. return $retarray;
  690. } else {
  691. $this->error = $this->db->error();
  692. return -1;
  693. }
  694. }
  695. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  696. /**
  697. * Load properties for minimum price
  698. *
  699. * @param int $prodid Product id
  700. * @param int $qty Minimum quantity
  701. * @param int $socid get min price for specific supplier
  702. * @return int <0 if KO, 0=Not found of no product id provided, >0 if OK
  703. */
  704. public function find_min_price_product_fournisseur($prodid, $qty = 0, $socid = 0)
  705. {
  706. // phpcs:enable
  707. global $conf;
  708. if (empty($prodid)) {
  709. dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING);
  710. return 0;
  711. }
  712. $this->product_fourn_price_id = '';
  713. $this->product_fourn_id = '';
  714. $this->fourn_ref = '';
  715. $this->fourn_price = '';
  716. $this->fourn_qty = '';
  717. $this->fourn_remise_percent = '';
  718. $this->fourn_remise = '';
  719. $this->fourn_unitprice = '';
  720. $this->fourn_id = '';
  721. $this->fourn_name = '';
  722. $this->delivery_time_days = '';
  723. $this->id = '';
  724. $this->fourn_multicurrency_price = '';
  725. $this->fourn_multicurrency_unitprice = '';
  726. $this->fourn_multicurrency_tx = '';
  727. $this->fourn_multicurrency_id = '';
  728. $this->fourn_multicurrency_code = '';
  729. $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
  730. $sql .= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,";
  731. $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,";
  732. $sql .= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days";
  733. $sql .= " ,pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
  734. $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
  735. $sql .= " WHERE s.entity IN (".getEntity('societe').")";
  736. $sql .= " AND pfp.entity IN (".getEntity('productsupplierprice').")";
  737. $sql .= " AND pfp.fk_product = ".((int) $prodid);
  738. $sql .= " AND pfp.fk_soc = s.rowid";
  739. $sql .= " AND s.status = 1"; // only enabled society
  740. if ($qty > 0) {
  741. $sql .= " AND pfp.quantity <= ".((float) $qty);
  742. }
  743. if ($socid > 0) {
  744. $sql .= ' AND pfp.fk_soc = '.((int) $socid);
  745. }
  746. dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG);
  747. $resql = $this->db->query($sql);
  748. if ($resql) {
  749. $record_array = array();
  750. //Store each record to array for later search of min
  751. while ($record = $this->db->fetch_array($resql)) {
  752. $record_array[] = $record;
  753. }
  754. if (count($record_array) == 0) {
  755. $this->db->free($resql);
  756. return 0;
  757. } else {
  758. $min = -1;
  759. foreach ($record_array as $record) {
  760. $fourn_price = $record["price"];
  761. // calculate unit price for quantity 1
  762. $fourn_unitprice = $record["unitprice"];
  763. $fourn_unitprice_with_discount = $record["unitprice"] * (1 - $record["remise_percent"] / 100);
  764. if (!empty($conf->dynamicprices->enabled) && !empty($record["fk_supplier_price_expression"])) {
  765. $prod_supplier = new ProductFournisseur($this->db);
  766. $prod_supplier->product_fourn_price_id = $record["product_fourn_price_id"];
  767. $prod_supplier->id = $prodid;
  768. $prod_supplier->fourn_qty = $record["quantity"];
  769. $prod_supplier->fourn_tva_tx = $record["tva_tx"];
  770. $prod_supplier->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
  771. $priceparser = new PriceParser($this->db);
  772. $price_result = $priceparser->parseProductSupplier($prod_supplier);
  773. if ($price_result >= 0) {
  774. $fourn_price = price2num($price_result, 'MU');
  775. if ($record["quantity"] != 0) {
  776. $fourn_unitprice = price2num($fourn_price / $record["quantity"], 'MU');
  777. } else {
  778. $fourn_unitprice = $fourn_price;
  779. }
  780. $fourn_unitprice_with_discount = $fourn_unitprice * (1 - $record["remise_percent"] / 100);
  781. }
  782. }
  783. if ($fourn_unitprice < $min || $min == -1) {
  784. $this->product_fourn_price_id = $record["product_fourn_price_id"];
  785. $this->ref_supplier = $record["ref_fourn"];
  786. $this->ref_fourn = $record["ref_fourn"]; // deprecated
  787. $this->fourn_ref = $record["ref_fourn"]; // deprecated
  788. $this->fourn_price = $fourn_price;
  789. $this->fourn_qty = $record["quantity"];
  790. $this->fourn_remise_percent = $record["remise_percent"];
  791. $this->fourn_remise = $record["remise"];
  792. $this->fourn_unitprice = $fourn_unitprice;
  793. $this->fourn_unitprice_with_discount = $fourn_unitprice_with_discount;
  794. $this->fourn_charges = $record["charges"]; // deprecated
  795. $this->fourn_tva_tx = $record["tva_tx"];
  796. $this->fourn_id = $record["fourn_id"];
  797. $this->fourn_name = $record["supplier_name"];
  798. $this->delivery_time_days = $record["delivery_time_days"];
  799. $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
  800. $this->id = $prodid;
  801. $this->fourn_multicurrency_price = $record["multicurrency_price"];
  802. $this->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
  803. $this->fourn_multicurrency_tx = $record["multicurrency_tx"];
  804. $this->fourn_multicurrency_id = $record["fk_multicurrency"];
  805. $this->fourn_multicurrency_code = $record["multicurrency_code"];
  806. $min = $fourn_unitprice;
  807. }
  808. }
  809. }
  810. $this->db->free($resql);
  811. return 1;
  812. } else {
  813. $this->error = $this->db->error();
  814. return -1;
  815. }
  816. }
  817. /**
  818. * Sets the supplier price expression
  819. *
  820. * @param int $expression_id Expression
  821. * @return int <0 if KO, >0 if OK
  822. */
  823. public function setSupplierPriceExpression($expression_id)
  824. {
  825. global $conf;
  826. // Clean parameters
  827. $this->db->begin();
  828. $expression_id = $expression_id != 0 ? $expression_id : 'NULL';
  829. $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
  830. $sql .= " SET fk_supplier_price_expression = ".((int) $expression_id);
  831. $sql .= " WHERE rowid = ".((int) $this->product_fourn_price_id);
  832. dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG);
  833. $resql = $this->db->query($sql);
  834. if ($resql) {
  835. $this->db->commit();
  836. return 1;
  837. } else {
  838. $this->error = $this->db->error()." sql=".$sql;
  839. $this->db->rollback();
  840. return -1;
  841. }
  842. }
  843. /**
  844. * Display supplier of product
  845. *
  846. * @param int $withpicto Add picto
  847. * @param string $option Target of link ('', 'customer', 'prospect', 'supplier')
  848. * @param int $maxlen Max length of name
  849. * @param integer $notooltip 1=Disable tooltip
  850. * @return string String with supplier price
  851. * TODO Remove this method. Use getNomUrl directly.
  852. */
  853. public function getSocNomUrl($withpicto = 0, $option = 'supplier', $maxlen = 0, $notooltip = 0)
  854. {
  855. $thirdparty = new Fournisseur($this->db);
  856. $thirdparty->fetch($this->fourn_id);
  857. return $thirdparty->getNomUrl($withpicto, $option, $maxlen, $notooltip);
  858. }
  859. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  860. /**
  861. * Display price of product
  862. *
  863. * @param int $showunitprice Show "Unit price" into output string
  864. * @param int $showsuptitle Show "Supplier" into output string
  865. * @param int $maxlen Max length of name
  866. * @param integer $notooltip 1=Disable tooltip
  867. * @param array $productFournList list of ProductFournisseur objects
  868. * to display in table format.
  869. * @return string String with supplier price
  870. */
  871. public function display_price_product_fournisseur($showunitprice = 1, $showsuptitle = 1, $maxlen = 0, $notooltip = 0, $productFournList = array())
  872. {
  873. // phpcs:enable
  874. global $conf, $langs;
  875. $out = '';
  876. $langs->load("suppliers");
  877. if (count($productFournList) > 0) {
  878. $out .= '<table class="nobordernopadding" width="100%">';
  879. $out .= '<tr><td class="liste_titre right">'.($showunitprice ? $langs->trans("Price").' '.$langs->trans("HT") : '').'</td>';
  880. $out .= '<td class="liste_titre right">'.($showunitprice ? $langs->trans("QtyMin") : '').'</td>';
  881. $out .= '<td class="liste_titre">'.$langs->trans("Supplier").'</td>';
  882. $out .= '<td class="liste_titre">'.$langs->trans("SupplierRef").'</td></tr>';
  883. foreach ($productFournList as $productFourn) {
  884. $out .= '<tr><td class="right">'.($showunitprice ?price($productFourn->fourn_unitprice * (1 - $productFourn->fourn_remise_percent / 100) - $productFourn->fourn_remise) : '').'</td>';
  885. $out .= '<td class="right">'.($showunitprice ? $productFourn->fourn_qty : '').'</td>';
  886. $out .= '<td>'.$productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).'</td>';
  887. $out .= '<td>'.$productFourn->fourn_ref.'<td></tr>';
  888. }
  889. $out .= '</table>';
  890. } else {
  891. $out = ($showunitprice ? price($this->fourn_unitprice * (1 - $this->fourn_remise_percent / 100) + $this->fourn_remise, 0, $langs, 1, -1, -1, $conf->currency).' '.$langs->trans("HT").' &nbsp; <span class="opacitymedium">(</span>' : '');
  892. $out .= ($showsuptitle ? '<span class="opacitymedium">'.$langs->trans("Supplier").'</span>: ' : '').$this->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).' / <span class="opacitymedium">'.$langs->trans("SupplierRef").'</span>: '.$this->ref_supplier;
  893. $out .= ($showunitprice ? '<span class="opacitymedium">)</span>' : '');
  894. }
  895. return $out;
  896. }
  897. /**
  898. * Function used to replace a thirdparty id with another one.
  899. *
  900. * @param DoliDB $db Database handler
  901. * @param int $origin_id Old thirdparty id
  902. * @param int $dest_id New thirdparty id
  903. * @return bool
  904. */
  905. public static function replaceThirdparty(DoliDB $db, $origin_id, $dest_id)
  906. {
  907. $tables = array(
  908. 'product_fournisseur_price'
  909. );
  910. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  911. }
  912. /**
  913. * Function used to replace a product id with another one.
  914. *
  915. * @param DoliDB $db Database handler
  916. * @param int $origin_id Old product id
  917. * @param int $dest_id New product id
  918. * @return bool
  919. */
  920. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  921. {
  922. $tables = array(
  923. 'product_fournisseur_price'
  924. );
  925. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  926. }
  927. /**
  928. * List supplier prices log of a supplier price
  929. *
  930. * @param int $product_fourn_price_id Id of supplier price
  931. * @param string $sortfield Sort field
  932. * @param string $sortorder Sort order
  933. * @param int $limit Limit
  934. * @param int $offset Offset
  935. * @return array Array of Log prices
  936. */
  937. public function listProductFournisseurPriceLog($product_fourn_price_id, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
  938. {
  939. $sql = "SELECT";
  940. $sql .= " u.lastname,";
  941. $sql .= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec,";
  942. $sql .= " pfpl.price, pfpl.quantity,";
  943. $sql .= " pfpl.fk_multicurrency, pfpl.multicurrency_code, pfpl.multicurrency_tx, pfpl.multicurrency_price, pfpl.multicurrency_unitprice";
  944. $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price_log as pfpl,";
  945. $sql .= " ".MAIN_DB_PREFIX."product_fournisseur_price as pfp,";
  946. $sql .= " ".MAIN_DB_PREFIX."user as u";
  947. $sql .= " WHERE pfp.entity IN (".getEntity('productprice').")";
  948. $sql .= " AND pfpl.fk_user = u.rowid";
  949. $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur";
  950. $sql .= " AND pfpl.fk_product_fournisseur = ".((int) $product_fourn_price_id);
  951. if (empty($sortfield)) {
  952. $sql .= " ORDER BY pfpl.datec";
  953. } else {
  954. $sql .= $this->db->order($sortfield, $sortorder);
  955. }
  956. $sql .= $this->db->plimit($limit, $offset);
  957. dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG);
  958. $resql = $this->db->query($sql);
  959. if ($resql) {
  960. $retarray = array();
  961. while ($obj = $this->db->fetch_object($resql)) {
  962. $tmparray = array();
  963. $tmparray['rowid'] = $obj->rowid;
  964. $tmparray['supplier_ref'] = $obj->supplier_ref;
  965. $tmparray['datec'] = $this->db->jdate($obj->datec);
  966. $tmparray['lastname'] = $obj->lastname;
  967. $tmparray['price'] = $obj->price;
  968. $tmparray['quantity'] = $obj->quantity;
  969. $tmparray['fk_multicurrency'] = $obj->fk_multicurrency;
  970. $tmparray['multicurrency_code'] = $obj->multicurrency_code;
  971. $tmparray['multicurrency_tx'] = $obj->multicurrency_tx;
  972. $tmparray['multicurrency_price'] = $obj->multicurrency_price;
  973. $tmparray['multicurrency_unitprice'] = $obj->multicurrency_unitprice;
  974. $retarray[] = $tmparray;
  975. }
  976. $this->db->free($resql);
  977. return $retarray;
  978. } else {
  979. $this->error = $this->db->error();
  980. return -1;
  981. }
  982. }
  983. /**
  984. * Display log price of product supplier price
  985. *
  986. * @param array $productFournLogList list of ProductFournisseur price log objects
  987. * to display in table format.
  988. * @return string HTML String with supplier price
  989. */
  990. public function displayPriceProductFournisseurLog($productFournLogList = array())
  991. {
  992. global $conf, $langs;
  993. $out = '';
  994. $langs->load("suppliers");
  995. if (count($productFournLogList) > 0) {
  996. $out .= '<table class="noborder centpercent">';
  997. $out .= '<tr class="liste_titre"><td class="liste_titre">'.$langs->trans("Date").'</td>';
  998. $out .= '<td class="liste_titre right">'.$langs->trans("Price").'</td>';
  999. //$out .= '<td class="liste_titre right">'.$langs->trans("QtyMin").'</td>';
  1000. $out .= '<td class="liste_titre">'.$langs->trans("User").'</td></tr>';
  1001. foreach ($productFournLogList as $productFournLog) {
  1002. $out .= '<tr><td>'.dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser').'</td>';
  1003. $out .= '<td class="right">'.price($productFournLog['price'], 0, $langs, 1, -1, -1, $conf->currency);
  1004. if ($productFournLog['multicurrency_code'] != $conf->currency) {
  1005. $out .= ' ('.price($productFournLog['multicurrency_price'], 0, $langs, 1, -1, -1, $productFournLog['multicurrency_code']).')';
  1006. }
  1007. $out .= '</td>';
  1008. //$out.= '<td class="right">'.$productFournLog['quantity'].'</td>';
  1009. $out .= '<td>'.$productFournLog['lastname'].'</td></tr>';
  1010. }
  1011. $out .= '</table>';
  1012. }
  1013. return $out;
  1014. }
  1015. /**
  1016. * Return a link to the object card (with optionaly the picto).
  1017. * Used getNomUrl of ProductFournisseur if a specific supplier ref is loaded. Otherwise use Product->getNomUrl().
  1018. *
  1019. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1020. * @param string $option On what the link point to ('nolink', ...)
  1021. * @param int $notooltip 1=Disable tooltip
  1022. * @param string $morecss Add more css on link
  1023. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1024. * @return string String with URL
  1025. */
  1026. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1027. {
  1028. global $db, $conf, $langs, $hookmanager;
  1029. if (!empty($conf->dol_no_mouse_hover)) {
  1030. $notooltip = 1; // Force disable tooltips
  1031. }
  1032. $result = '';
  1033. $label = '';
  1034. if (!empty($this->entity)) {
  1035. $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
  1036. if ($this->nbphoto > 0) {
  1037. $label .= '<div class="photointooltip">';
  1038. $label .= $tmpphoto;
  1039. $label .= '</div><div style="clear: both;"></div>';
  1040. }
  1041. }
  1042. if ($this->type == Product::TYPE_PRODUCT) {
  1043. $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
  1044. } elseif ($this->type == Product::TYPE_SERVICE) {
  1045. $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
  1046. }
  1047. if (isset($this->status) && isset($this->status_buy)) {
  1048. $label .= ' '.$this->getLibStatut(5, 0);
  1049. $label .= ' '.$this->getLibStatut(5, 1);
  1050. }
  1051. if (!empty($this->ref)) {
  1052. $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.($this->ref ? $this->ref : $this->product_ref);
  1053. }
  1054. if (!empty($this->label)) {
  1055. $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
  1056. }
  1057. $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
  1058. if ($this->type == Product::TYPE_PRODUCT || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) {
  1059. if (!empty($conf->productbatch->enabled)) {
  1060. $langs->load("productbatch");
  1061. $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
  1062. }
  1063. }
  1064. if (!empty($conf->barcode->enabled)) {
  1065. $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
  1066. }
  1067. if ($this->type == Product::TYPE_PRODUCT) {
  1068. if ($this->weight) {
  1069. $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
  1070. }
  1071. $labelsize = "";
  1072. if ($this->length) {
  1073. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
  1074. }
  1075. if ($this->width) {
  1076. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
  1077. }
  1078. if ($this->height) {
  1079. $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
  1080. }
  1081. if ($labelsize) {
  1082. $label .= "<br>".$labelsize;
  1083. }
  1084. $labelsurfacevolume = "";
  1085. if ($this->surface) {
  1086. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
  1087. }
  1088. if ($this->volume) {
  1089. $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
  1090. }
  1091. if ($labelsurfacevolume) {
  1092. $label .= "<br>".$labelsurfacevolume;
  1093. }
  1094. }
  1095. if (!empty($conf->accounting->enabled) && $this->status) {
  1096. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  1097. $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
  1098. $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
  1099. $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
  1100. }
  1101. if (!empty($conf->accounting->enabled) && $this->status_buy) {
  1102. include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
  1103. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
  1104. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
  1105. $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
  1106. }
  1107. $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id, 'pfpl.datec', 'DESC'); // set sort order here
  1108. if (is_array($logPrices) && count($logPrices) > 0) {
  1109. $label .= '<br><br>';
  1110. $label .= '<u>'.$langs->trans("History").'</u>';
  1111. $label .= $this->displayPriceProductFournisseurLog($logPrices);
  1112. }
  1113. $url = dol_buildpath('/product/fournisseurs.php', 1).'?id='.$this->id.'&action=add_price&token='.newToken().'&socid='.$this->fourn_id.'&rowid='.$this->product_fourn_price_id;
  1114. if ($option != 'nolink') {
  1115. // Add param to save lastsearch_values or not
  1116. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1117. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1118. $add_save_lastsearch_values = 1;
  1119. }
  1120. if ($add_save_lastsearch_values) {
  1121. $url .= '&save_lastsearch_values=1';
  1122. }
  1123. }
  1124. $linkclose = '';
  1125. if (empty($notooltip)) {
  1126. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1127. $label = $langs->trans("SupplierRef");
  1128. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1129. }
  1130. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1131. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1132. } else {
  1133. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1134. }
  1135. $linkstart = '<a href="'.$url.'"';
  1136. $linkstart .= $linkclose.'>';
  1137. $linkend = '</a>';
  1138. $result .= $linkstart;
  1139. if ($withpicto) {
  1140. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  1141. }
  1142. if ($withpicto != 2) {
  1143. $result .= $this->ref.($this->ref_supplier ? ' ('.$this->ref_supplier.')' : '');
  1144. }
  1145. $result .= $linkend;
  1146. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1147. global $action;
  1148. $hookmanager->initHooks(array($this->element . 'dao'));
  1149. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1150. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1151. if ($reshook > 0) {
  1152. $result = $hookmanager->resPrint;
  1153. } else {
  1154. $result .= $hookmanager->resPrint;
  1155. }
  1156. return $result;
  1157. }
  1158. /**
  1159. * Private function to log price history
  1160. *
  1161. * @param User $user Object user who adds/changes price
  1162. * @param integer $datec date create
  1163. * @param float $buyprice price for qty
  1164. * @param float $qty qty for price
  1165. * @param float $multicurrency_buyprice Purchase price for the quantity min in currency
  1166. * @param float $multicurrency_unitBuyPrice Unit Purchase price in currency
  1167. * @param float $multicurrency_tx Rate currency
  1168. * @param int $fk_multicurrency key multi currency
  1169. * @param string $multicurrency_code Currency code
  1170. *
  1171. * @return int < 0 NOK > 0 OK
  1172. */
  1173. private function logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice = null, $multicurrency_unitBuyPrice = null, $multicurrency_tx = null, $fk_multicurrency = null, $multicurrency_code = null)
  1174. {
  1175. // Add record into log table
  1176. $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log(";
  1177. $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
  1178. $sql .= "datec, fk_product_fournisseur,fk_user,price,quantity)";
  1179. $sql .= "values(";
  1180. $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
  1181. $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
  1182. $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape($multicurrency_tx)."'" : '1').",";
  1183. $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape($fk_multicurrency)."'" : 'null').",";
  1184. $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
  1185. $sql .= "'".$this->db->idate($datec)."',";
  1186. $sql .= " ".((int) $this->product_fourn_price_id).",";
  1187. $sql .= " ".$user->id.",";
  1188. $sql .= " ".price2num($buyprice).",";
  1189. $sql .= " ".price2num($qty);
  1190. $sql .= ")";
  1191. $resql = $this->db->query($sql);
  1192. if (!$resql) {
  1193. return -1;
  1194. } else {
  1195. return 1;
  1196. }
  1197. }
  1198. }