From 329bdfc9fd86bc53823bad6e9ec09fdc0a4904b3 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Mon, 11 Jul 2016 11:35:38 +0200
Subject: [PATCH] FIX We must take last recent price when using several level
 of prices

---
 htdocs/core/class/html.form.class.php | 6 +++---
 htdocs/product/ajax/products.php      | 4 ++--
 2 files changed, 5 insertions(+), 5 deletions(-)

diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php
index 1bbeab05d53..3354aa01209 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -1767,7 +1767,7 @@ class Form
 				$optJson = array();
 				$objp = $this->db->fetch_object($result);
 
-				if (!empty($objp->price_by_qty) && $objp->price_by_qty == 1 && !empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY))
+				if (!empty($conf->global->PRODUIT_CUSTOMER_PRICES_BY_QTY) && !empty($objp->price_by_qty) && $objp->price_by_qty == 1)
 				{ // Price by quantity will return many prices for the same product
 					$sql = "SELECT rowid, quantity, price, unitprice, remise_percent, remise";
 					$sql.= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
@@ -1915,8 +1915,8 @@ class Form
             $sql.= " WHERE fk_product='".$objp->rowid."'";
             $sql.= " AND entity IN (".getEntity('productprice', 1).")";
             $sql.= " AND price_level=".$price_level;
-            $sql.= " ORDER BY date_price, rowid";
-            $sql.= " DESC LIMIT 1";
+            $sql.= " ORDER BY date_price DESC, rowid DESC"; // Warning DESC must be both on date_price and rowid.
+            $sql.= " LIMIT 1";
 
             dol_syslog(get_class($this).'::constructProductListOption search price for level '.$price_level.'', LOG_DEBUG);
             $result2 = $this->db->query($sql);
diff --git a/htdocs/product/ajax/products.php b/htdocs/product/ajax/products.php
index 05efcc24a0e..85990fe1bd4 100644
--- a/htdocs/product/ajax/products.php
+++ b/htdocs/product/ajax/products.php
@@ -180,9 +180,9 @@ if (! empty($action) && $action == 'fetch' && ! empty($id))
 	$searchkey = (GETPOST($idprod) ? GETPOST($idprod) : (GETPOST($htmlname) ? GETPOST($htmlname) : ''));
 
 	$form = new Form($db);
-	if (empty($mode) || $mode == 1) {
+	if (empty($mode) || $mode == 1) {  // mode=1: customer
 		$arrayresult = $form->select_produits_list("", $htmlname, $type, "", $price_level, $searchkey, $status, $finished, $outjson, $socid);
-	} elseif ($mode == 2) {
+	} elseif ($mode == 2) {            // mode=2: supplier
 		$arrayresult = $form->select_produits_fournisseurs_list($socid, "", $htmlname, $type, "", $searchkey, $status, $outjson);
 	}
 
-- 
GitLab