dolibarr 25.0.0-alpha
fournisseur.product.class.php
Go to the documentation of this file.
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-2023 Charlene Benke <charlene@patas-monkey.com>
9 * Copyright (C) 2019-2026 Frédéric France <frederic.france@free.fr>
10 * Copyright (C) 2020 Pierre Ardoin <mapiolca@me.com>
11 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
12 *
13 * This program is free software; you can redistribute it and/or modify
14 * it under the terms of the GNU General Public License as published by
15 * the Free Software Foundation; either version 3 of the License, or
16 * (at your option) any later version.
17 *
18 * This program is distributed in the hope that it will be useful,
19 * but WITHOUT ANY WARRANTY; without even the implied warranty of
20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 * GNU General Public License for more details.
22 *
23 * You should have received a copy of the GNU General Public License
24 * along with this program. If not, see <https://www.gnu.org/licenses/>.
25 */
26
33require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
34require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
35require_once DOL_DOCUMENT_ROOT.'/product/class/productfournisseurprice.class.php';
36
37
42{
46 public $db;
47
52 public $TRIGGER_PREFIX = 'PRODUCT'; // We use parent because parent method can still have the parent prefix
53
57 public $error = '';
58
62 public $product_fourn_price_id;
63
67 public $id;
68
74 public $fourn_ref;
75
79 public $delivery_time_days;
80
84 public $ref_supplier;
85
89 public $desc_supplier;
90
94 public $vatrate_supplier;
95
101 public $fk_product;
102
106 public $product_id;
107
111 public $product_ref;
112
116 public $fourn_id;
117
121 public $fourn_name;
122
126 public $fourn_qty;
127
131 public $fourn_pu;
132
136 public $fourn_price;
137
141 public $fourn_remise_percent;
142
146 public $fourn_remise;
147
151 public $fourn_charges; // when getDolGlobalString('PRODUCT_CHARGES') is set
152
153
154 /* Properties found into product_fournisseur_price */
155
159 public $product_fourn_id;
160
164 public $product_fourn_entity;
165
169 public $product_fourn_packaging;
170
171
175 public $user_id;
176
180 public $fk_availability;
181
185 public $fourn_unitprice;
189 public $fourn_unitprice_with_discount; // not saved into database
193 public $fourn_tva_tx;
197 public $fourn_tva_npr;
198
202 public $fk_supplier_price_expression;
203
207 public $supplier_reputation;
208
212 public $reputations = array();
213
214 // Multicurrency
215
219 public $fourn_multicurrency_id;
220
224 public $fourn_multicurrency_code;
228 public $fourn_multicurrency_tx;
232 public $fourn_multicurrency_price;
236 public $fourn_multicurrency_unitprice;
237
243 public $fourn_barcode;
244
248 public $supplier_barcode;
249
255 public $fourn_fk_barcode_type;
256
260 public $supplier_fk_barcode_type;
261
265 public $labelStatusShort;
269 public $labelStatus;
270
271 const STATUS_OPEN = 1;
272 const STATUS_CANCELED = 0;
273
274
280 public function __construct($db)
281 {
282 global $langs;
283
284 $this->db = $db;
285 $langs->load("suppliers");
286 $this->reputations = array('-1' => '', 'FAVORITE' => $langs->trans('Favorite'), 'NOTTHGOOD' => $langs->trans('NotTheGoodQualitySupplier'), 'DONOTORDER' => $langs->trans('DoNotOrderThisProductToThisSupplier'));
287 }
288
289 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
296 public function remove_fournisseur($id_fourn)
297 {
298 // phpcs:enable
299 $ok = 1;
300
301 $this->db->begin();
302
303 $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
304 $sql .= " WHERE fk_product = ".((int) $this->id)." AND fk_soc = ".((int) $id_fourn);
305
306 dol_syslog(get_class($this)."::remove_fournisseur", LOG_DEBUG);
307 $resql2 = $this->db->query($sql);
308 if (!$resql2) {
309 $this->error = $this->db->lasterror();
310 $ok = 0;
311 }
312
313 if ($ok) {
314 $this->db->commit();
315 return 1;
316 } else {
317 $this->db->rollback();
318 return -1;
319 }
320 }
321
322
323 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
330 public function remove_product_fournisseur_price($rowid)
331 {
332 // phpcs:enable
333 global $user;
334
335 $error = 0;
336
337 // When called on a loaded product, the price line must be one of its own
338 if ($this->id > 0) {
339 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
340 $sql .= " WHERE rowid = ".((int) $rowid)." AND fk_product = ".((int) $this->id);
341 $resql = $this->db->query($sql);
342 if (!$resql || !$this->db->num_rows($resql)) {
343 $this->error = 'ErrorRecordNotFound';
344 return -1;
345 }
346 }
347
348 $this->db->begin();
349
350 // Call trigger
351 $result = $this->call_trigger('PRODUCT_BUYPRICE_DELETE', $user);
352 if ($result < 0) {
353 $error++;
354 }
355 // End call triggers
356
357 if (empty($error)) {
358 $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
359 $sql .= " WHERE rowid = ".((int) $rowid);
360
361 dol_syslog(get_class($this)."::remove_product_fournisseur_price", LOG_DEBUG);
362 $resql = $this->db->query($sql);
363 if (!$resql) {
364 $this->error = $this->db->lasterror();
365 $error++;
366 }
367 }
368
369 if (empty($error)) {
370 $this->db->commit();
371 return 1;
372 } else {
373 $this->db->rollback();
374 return -1;
375 }
376 }
377
378
379 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
409 public function update_buyprice(
410 $qty,
411 $buyprice,
412 $user,
413 $price_base_type,
414 $fourn,
415 $availability,
416 $ref_fourn,
417 $tva_tx,
418 $charges = 0,
419 $remise_percent = 0,
420 $remise = 0,
421 $newnpr = 0,
422 $delivery_time_days = 0,
423 $supplier_reputation = '',
424 $localtaxes_array = array(),
425 $newdefaultvatcode = '',
426 $multicurrency_buyprice = 0,
427 $multicurrency_price_base_type = 'HT',
428 $multicurrency_tx = 1,
429 $multicurrency_code = '',
430 $desc_fourn = '',
431 $barcode = '',
432 $fk_barcode_type = 0,
433 $options = array()
434 ) {
435 // phpcs:enable
436 global $conf;
437 //global $mysoc;
438
439 // Clean parameter
440 if (empty($qty)) {
441 $qty = 0;
442 }
443 if (empty($buyprice)) {
444 $buyprice = 0;
445 }
446 if (empty($charges)) {
447 $charges = 0;
448 }
449 if (empty($availability)) {
450 $availability = 0;
451 }
452 if (empty($remise_percent)) {
453 $remise_percent = 0;
454 }
455 if (empty($supplier_reputation) || $supplier_reputation == -1) {
456 $supplier_reputation = '';
457 }
458 if ($delivery_time_days != '' && !is_numeric($delivery_time_days)) {
459 $delivery_time_days = 0;
460 }
461 if ($price_base_type == 'TTC') {
462 $ttx = $tva_tx;
463 $buyprice /= (1 + ($ttx / 100));
464 }
465
466 // Multicurrency
467 $multicurrency_unitBuyPrice = null;
468 $fk_multicurrency = null;
469 if (isModEnabled("multicurrency")) {
470 if (empty($multicurrency_tx)) {
471 $multicurrency_tx = 1;
472 }
473 if (empty($multicurrency_buyprice)) {
474 $multicurrency_buyprice = 0;
475 }
476 if ($multicurrency_price_base_type == 'TTC') {
477 $ttx = $tva_tx;
478 $multicurrency_buyprice /= (1 + ($ttx / 100));
479 }
480 $multicurrency_buyprice = (float) price2num($multicurrency_buyprice, 'MU');
481 $multicurrency_unitBuyPrice = (float) price2num((float) $multicurrency_buyprice / $qty, 'MU');
482
483 $buyprice = (float) $multicurrency_buyprice / $multicurrency_tx;
484 $fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $multicurrency_code);
485 }
486
487 $buyprice = (float) price2num($buyprice, 'MU');
488 $charges = (float) price2num($charges, 'MU');
489 $qty = (float) price2num($qty, 'MS');
490 $unitBuyPrice = (float) price2num($buyprice / $qty, 'MU');
491
492 // We can have a purchase ref that need to buy 100 min for a given price and with a packaging of 50.
493 $packaging = price2num((empty($this->product_fourn_packaging) ? $qty : $this->product_fourn_packaging), 'MS');
494
495 $error = 0;
496 $now = dol_now();
497
498 $newvat = $tva_tx;
499
500 if (count($localtaxes_array) > 0) {
501 $localtaxtype1 = $localtaxes_array['0'];
502 $localtax1 = $localtaxes_array['1'];
503 $localtaxtype2 = $localtaxes_array['2'];
504 $localtax2 = $localtaxes_array['3'];
505 } else { // old method. deprecated because it can't retrieve type
506 $localtaxtype1 = '0';
507 $localtax1 = get_localtax($newvat, 1);
508 $localtaxtype2 = '0';
509 $localtax2 = get_localtax($newvat, 2);
510 }
511 if (empty($localtax1)) {
512 $localtax1 = 0; // If = '' then = 0
513 }
514 if (empty($localtax2)) {
515 $localtax2 = 0; // If = '' then = 0
516 }
517
518 $this->db->begin();
519
520 if (empty($this->product_fourn_price_id)) {
521 // Reuse the price line of this product, supplier, supplier ref and quantity, so its history is kept
522 $sql = "SELECT rowid FROM ".$this->db->prefix()."product_fournisseur_price";
523 $sql .= " WHERE fk_product = ".((int) $this->id)." AND fk_soc = ".((int) $fourn->id)." AND ref_fourn = '".$this->db->escape($ref_fourn)."'";
524 $sql .= " AND quantity = ".((float) $qty)." AND entity = ".((int) $conf->entity);
525 $resql = $this->db->query($sql);
526 $obj = ($resql ? $this->db->fetch_object($resql) : null);
527 $this->product_fourn_price_id = ($obj ? $obj->rowid : 0);
528 }
529
530 if ($this->product_fourn_price_id > 0) {
531 // check if price already logged, if not first log current price
532 $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id);
533 if (is_array($logPrices) && count($logPrices) == 0) {
534 $currentPfp = new self($this->db);
535 $result = $currentPfp->fetch_product_fournisseur_price($this->product_fourn_price_id);
536 if ($result > 0 && $currentPfp->fourn_price != 0) {
537 $currentPfpUser = new User($this->db);
538 $result = $currentPfpUser->fetch($currentPfp->user_id);
539 if ($result > 0) {
540 $currentPfp->logPrice(
541 $currentPfpUser,
542 $currentPfp->date_creation,
543 (float) $currentPfp->fourn_price,
544 $currentPfp->fourn_qty,
545 $currentPfp->fourn_multicurrency_price,
546 $currentPfp->fourn_multicurrency_unitprice,
547 $currentPfp->fourn_multicurrency_tx,
548 $currentPfp->fourn_multicurrency_id,
549 $currentPfp->fourn_multicurrency_code
550 );
551 }
552 }
553 }
554 $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
555 $sql .= " SET fk_user = ".((int) $user->id)." ,";
556 $sql .= " datec = '".$this->db->idate($now)."' ,"; // Note: Even if this is an update, we update the creation date as the log of each change is tracked into product_fournisseur_log.
557 $sql .= " ref_fourn = '".$this->db->escape($ref_fourn)."',";
558 $sql .= " desc_fourn = '".$this->db->escape($desc_fourn)."',";
559 $sql .= " price = ".((float) $buyprice).",";
560 $sql .= " quantity = ".((float) $qty).",";
561 $sql .= " remise_percent = ".((float) $remise_percent).",";
562 $sql .= " remise = ".((float) $remise).",";
563 $sql .= " unitprice = ".((float) $unitBuyPrice).",";
564 $sql .= " fk_availability = ".((int) $availability).",";
565 $sql .= " multicurrency_price = ".(isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
566 $sql .= " multicurrency_unitprice = ".(isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
567 $sql .= " multicurrency_tx = ".(isset($multicurrency_tx) ? "'".$this->db->escape((string) $multicurrency_tx)."'" : '1').",";
568 $sql .= " fk_multicurrency = ".(isset($fk_multicurrency) ? (int) $fk_multicurrency : 'null').",";
569 $sql .= " multicurrency_code = ".(isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
570 $sql .= " entity = ".((int) $conf->entity).",";
571 $sql .= " tva_tx = ".((float) price2num($tva_tx)).",";
572 // TODO Add localtax1 and localtax2
573 //$sql.= " localtax1_tx=".($localtax1>=0?$localtax1:'NULL').",";
574 //$sql.= " localtax2_tx=".($localtax2>=0?$localtax2:'NULL').",";
575 //$sql.= " localtax1_type=".($localtaxtype1!=''?"'".$this->db->escape($localtaxtype1)."'":"'0'").",";
576 //$sql.= " localtax2_type=".($localtaxtype2!=''?"'".$this->db->escape($localtaxtype2)."'":"'0'").",";
577 $sql .= " default_vat_code = ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
578 $sql .= " info_bits = ".((int) $newnpr).",";
579 $sql .= " charges = ".((float) $charges).","; // deprecated
580 $sql .= " delivery_time_days = ".($delivery_time_days != '' ? ((int) $delivery_time_days) : 'null').",";
581 $sql .= " supplier_reputation = ".(empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
582 $sql .= " barcode = ".(empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
583 $sql .= " fk_barcode_type = ".(empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape((string) $fk_barcode_type)."'");
584 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
585 $sql .= ", packaging = ".(empty($packaging) ? 1 : ((float) $packaging));
586 }
587 $sql .= " WHERE rowid = ".((int) $this->product_fourn_price_id);
588
589 if (!$error) {
590 if (!empty($options) && is_array($options)) {
591 $productfournisseurprice = new ProductFournisseurPrice($this->db);
592 $res = $productfournisseurprice->fetch($this->product_fourn_price_id);
593 if ($res > 0) {
594 foreach ($options as $key => $value) {
595 $productfournisseurprice->array_options[$key] = $value;
596 }
597 $res = $productfournisseurprice->update($user);
598 if ($res < 0) {
599 $this->setErrorsFromObject($productfournisseurprice);
600 $error++;
601 }
602 }
603 }
604 }
605
606 // TODO Add price_base_type and price_ttc
607
608 dol_syslog(get_class($this).'::update_buyprice update knowing id of line = product_fourn_price_id = '.$this->product_fourn_price_id, LOG_DEBUG);
609 $resql = $this->db->query($sql);
610 if ($resql) {
611 // Call trigger
612 $result = $this->call_trigger('PRODUCT_BUYPRICE_MODIFY', $user);
613 if ($result < 0) {
614 $error++;
615 }
616 // End call triggers
617 if (!$error && !getDolGlobalString('PRODUCT_PRICE_SUPPLIER_NO_LOG')) {
618 $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, (float) $multicurrency_unitBuyPrice, $multicurrency_tx, (int) $fk_multicurrency, $multicurrency_code);
619 if ($result < 0) {
620 $error++;
621 }
622 }
623 if (empty($error)) {
624 $this->db->commit();
625 return $this->product_fourn_price_id;
626 } else {
627 $this->db->rollback();
628 return -1;
629 }
630 } else {
631 $this->error = $this->db->error()." sql=".$sql;
632 $this->db->rollback();
633 return -2;
634 }
635 } else {
636 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);
637
638 // Delete price for this quantity
639 $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_fournisseur_price";
640 $sql .= " WHERE fk_soc = ".((int) $fourn->id)." AND ref_fourn = '".$this->db->escape($ref_fourn)."' AND quantity = ".((float) $qty)." AND entity = ".((int) $conf->entity);
641 $resql = $this->db->query($sql);
642 if ($resql) {
643 // Add price for this quantity to supplier
644 $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price(";
645 $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
646 $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";
647 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
648 $sql .= ", packaging";
649 }
650 $sql .= ") values(";
651 $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
652 $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
653 $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape((string) $multicurrency_tx)."'" : '1').",";
654 $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape((string) $fk_multicurrency)."'" : 'null').",";
655 $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
656 $sql .= " '".$this->db->idate($now)."',";
657 $sql .= " ".((int) $this->id).",";
658 $sql .= " ".((int) $fourn->id).",";
659 $sql .= " '".$this->db->escape($ref_fourn)."',";
660 $sql .= " '".$this->db->escape($desc_fourn)."',";
661 $sql .= " ".((int) $user->id).",";
662 $sql .= " ".price2num($buyprice).",";
663 $sql .= " ".((float) $qty).",";
664 $sql .= " ".((float) $remise_percent).",";
665 $sql .= " ".((float) $remise).",";
666 $sql .= " ".price2num($unitBuyPrice).",";
667 $sql .= " ".price2num($tva_tx).",";
668 $sql .= " ".price2num($charges).",";
669 $sql .= " ".((int) $availability).",";
670 $sql .= " ".($newdefaultvatcode ? "'".$this->db->escape($newdefaultvatcode)."'" : "null").",";
671 $sql .= " ".((int) $newnpr).",";
672 $sql .= ((int) $conf->entity).",";
673 $sql .= ($delivery_time_days != '' ? ((int) $delivery_time_days) : 'null').",";
674 $sql .= (empty($supplier_reputation) ? 'NULL' : "'".$this->db->escape($supplier_reputation)."'").",";
675 $sql .= (empty($barcode) ? 'NULL' : "'".$this->db->escape($barcode)."'").",";
676 $sql .= (empty($fk_barcode_type) ? 'NULL' : "'".$this->db->escape((string) $fk_barcode_type)."'");
677 if (getDolGlobalString('PRODUCT_USE_SUPPLIER_PACKAGING')) {
678 $sql .= ", ".(empty($this->packaging) ? '1' : "'".$this->db->escape((string) $this->packaging)."'");
679 }
680 $sql .= ")";
681
682 $this->product_fourn_price_id = 0;
683
684 $resql = $this->db->query($sql);
685 if ($resql) {
686 $this->product_fourn_price_id = $this->db->last_insert_id(MAIN_DB_PREFIX."product_fournisseur_price");
687 } else {
688 $this->error = $this->db->lasterror();
689 $error++;
690 }
691
692 if (!$error) {
693 if (!empty($options) && is_array($options)) {
694 $productfournisseurprice = new ProductFournisseurPrice($this->db);
695 $res = $productfournisseurprice->fetch($this->product_fourn_price_id);
696 if ($res > 0) {
697 foreach ($options as $key => $value) {
698 $productfournisseurprice->array_options[$key] = $value;
699 }
700 $res = $productfournisseurprice->update($user);
701 if ($res < 0) {
702 $this->error = $productfournisseurprice->error;
703 $this->errors = $productfournisseurprice->errors;
704 $error++;
705 }
706 }
707 }
708 }
709
710 if (!$error && !getDolGlobalString('PRODUCT_PRICE_SUPPLIER_NO_LOG')) {
711 // Add record into log table
712 // $this->product_fourn_price_id must be set
713 $result = $this->logPrice($user, $now, $buyprice, $qty, $multicurrency_buyprice, (float) $multicurrency_unitBuyPrice, $multicurrency_tx, (int) $fk_multicurrency, $multicurrency_code);
714 if ($result < 0) {
715 $error++;
716 }
717 }
718
719 if (!$error) {
720 // Call trigger
721 $result = $this->call_trigger('PRODUCT_BUYPRICE_CREATE', $user);
722 if ($result < 0) {
723 $error++;
724 }
725 // End call triggers
726
727 if (empty($error)) {
728 $this->db->commit();
729 return $this->product_fourn_price_id;
730 } else {
731 $this->db->rollback();
732 return -1;
733 }
734 } else {
735 $this->error = $this->db->lasterror()." sql=".$sql;
736 $this->db->rollback();
737 return -2;
738 }
739 } else {
740 $this->error = $this->db->lasterror()." sql=".$sql;
741 $this->db->rollback();
742 return -1;
743 }
744 }
745 }
746
747 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
755 public function fetch_product_fournisseur_price($rowid, $ignore_expression = 0)
756 {
757 // phpcs:enable
758 $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,";
759 $sql .= " pfp.fk_soc, pfp.ref_fourn, pfp.desc_fourn, pfp.fk_product, pfp.charges, pfp.fk_supplier_price_expression, pfp.delivery_time_days,";
760 $sql .= " pfp.supplier_reputation, pfp.fk_user, pfp.datec,";
761 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code,";
762 $sql .= " pfp.barcode, pfp.fk_barcode_type, pfp.packaging,";
763 $sql .= " p.ref as product_ref, p.tosell as status, p.tobuy as status_buy";
764 $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."product as p";
765 $sql .= " WHERE pfp.rowid = ".(int) $rowid;
766 $sql .= " AND pfp.fk_product = p.rowid";
767
768 dol_syslog(get_class($this)."::fetch_product_fournisseur_price", LOG_DEBUG);
769 $resql = $this->db->query($sql);
770 if ($resql) {
771 $obj = $this->db->fetch_object($resql);
772 if ($obj) {
773 $this->product_fourn_price_id = $rowid;
774 $this->id = $obj->fk_product;
775
776 $this->fk_product = $obj->fk_product;
777 $this->product_id = $obj->fk_product;
778 $this->product_ref = $obj->product_ref;
779 $this->status = $obj->status;
780 $this->status_buy = $obj->status_buy;
781 $this->fourn_id = $obj->fk_soc;
782 $this->fourn_ref = $obj->ref_fourn; // deprecated
783 $this->ref_supplier = $obj->ref_fourn;
784 $this->desc_supplier = $obj->desc_fourn;
785 $this->fourn_price = $obj->price;
786 $this->fourn_charges = $obj->charges; // when getDolGlobalString('PRODUCT_CHARGES') is set
787 $this->fourn_qty = $obj->quantity;
788 $this->fourn_remise_percent = $obj->remise_percent;
789 $this->fourn_remise = $obj->remise;
790 $this->fourn_unitprice = $obj->unitprice;
791 $this->fourn_tva_tx = $obj->tva_tx;
792 $this->fourn_tva_npr = $obj->fourn_tva_npr;
793 // Add also localtaxes
794 $this->fk_availability = $obj->fk_availability;
795 $this->delivery_time_days = $obj->delivery_time_days;
796 $this->fk_supplier_price_expression = $obj->fk_supplier_price_expression;
797 $this->supplier_reputation = $obj->supplier_reputation;
798 $this->default_vat_code = $obj->default_vat_code;
799 $this->user_id = $obj->fk_user;
800 $this->date_creation = $this->db->jdate($obj->datec);
801 $this->fourn_multicurrency_price = $obj->multicurrency_price;
802 $this->fourn_multicurrency_unitprice = $obj->multicurrency_unitprice;
803 $this->fourn_multicurrency_tx = $obj->multicurrency_tx;
804 $this->fourn_multicurrency_id = $obj->fk_multicurrency;
805 $this->fourn_multicurrency_code = $obj->multicurrency_code;
806 if (isModEnabled('barcode')) {
807 $this->fourn_barcode = $obj->barcode; // deprecated
808 $this->fourn_fk_barcode_type = $obj->fk_barcode_type; // deprecated
809 $this->supplier_barcode = $obj->barcode;
810 $this->supplier_fk_barcode_type = $obj->fk_barcode_type;
811 }
812 $this->packaging = (float) $obj->packaging;
813
814 if (isModEnabled('dynamicprices') && empty($ignore_expression) && !empty($this->fk_supplier_price_expression)) {
815 require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
816 $priceparser = new PriceParser($this->db);
817 $price_result = $priceparser->parseProductSupplier($this);
818 if ($price_result >= 0) {
819 $this->fourn_price = $price_result;
820 //recalculation of unitprice, as probably the price changed...
821 if ($this->fourn_qty != 0) {
822 $this->fourn_unitprice = price2num($this->fourn_price / $this->fourn_qty, 'MU');
823 } else {
824 $this->fourn_unitprice = "";
825 }
826 }
827 }
828
829 return 1;
830 } else {
831 return 0;
832 }
833 } else {
834 $this->error = $this->db->lasterror();
835 return -1;
836 }
837 }
838
839
840 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
853 public function list_product_fournisseur_price($prodid, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0, $socid = 0)
854 {
855 // phpcs:enable
856 $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, p.tobatch as status_batch, p.fk_unit as product_fk_unit,";
857 $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,";
858 $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,";
859 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code, pfp.datec, pfp.tms,";
860 $sql .= " pfp.barcode, pfp.fk_barcode_type, pfp.packaging, pfp.status as pfstatus";
861 $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price as pfp, ".MAIN_DB_PREFIX."product as p, ".MAIN_DB_PREFIX."societe as s";
862 $sql .= " WHERE pfp.entity IN (".getEntity('productsupplierprice').")";
863 $sql .= " AND pfp.fk_soc = s.rowid AND pfp.fk_product = p.rowid";
864 $sql .= ($socid > 0 ? ' AND pfp.fk_soc = '.((int) $socid) : '');
865 $sql .= " AND s.status = 1"; // only enabled company selected
866 $sql .= " AND pfp.fk_product = ".((int) $prodid);
867 if (empty($sortfield)) {
868 $sql .= " ORDER BY s.nom, pfp.quantity, pfp.price";
869 } else {
870 $sql .= $this->db->order($sortfield, $sortorder);
871 }
872 $sql .= $this->db->plimit($limit, $offset);
873 dol_syslog(get_class($this)."::list_product_fournisseur_price", LOG_DEBUG);
874
875 $resql = $this->db->query($sql);
876 if ($resql) {
877 $retarray = array();
878
879 while ($record = $this->db->fetch_array($resql)) {
880 //define base attribute
881 $prodfourn = new ProductFournisseur($this->db);
882
883 $prodfourn->product_ref = $record["product_ref"];
884 $prodfourn->product_fourn_price_id = $record["product_fourn_pri_id"];
885 $prodfourn->status = $record["status"];
886 $prodfourn->status_buy = $record["status_buy"];
887 $prodfourn->status_batch = $record["status_batch"];
888 $prodfourn->product_fourn_id = $record["product_fourn_id"];
889 $prodfourn->product_fourn_entity = $record["entity"];
890 $prodfourn->ref_supplier = $record["ref_fourn"];
891 $prodfourn->fourn_ref = $record["ref_fourn"];
892 $prodfourn->desc_supplier = $record["desc_fourn"];
893 $prodfourn->fourn_price = $record["price"];
894 $prodfourn->fourn_qty = $record["quantity"];
895 $prodfourn->fourn_remise_percent = $record["remise_percent"];
896 $prodfourn->fourn_remise = $record["remise"];
897 $prodfourn->fourn_unitprice = $record["unitprice"];
898 $prodfourn->fourn_charges = $record["charges"]; // when getDolGlobalString('PRODUCT_CHARGES') is set
899 $prodfourn->fourn_tva_tx = $record["tva_tx"];
900 $prodfourn->fourn_id = $record["fourn_id"];
901 $prodfourn->fourn_name = $record["supplier_name"];
902 $prodfourn->fk_availability = $record["fk_availability"];
903 $prodfourn->delivery_time_days = $record["delivery_time_days"];
904 $prodfourn->id = $prodid;
905 $prodfourn->fourn_tva_npr = $record["info_bits"];
906 $prodfourn->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
907 $prodfourn->supplier_reputation = $record["supplier_reputation"];
908 $prodfourn->fourn_date_creation = $this->db->jdate($record['datec']);
909 $prodfourn->fourn_date_modification = $this->db->jdate($record['tms']);
910 // Carry the product's default measuring unit so the AJAX caller
911 // (getSupplierPrices.php) can return it to the line form, which
912 // then preselects #units like the customer side already does for
913 // idprod (see issues #34610 client-side and #38636 supplier-side).
914 $prodfourn->fk_unit = $record["product_fk_unit"];
915
916 $prodfourn->fourn_multicurrency_price = $record["multicurrency_price"];
917 $prodfourn->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
918 $prodfourn->fourn_multicurrency_tx = $record["multicurrency_tx"];
919 $prodfourn->fourn_multicurrency_id = $record["fk_multicurrency"];
920 $prodfourn->fourn_multicurrency_code = $record["multicurrency_code"];
921
922 $prodfourn->packaging = (float) $record["packaging"];
923 $prodfourn->status = $record["pfstatus"];
924
925 if (isModEnabled('barcode')) {
926 $prodfourn->supplier_barcode = $record["barcode"];
927 $prodfourn->supplier_fk_barcode_type = $record["fk_barcode_type"];
928 }
929
930 if (isModEnabled('dynamicprices') && !empty($prodfourn->fk_supplier_price_expression)) {
931 require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
932 $priceparser = new PriceParser($this->db);
933 $price_result = $priceparser->parseProductSupplier($prodfourn);
934 if ($price_result >= 0) {
935 $prodfourn->fourn_price = $price_result;
936 // Set to null on purpose an will have non-null value before method return @phan-suppress-next-line PhanTypeMismatchPropertyProbablyReal
937 $prodfourn->fourn_unitprice = null; //force recalculation of unitprice, as probably the price changed... @phpstan-ignore-line
938 }
939 }
940
941 if (!isset($prodfourn->fourn_unitprice)) {
942 if ($prodfourn->fourn_qty != 0) {
943 $prodfourn->fourn_unitprice = price2num($prodfourn->fourn_price / $prodfourn->fourn_qty, 'MU');
944 } else {
945 $prodfourn->fourn_unitprice = "";
946 }
947 }
948
949 $retarray[] = $prodfourn;
950 }
951
952 $this->db->free($resql);
953 return $retarray;
954 } else {
955 $this->error = $this->db->error();
956 return -1;
957 }
958 }
959
960 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
970 public function find_min_price_product_fournisseur($prodid, $qty = 0, $socid = 0)
971 {
972 // phpcs:enable
973 if (empty($prodid)) {
974 dol_syslog("Warning function find_min_price_product_fournisseur were called with prodid empty. May be a bug.", LOG_WARNING);
975 return 0;
976 }
977
978 $this->product_fourn_price_id = 0;
979 $this->product_fourn_id = 0;
980 $this->fourn_ref = '';
981 $this->fourn_price = 0;
982 $this->fourn_qty = 0;
983 $this->fourn_remise_percent = 0;
984 $this->fourn_remise = 0;
985 $this->fourn_unitprice = 0;
986 $this->fourn_id = 0;
987 $this->fourn_name = '';
988 $this->delivery_time_days = 0;
989 $this->id = 0;
990
991 $this->fourn_multicurrency_price = 0;
992 $this->fourn_multicurrency_unitprice = 0;
993 $this->fourn_multicurrency_tx = 0;
994 $this->fourn_multicurrency_id = 0;
995 $this->fourn_multicurrency_code = '';
996
997 $sql = "SELECT s.nom as supplier_name, s.rowid as fourn_id,";
998 $sql .= " pfp.rowid as product_fourn_price_id, pfp.ref_fourn,";
999 $sql .= " pfp.price, pfp.quantity, pfp.unitprice, pfp.tva_tx, pfp.charges,";
1000 $sql .= " pfp.remise, pfp.remise_percent, pfp.fk_supplier_price_expression, pfp.delivery_time_days,";
1001 $sql .= " pfp.multicurrency_price, pfp.multicurrency_unitprice, pfp.multicurrency_tx, pfp.fk_multicurrency, pfp.multicurrency_code";
1002 $sql .= " FROM ".MAIN_DB_PREFIX."societe as s, ".MAIN_DB_PREFIX."product_fournisseur_price as pfp";
1003 $sql .= " WHERE s.entity IN (".getEntity('societe').")";
1004 $sql .= " AND pfp.entity IN (".getEntity('productsupplierprice').")";
1005 $sql .= " AND pfp.fk_product = ".((int) $prodid);
1006 $sql .= " AND pfp.fk_soc = s.rowid";
1007 $sql .= " AND s.status = 1"; // only enabled society
1008 if ($qty > 0) {
1009 $sql .= " AND pfp.quantity <= ".((float) $qty);
1010 }
1011 if ($socid > 0) {
1012 $sql .= ' AND pfp.fk_soc = '.((int) $socid);
1013 }
1014
1015 dol_syslog(get_class($this)."::find_min_price_product_fournisseur", LOG_DEBUG);
1016
1017 $resql = $this->db->query($sql);
1018 if ($resql) {
1019 $record_array = array();
1020
1021 //Store each record to array for later search of min
1022 while ($record = $this->db->fetch_array($resql)) {
1023 $record_array[] = $record;
1024 }
1025
1026 if (count($record_array) == 0) {
1027 $this->db->free($resql);
1028 return 0;
1029 } else {
1030 $min = -1;
1031 foreach ($record_array as $record) {
1032 $fourn_price = $record["price"];
1033 // calculate unit price for quantity 1
1034 $fourn_unitprice = $record["unitprice"];
1035 $fourn_unitprice_with_discount = $record["unitprice"] * (1 - $record["remise_percent"] / 100);
1036
1037 if (isModEnabled('dynamicprices') && !empty($record["fk_supplier_price_expression"])) {
1038 $prod_supplier = new ProductFournisseur($this->db);
1039 $prod_supplier->product_fourn_price_id = $record["product_fourn_price_id"];
1040 $prod_supplier->id = $prodid;
1041 $prod_supplier->fourn_qty = $record["quantity"];
1042 $prod_supplier->fourn_tva_tx = $record["tva_tx"];
1043 $prod_supplier->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
1044
1045 require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_parser.class.php';
1046 $priceparser = new PriceParser($this->db);
1047 $price_result = $priceparser->parseProductSupplier($prod_supplier);
1048 if ($price_result >= 0) {
1049 $fourn_price = price2num($price_result, 'MU');
1050 if ($record["quantity"] != 0) {
1051 $fourn_unitprice = price2num((float) $fourn_price / $record["quantity"], 'MU');
1052 } else {
1053 $fourn_unitprice = $fourn_price;
1054 }
1055 $fourn_unitprice_with_discount = (float) $fourn_unitprice * (1 - $record["remise_percent"] / 100);
1056 }
1057 }
1058
1059 if ($fourn_unitprice_with_discount < $min || $min == -1) {
1060 $this->id = $prodid;
1061 $this->product_fourn_price_id = $record["product_fourn_price_id"];
1062 $this->ref_supplier = $record["ref_fourn"];
1063 $this->ref_fourn = $record["ref_fourn"]; // deprecated
1064 $this->fourn_ref = $record["ref_fourn"]; // deprecated
1065 $this->fourn_price = $fourn_price;
1066 $this->fourn_qty = $record["quantity"];
1067 $this->fourn_remise_percent = $record["remise_percent"];
1068 $this->fourn_remise = $record["remise"];
1069 $this->fourn_unitprice = $fourn_unitprice;
1070 $this->fourn_unitprice_with_discount = $fourn_unitprice_with_discount;
1071 $this->fourn_charges = $record["charges"]; // when getDolGlobalString('PRODUCT_CHARGES') is set
1072 $this->fourn_tva_tx = $record["tva_tx"];
1073 $this->fourn_id = $record["fourn_id"]; // thirdparty id
1074 $this->fourn_name = $record["supplier_name"];
1075 $this->delivery_time_days = $record["delivery_time_days"];
1076 // False positive @phan-suppress-next-line PhanTypeMismatchProperty
1077 $this->fk_supplier_price_expression = $record["fk_supplier_price_expression"];
1078 $this->fourn_multicurrency_price = $record["multicurrency_price"];
1079 $this->fourn_multicurrency_unitprice = $record["multicurrency_unitprice"];
1080 $this->fourn_multicurrency_tx = $record["multicurrency_tx"];
1081 $this->fourn_multicurrency_id = $record["fk_multicurrency"];
1082 $this->fourn_multicurrency_code = $record["multicurrency_code"];
1083
1084 $min = $fourn_unitprice_with_discount;
1085 }
1086 }
1087 }
1088
1089 $this->db->free($resql);
1090
1091 return $this->product_fourn_price_id;
1092 } else {
1093 $this->error = $this->db->error();
1094 return -1;
1095 }
1096 }
1097
1104 public function setSupplierPriceExpression($expression_id)
1105 {
1106 // Clean parameters
1107 $this->db->begin();
1108 $expression_id = $expression_id != 0 ? $expression_id : 'NULL';
1109
1110 $sql = "UPDATE ".MAIN_DB_PREFIX."product_fournisseur_price";
1111 $sql .= " SET fk_supplier_price_expression = ".((int) $expression_id);
1112 $sql .= " WHERE rowid = ".((int) $this->product_fourn_price_id);
1113
1114 dol_syslog(get_class($this)."::setSupplierPriceExpression", LOG_DEBUG);
1115
1116 $resql = $this->db->query($sql);
1117 if ($resql) {
1118 $this->db->commit();
1119 return 1;
1120 } else {
1121 $this->error = $this->db->error()." sql=".$sql;
1122 $this->db->rollback();
1123 return -1;
1124 }
1125 }
1126
1137 public function getSocNomUrl($withpicto = 0, $option = 'supplier', $maxlen = 0, $notooltip = 0)
1138 {
1139 $thirdparty = new Fournisseur($this->db);
1140 $thirdparty->fetch($this->fourn_id);
1141
1142 return $thirdparty->getNomUrl($withpicto, $option, $maxlen, $notooltip);
1143 }
1144
1145 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1157 public function display_price_product_fournisseur($showunitprice = 1, $showsuptitle = 1, $maxlen = 0, $notooltip = 0, $productFournList = array())
1158 {
1159 // phpcs:enable
1160 global $conf, $langs, $user;
1161
1162 $out = '';
1163 $langs->load("suppliers");
1164 if (count($productFournList) > 0) {
1165 $out .= '<table class="centpercent liste nomarginbottom">';
1166 $out .= '<tr class="liste_titre"><td class="liste_titre right">'.($showunitprice ? $langs->trans("Price").' '.$langs->trans("HT") : '').'</td>';
1167 $out .= '<td class="liste_titre right">'.($showunitprice ? $langs->trans("QtyMin") : '').'</td>';
1168 $out .= '<td class="liste_titre">'.$langs->trans("Supplier").'</td>';
1169 $out .= '<td class="liste_titre">'.$langs->trans("SupplierRef").'</td></tr>';
1170 foreach ($productFournList as $productFourn) {
1171 $out .= '<tr><td class="right">'.($showunitprice ? price($productFourn->fourn_unitprice * (1 - $productFourn->fourn_remise_percent / 100) - $productFourn->fourn_remise) : '').'</td>';
1172 $out .= '<td class="right">'.($showunitprice ? $productFourn->fourn_qty : '').'</td>';
1173 $out .= '<td>'.$productFourn->getSocNomUrl(1, 'supplier', $maxlen, $notooltip).'</td>';
1174 $out .= '<td>'.dolPrintHTML($productFourn->fourn_ref).'</td></tr>';
1175 }
1176 $out .= '</table>';
1177 } else {
1178 $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") : '');
1179 if ($user->hasRight("fournisseur", "read")) { // Without permission, never show the best supplier seller
1180 $out .= ($showunitprice ? ' &nbsp; <span class="opacitymedium">(</span>' : '');
1181 $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;
1182 $out .= ($showunitprice ? '<span class="opacitymedium">)</span>' : '');
1183 }
1184 }
1185 return $out;
1186 }
1187
1196 public static function replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
1197 {
1198 // llx_product_fournisseur_price has a UNIQUE INDEX uk_product_fournisseur_price_ref
1199 // on (ref_fourn, fk_soc, quantity, entity). A blind UPDATE fk_soc = dest on every
1200 // origin row fails on rows where dest already has the same (ref_fourn, quantity, entity),
1201 // blocking the whole merge with a 1062 Duplicate entry error (see #38456).
1202 // Drop the colliding origin rows first - they would become exact duplicates of dest
1203 // rows so the merge has nothing to lose by keeping the dest version.
1204 $sqlselect = "SELECT pfp_origin.rowid";
1205 $sqlselect .= " FROM ".$dbs->prefix()."product_fournisseur_price AS pfp_origin";
1206 $sqlselect .= " INNER JOIN ".$dbs->prefix()."product_fournisseur_price AS pfp_dest";
1207 $sqlselect .= " ON pfp_dest.fk_soc = ".((int) $dest_id);
1208 $sqlselect .= " AND pfp_dest.ref_fourn = pfp_origin.ref_fourn";
1209 $sqlselect .= " AND pfp_dest.quantity = pfp_origin.quantity";
1210 $sqlselect .= " AND pfp_dest.entity = pfp_origin.entity";
1211 $sqlselect .= " WHERE pfp_origin.fk_soc = ".((int) $origin_id);
1212
1213 $resql = $dbs->query($sqlselect);
1214 if (!$resql) {
1215 return false;
1216 }
1217 $colliding = array();
1218 while ($obj = $dbs->fetch_object($resql)) {
1219 $colliding[] = (int) $obj->rowid;
1220 }
1221 $dbs->free($resql);
1222
1223 foreach ($colliding as $rowid) {
1224 $sqldel = "DELETE FROM ".$dbs->prefix()."product_fournisseur_price";
1225 $sqldel .= " WHERE rowid = ".((int) $rowid);
1226 if (!$dbs->query($sqldel)) {
1227 return false;
1228 }
1229 }
1230
1231 $tables = array(
1232 'product_fournisseur_price'
1233 );
1234
1235 return CommonObject::commonReplaceThirdparty($dbs, $origin_id, $dest_id, $tables);
1236 }
1237
1246 public static function replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
1247 {
1248 $tables = array(
1249 'product_fournisseur_price'
1250 );
1251
1252 return CommonObject::commonReplaceProduct($dbs, $origin_id, $dest_id, $tables);
1253 }
1254
1265 public function listProductFournisseurPriceLog($product_fourn_price_id, $sortfield = '', $sortorder = '', $limit = 0, $offset = 0)
1266 {
1267 $sql = "SELECT";
1268 $sql .= " u.lastname,";
1269 $sql .= " pfpl.rowid, pfp.ref_fourn as supplier_ref, pfpl.datec,";
1270 $sql .= " pfpl.price, pfpl.quantity,";
1271 $sql .= " pfpl.fk_multicurrency, pfpl.multicurrency_code, pfpl.multicurrency_tx, pfpl.multicurrency_price, pfpl.multicurrency_unitprice";
1272 $sql .= " FROM ".MAIN_DB_PREFIX."product_fournisseur_price_log as pfpl,";
1273 $sql .= " ".MAIN_DB_PREFIX."product_fournisseur_price as pfp,";
1274 $sql .= " ".MAIN_DB_PREFIX."user as u";
1275 $sql .= " WHERE pfp.entity IN (".getEntity('productprice').")";
1276 $sql .= " AND pfpl.fk_user = u.rowid";
1277 $sql .= " AND pfp.rowid = pfpl.fk_product_fournisseur";
1278 $sql .= " AND pfpl.fk_product_fournisseur = ".((int) $product_fourn_price_id);
1279 if (empty($sortfield)) {
1280 $sql .= " ORDER BY pfpl.datec";
1281 } else {
1282 $sql .= $this->db->order($sortfield, $sortorder);
1283 }
1284 $sql .= $this->db->plimit($limit, $offset);
1285 dol_syslog(get_class($this)."::list_product_fournisseur_price_log", LOG_DEBUG);
1286
1287 $resql = $this->db->query($sql);
1288 if ($resql) {
1289 $retarray = array();
1290
1291 while ($obj = $this->db->fetch_object($resql)) {
1292 $tmparray = array();
1293 $tmparray['rowid'] = $obj->rowid;
1294 $tmparray['supplier_ref'] = $obj->supplier_ref;
1295 $tmparray['datec'] = $this->db->jdate($obj->datec);
1296 $tmparray['lastname'] = $obj->lastname;
1297 $tmparray['price'] = $obj->price;
1298 $tmparray['quantity'] = $obj->quantity;
1299 $tmparray['fk_multicurrency'] = $obj->fk_multicurrency;
1300 $tmparray['multicurrency_code'] = $obj->multicurrency_code;
1301 $tmparray['multicurrency_tx'] = $obj->multicurrency_tx;
1302 $tmparray['multicurrency_price'] = $obj->multicurrency_price;
1303 $tmparray['multicurrency_unitprice'] = $obj->multicurrency_unitprice;
1304
1305 $retarray[] = $tmparray;
1306 }
1307
1308 $this->db->free($resql);
1309 return $retarray;
1310 } else {
1311 $this->error = $this->db->error();
1312 return -1;
1313 }
1314 }
1315
1323 public function displayPriceProductFournisseurLog($productFournLogList = array())
1324 {
1325 global $conf, $langs;
1326
1327 $out = '';
1328 $langs->load("suppliers");
1329 if (count($productFournLogList) > 0) {
1330 $out .= '<table class="noborder centpercent">';
1331 $out .= '<tr class="liste_titre"><td class="liste_titre">'.$langs->trans("Date").'</td>';
1332 $out .= '<td class="liste_titre right">'.$langs->trans("Price").'</td>';
1333 //$out .= '<td class="liste_titre right">'.$langs->trans("QtyMin").'</td>';
1334 $out .= '<td class="liste_titre">'.$langs->trans("User").'</td></tr>';
1335 foreach ($productFournLogList as $productFournLog) {
1336 $out .= '<tr><td>'.dol_print_date($productFournLog['datec'], 'dayhour', 'tzuser').'</td>';
1337 $out .= '<td class="right">'.price($productFournLog['price'], 0, $langs, 1, -1, -1, $conf->currency);
1338 if (isModEnabled('multicurrency') && !empty($productFournLog['multicurrency_code']) && $productFournLog['multicurrency_code'] != $conf->currency) {
1339 $out .= ' ('.price($productFournLog['multicurrency_price'], 0, $langs, 1, -1, -1, $productFournLog['multicurrency_code']).')';
1340 }
1341 $out .= '</td>';
1342 //$out.= '<td class="right">'.$productFournLog['quantity'].'</td>';
1343 $out .= '<td>'.$productFournLog['lastname'].'</td></tr>';
1344 }
1345 $out .= '</table>';
1346 }
1347 return $out;
1348 }
1349
1350
1366 public function getNomUrl($withpicto = 0, $option = '', $maxlength = 0, $save_lastsearch_value = -1, $notooltip = 0, $morecss = '', $add_label = 0, $sep = ' - ', $addlinktonotes = 0)
1367 {
1368 global $conf, $langs, $hookmanager, $user;
1369
1370 if (!empty($conf->dol_no_mouse_hover)) {
1371 $notooltip = 1; // Force disable tooltips
1372 }
1373
1374 $result = '';
1375 $label = '';
1376
1377 $newref = (string) $this->ref;
1378 if ($maxlength) {
1379 $newref = dol_trunc($newref, $maxlength, 'middle');
1380 }
1381
1382 if (!empty($this->entity)) {
1383 $tmpphoto = $this->show_photos('product', $conf->product->multidir_output[$this->entity], 1, 1, 0, 0, 0, 80);
1384 if ($this->nbphoto > 0) {
1385 $label .= '<div class="photointooltip">';
1386 $label .= $tmpphoto;
1387 $label .= '</div><div style="clear: both;"></div>';
1388 }
1389 }
1390
1391 if ($this->type == Product::TYPE_PRODUCT) {
1392 $label .= img_picto('', 'product').' <u class="paddingrightonly">'.$langs->trans("Product").'</u>';
1393 } elseif ($this->type == Product::TYPE_SERVICE) {
1394 $label .= img_picto('', 'service').' <u class="paddingrightonly">'.$langs->trans("Service").'</u>';
1395 }
1396 if (isset($this->status) && isset($this->status_buy)) {
1397 $label .= ' '.$this->getLibStatut(5, 0);
1398 $label .= ' '.$this->getLibStatut(5, 1);
1399 }
1400
1401 if (!empty($this->ref)) {
1402 $label .= '<br><b>'.$langs->trans('ProductRef').':</b> '.($this->ref ? $this->ref : $this->product_ref);
1403 }
1404 if (!empty($this->label)) {
1405 $label .= '<br><b>'.$langs->trans('ProductLabel').':</b> '.$this->label;
1406 }
1407 $label .= '<br><b>'.$langs->trans('RefSupplier').':</b> '.$this->ref_supplier;
1408
1409 if ($this->type == Product::TYPE_PRODUCT || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
1410 if (isModEnabled('productbatch')) {
1411 $langs->load("productbatch");
1412 $label .= "<br><b>".$langs->trans("ManageLotSerial").'</b>: '.$this->getLibStatut(0, 2);
1413 }
1414 }
1415 if (isModEnabled('barcode')) {
1416 $label .= '<br><b>'.$langs->trans('BarCode').':</b> '.$this->barcode;
1417 }
1418
1419 if ($this->type == Product::TYPE_PRODUCT) {
1420 if ($this->weight) {
1421 $label .= "<br><b>".$langs->trans("Weight").'</b>: '.$this->weight.' '.measuringUnitString(0, "weight", $this->weight_units);
1422 }
1423 $labelsize = "";
1424 if ($this->length) {
1425 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Length").'</b>: '.$this->length.' '.measuringUnitString(0, 'size', $this->length_units);
1426 }
1427 if ($this->width) {
1428 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Width").'</b>: '.$this->width.' '.measuringUnitString(0, 'size', $this->width_units);
1429 }
1430 if ($this->height) {
1431 $labelsize .= ($labelsize ? " - " : "")."<b>".$langs->trans("Height").'</b>: '.$this->height.' '.measuringUnitString(0, 'size', $this->height_units);
1432 }
1433 if ($labelsize) {
1434 $label .= "<br>".$labelsize;
1435 }
1436
1437 $labelsurfacevolume = "";
1438 if ($this->surface) {
1439 $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Surface").'</b>: '.$this->surface.' '.measuringUnitString(0, 'surface', $this->surface_units);
1440 }
1441 if ($this->volume) {
1442 $labelsurfacevolume .= ($labelsurfacevolume ? " - " : "")."<b>".$langs->trans("Volume").'</b>: '.$this->volume.' '.measuringUnitString(0, 'volume', $this->volume_units);
1443 }
1444 if ($labelsurfacevolume) {
1445 $label .= "<br>".$labelsurfacevolume;
1446 }
1447 }
1448
1449 if (isModEnabled('accounting') && $this->status) {
1450 include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1451 $label .= '<br><b>'.$langs->trans('ProductAccountancySellCode').':</b> '.length_accountg($this->accountancy_code_sell);
1452 $label .= '<br><b>'.$langs->trans('ProductAccountancySellIntraCode').':</b> '.length_accountg($this->accountancy_code_sell_intra);
1453 $label .= '<br><b>'.$langs->trans('ProductAccountancySellExportCode').':</b> '.length_accountg($this->accountancy_code_sell_export);
1454 }
1455 if (isModEnabled('accounting') && $this->status_buy) {
1456 include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1457 $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyCode').':</b> '.length_accountg($this->accountancy_code_buy);
1458 $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyIntraCode').':</b> '.length_accountg($this->accountancy_code_buy_intra);
1459 $label .= '<br><b>'.$langs->trans('ProductAccountancyBuyExportCode').':</b> '.length_accountg($this->accountancy_code_buy_export);
1460 }
1461
1462 $logPrices = $this->listProductFournisseurPriceLog($this->product_fourn_price_id, 'pfpl.datec', 'DESC', getDolGlobalInt('MAIN_TOOLTIP_PRICELOG_HISTORY_LIMIT', 10)); // set sort order here
1463 if (is_array($logPrices) && count($logPrices) > 0) {
1464 $label .= '<br><br>';
1465 $label .= '<u>'.$langs->trans("History").'</u>';
1466 $label .= $this->displayPriceProductFournisseurLog($logPrices);
1467 }
1468
1469 $url = DOL_URL_ROOT.'/product/price_suppliers.php?id='.((int) $this->id).'&action=create_price&token='.newToken().'&socid='.((int) $this->fourn_id).'&rowid='.((int) $this->product_fourn_price_id);
1470
1471 if ($option != 'nolink') {
1472 // Add param to save lastsearch_values or not
1473 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1474 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1475 $add_save_lastsearch_values = 1;
1476 }
1477 if ($add_save_lastsearch_values) {
1478 $url .= '&save_lastsearch_values=1';
1479 }
1480 }
1481
1482 $allowothertags = array('table', 'tr', 'td');
1483 $linkclose = '';
1484 if (empty($notooltip)) {
1485 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1486 $label = $langs->trans("SupplierRef");
1487 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label, 0, $allowothertags).'"';
1488 }
1489 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label, 0, $allowothertags).'"';
1490 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1491 } else {
1492 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1493 }
1494
1495 $linkstart = '<a href="'.$url.'"';
1496 $linkstart .= $linkclose.'>';
1497 $linkend = '</a>';
1498
1499 $result .= $linkstart;
1500 if ($withpicto) {
1501 $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, $allowothertags);
1502 }
1503 if ($withpicto != 2) {
1504 $result .= $newref.($this->ref_supplier ? ' ('.$this->ref_supplier.')' : '');
1505 }
1506 $result .= $linkend;
1507 if ($withpicto != 2) {
1508 $result .= (($add_label && $this->label) ? $sep.dol_trunc($this->label, ($add_label > 1 ? $add_label : 0)) : '');
1509 }
1510
1511 if ($addlinktonotes) {
1512 $txttoshow = ($user->socid > 0 ? $this->note_public : $this->note_private);
1513 if ($txttoshow) {
1514 $notetoshow = $langs->trans("ViewPrivateNote").':<br>'.dol_string_nohtmltag($txttoshow, 1);
1515 $result .= ' <span class="note inline-block">';
1516 $result .= '<a href="'.DOL_URL_ROOT.'/product/note.php?id='.$this->id.'" class="classfortooltip" title="'.dol_escape_htmltag($notetoshow).'">';
1517 $result .= img_picto('', 'note');
1518 $result .= '</a>';
1519 $result .= '</span>';
1520 }
1521 }
1522
1523 global $action;
1524 $hookmanager->initHooks(array($this->element . 'dao'));
1525 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1526 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1527 if ($reshook > 0) {
1528 $result = $hookmanager->resPrint;
1529 } else {
1530 $result .= $hookmanager->resPrint;
1531 }
1532 return $result;
1533 }
1534
1542 /* public function getLibStatut($mode = 0, $type = 0) // must be compatible with getLibStatut of inherited Product
1543 {
1544 return $this->LibStatut($this->status, $mode);
1545 }
1546 */
1547 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1556 /*
1557 public function LibStatut($status, $mode = 0, $type = 0)
1558 {
1559 // phpcs:enable
1560 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1561 global $langs;
1562 //$langs->load("mymodule@mymodule");
1563 $this->labelStatus[self::STATUS_OPEN] = $langs->transnoentitiesnoconv('Enabled');
1564 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
1565 $this->labelStatusShort[self::STATUS_OPEN] = $langs->transnoentitiesnoconv('Enabled');
1566 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
1567 }
1568
1569 $statusType = 'status4';
1570 //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1571 if ($status == self::STATUS_CANCELED) {
1572 $statusType = 'status6';
1573 }
1574
1575 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1576 }
1577 */
1578
1594 private function logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice = null, $multicurrency_unitBuyPrice = null, $multicurrency_tx = null, $fk_multicurrency = null, $multicurrency_code = null)
1595 {
1596 // Add record into log table
1597 $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_fournisseur_price_log(";
1598 $sql .= " multicurrency_price, multicurrency_unitprice, multicurrency_tx, fk_multicurrency, multicurrency_code,";
1599 $sql .= "datec, fk_product_fournisseur,fk_user,price,quantity)";
1600 $sql .= "values(";
1601 $sql .= (isset($multicurrency_buyprice) ? "'".$this->db->escape(price2num($multicurrency_buyprice))."'" : 'null').",";
1602 $sql .= (isset($multicurrency_unitBuyPrice) ? "'".$this->db->escape(price2num($multicurrency_unitBuyPrice))."'" : 'null').",";
1603 $sql .= (isset($multicurrency_tx) ? "'".$this->db->escape((string) $multicurrency_tx)."'" : '1').",";
1604 $sql .= (isset($fk_multicurrency) ? "'".$this->db->escape((string) $fk_multicurrency)."'" : 'null').",";
1605 $sql .= (isset($multicurrency_code) ? "'".$this->db->escape($multicurrency_code)."'" : 'null').",";
1606 $sql .= "'".$this->db->idate($datec)."',";
1607 $sql .= " ".((int) $this->product_fourn_price_id).",";
1608 $sql .= " ".((int) $user->id).",";
1609 $sql .= " ".price2num($buyprice).",";
1610 $sql .= " ".price2num($qty);
1611 $sql .= ")";
1612
1613 $resql = $this->db->query($sql);
1614 if (!$resql) {
1615 return -1;
1616 } else {
1617 return 1;
1618 }
1619 }
1620}
length_accountg($account)
Return General accounting account with defined length (used for product and miscellaneous)
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
setErrorsFromObject($object)
setErrorsFromObject
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
show_photos($modulepart, $sdir, $size=0, $nbmax=0, $nbbyrow=5, $showfilename=0, $showaction=0, $maxHeight=120, $maxWidth=160, $nolink=0, $overwritetitle=0, $usesharelink=0, $cache='', $addphotorefcss='photoref')
Show photos of an object (nbmax maximum), into several columns.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
Class to manage Dolibarr database access.
Class to manage suppliers.
static getIdFromCode($dbs, $code)
Get id of currency from code.
Class to parse product price expressions.
Class to manage predefined suppliers products.
displayPriceProductFournisseurLog($productFournLogList=array())
Display log price of product supplier price.
listProductFournisseurPriceLog($product_fourn_price_id, $sortfield='', $sortorder='', $limit=0, $offset=0)
List supplier prices log of a supplier price.
getSocNomUrl($withpicto=0, $option='supplier', $maxlen=0, $notooltip=0)
Display supplier of product.
getNomUrl($withpicto=0, $option='', $maxlength=0, $save_lastsearch_value=-1, $notooltip=0, $morecss='', $add_label=0, $sep=' - ', $addlinktonotes=0)
Return a link to the object card (with optionally the picto).
logPrice($user, $datec, $buyprice, $qty, $multicurrency_buyprice=null, $multicurrency_unitBuyPrice=null, $multicurrency_tx=null, $fk_multicurrency=null, $multicurrency_code=null)
Return the label of the status.
setSupplierPriceExpression($expression_id)
Sets the supplier price expression.
find_min_price_product_fournisseur($prodid, $qty=0, $socid=0)
Load properties for minimum price.
list_product_fournisseur_price($prodid, $sortfield='', $sortorder='', $limit=0, $offset=0, $socid=0)
List all supplier prices of a product.
fetch_product_fournisseur_price($rowid, $ignore_expression=0)
Loads the price information of a provider.
remove_fournisseur($id_fourn)
Remove all prices for this couple supplier-product.
remove_product_fournisseur_price($rowid)
Remove a price for a couple supplier-product.
static replaceThirdparty(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
static replaceProduct(DoliDB $dbs, $origin_id, $dest_id)
Function used to replace a product id with another one.
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=0, $options=array())
Modify the purchase price for a supplier.
display_price_product_fournisseur($showunitprice=1, $showsuptitle=1, $maxlen=0, $notooltip=0, $productFournList=array())
Display price of product.
Class for ProductFournisseurPrice.
Class to manage products or services.
const TYPE_PRODUCT
Regular product.
getLibStatut($mode=0, $type=0)
Return label of status of object.
const TYPE_SERVICE
Service.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_localtax($vatrate, $local, $thirdparty_buyer=null, $thirdparty_seller=null, $vatnpr=0)
Return localtax rate for a particular VAT rate, when selling a product with vat $vatrate,...
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
query($query, $usesavepoint=0, $type='auto', $result_mode=0)
Execute a SQL request and return the resultset.
fetch_object($resultset)
Returns the current line (as an object) for the resultset cursor.
free($resultset=null)
Free last resultset used.
measuringUnitString($unitid, $measuring_style='', $unitscale=null, $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.