diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php
index a5c0a89f29dff645be483be76ed96bc344d27bcd..4ea377a44878e394fb395cedec053977adb2118a 100644
--- a/htdocs/comm/remise.php
+++ b/htdocs/comm/remise.php
@@ -100,8 +100,8 @@ if ($socid > 0)
 
 	$head = societe_prepare_head($object);
 
-	
-	
+
+
 	print '<form method="POST" action="remise.php?id='.$object->id.'">';
 	print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
 	print '<input type="hidden" name="action" value="setremise">';
@@ -110,9 +110,9 @@ if ($socid > 0)
 	dol_fiche_head($head, 'relativediscount', $langs->trans("ThirdParty"),0,'company');
 
     dol_banner_tab($object, 'socid', '', ($user->societe_id?0:1), 'rowid', 'nom');
-        
+
     print '<div class="fichecenter">';
-    
+
     print '<div class="underbanner clearboth"></div>';
 	print '<table class="border centpercent">';
 
@@ -138,9 +138,9 @@ if ($socid > 0)
 	print "</table>";
 
 	print '</div>';
-	
+
 	dol_fiche_end();
-	
+
 	print '<div class="center">';
 	print '<input type="submit" class="button" value="'.$langs->trans("Modify").'">';
     if (! empty($backtopage))
@@ -161,7 +161,8 @@ if ($socid > 0)
 	$sql  = "SELECT rc.rowid, rc.remise_client as remise_percent, rc.note, rc.datec as dc,";
 	$sql.= " u.login, u.rowid as user_id";
 	$sql.= " FROM ".MAIN_DB_PREFIX."societe_remise as rc, ".MAIN_DB_PREFIX."user as u";
-	$sql.= " WHERE rc.fk_soc =". $object->id;
+	$sql.= " WHERE rc.fk_soc = " . $object->id;
+	$sql.= " AND rc.entity = " . $conf->entity;
 	$sql.= " AND u.rowid = rc.fk_user_author";
 	$sql.= " ORDER BY rc.datec DESC";
 
diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php
index e358b842d2dde5f9e1dfbc0c8f42e69a97cd9577..e00e5bbade10b47e3375ab7f2c52f1a233a1d357 100644
--- a/htdocs/comm/remx.php
+++ b/htdocs/comm/remx.php
@@ -239,7 +239,8 @@ if ($socid > 0)
 	$remise_all=$remise_user=0;
 	$sql = "SELECT SUM(rc.amount_ht) as amount, rc.fk_user";
 	$sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
-	$sql.= " WHERE rc.fk_soc =". $object->id;
+	$sql.= " WHERE rc.fk_soc = " . $object->id;
+	$sql.= " AND rc.entity = " . $conf->entity;
 	$sql.= " AND (fk_facture_line IS NULL AND fk_facture IS NULL)";
 	$sql.= " GROUP BY rc.fk_user";
 	$resql=$db->query($sql);
@@ -319,7 +320,8 @@ if ($socid > 0)
 	$sql.= " fa.facnumber as ref, fa.type as type";
 	$sql.= " FROM  ".MAIN_DB_PREFIX."user as u, ".MAIN_DB_PREFIX."societe_remise_except as rc";
 	$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as fa ON rc.fk_facture_source = fa.rowid";
-	$sql.= " WHERE rc.fk_soc =". $object->id;
+	$sql.= " WHERE rc.fk_soc = " . $object->id;
+	$sql.= " AND rc.entity = " . $conf->entity;
 	$sql.= " AND u.rowid = rc.fk_user";
 	$sql.= " AND (rc.fk_facture_line IS NULL AND rc.fk_facture IS NULL)";
 	$sql.= " ORDER BY rc.datec DESC";
diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php
index 3542b8eb1a9deea04733d45a31f63253ad3ebaaa..81d85ece343ac42e41a6e89fa68d31ccf429ed7c 100644
--- a/htdocs/core/class/discount.class.php
+++ b/htdocs/core/class/discount.class.php
@@ -66,6 +66,8 @@ class DiscountAbsolute
      */
     function fetch($rowid,$fk_facture_source=0)
     {
+    	global $conf;
+
         // Check parameters
         if (! $rowid && ! $fk_facture_source)
         {
@@ -81,9 +83,9 @@ class DiscountAbsolute
         $sql.= " f.facnumber as ref_facture_source";
         $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
         $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."facture as f ON sr.fk_facture_source = f.rowid";
-        $sql.= " WHERE";
-        if ($rowid) $sql.= " sr.rowid=".$rowid;
-        if ($fk_facture_source) $sql.= " sr.fk_facture_source=".$fk_facture_source;
+        $sql.= " WHERE sr.entity = " . $conf->entity;
+        if ($rowid) $sql.= " AND sr.rowid=".$rowid;
+        if ($fk_facture_source) $sql.= " AND sr.fk_facture_source=".$fk_facture_source;
 
         dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
         $resql = $this->db->query($sql);
@@ -150,11 +152,11 @@ class DiscountAbsolute
 
         // Insert request
         $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise_except";
-        $sql.= " (datec, fk_soc, fk_user, description,";
+        $sql.= " (entity, datec, fk_soc, fk_user, description,";
         $sql.= " amount_ht, amount_tva, amount_ttc, tva_tx,";
         $sql.= " fk_facture_source";
         $sql.= ")";
-        $sql.= " VALUES ('".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',";
+        $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($this->datec!=''?$this->datec:dol_now())."', ".$this->fk_soc.", ".$user->id.", '".$this->db->escape($this->description)."',";
         $sql.= " ".$this->amount_ht.", ".$this->amount_tva.", ".$this->amount_ttc.", ".$this->tva_tx.",";
         $sql.= " ".($this->fk_facture_source?"'".$this->fk_facture_source."'":"null");
         $sql.= ")";
@@ -343,10 +345,13 @@ class DiscountAbsolute
      */
     function getAvailableDiscounts($company='', $user='',$filter='', $maxvalue=0)
     {
+    	global $conf;
+
         $sql  = "SELECT SUM(rc.amount_ttc) as amount";
         //        $sql  = "SELECT rc.amount_ttc as amount";
         $sql.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as rc";
-        $sql.= " WHERE (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)";	// Available
+        $sql.= " WHERE rc.entity = " . $conf->entity;
+        $sql.= " AND (rc.fk_facture IS NULL AND rc.fk_facture_line IS NULL)";	// Available
         if (is_object($company)) $sql.= " AND rc.fk_soc = ".$company->id;
         if (is_object($user))    $sql.= " AND rc.fk_user = ".$user->id;
         if ($filter)   $sql.=' AND ('.$filter.')';
diff --git a/htdocs/core/class/html.form.class.php b/htdocs/core/class/html.form.class.php
index c4273a779a92c8c34ea829ce854dc160da7fa54c..1fa0a90d64bc3d47fd8689ecc34667f3bf54b701 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -484,7 +484,7 @@ class Form
 
     /**
      * Generate select HTML to choose massaction
-     * 
+     *
      * @param	string	$selected		Selected value
      * @param	int		$arrayofaction	array('code'=>'label', ...)
      * @return	string					Select list
@@ -492,9 +492,9 @@ class Form
     function selectMassAction($selected, $arrayofaction)
     {
     	global $conf,$langs,$hookmanager;
-    	
+
     	if (count($arrayofaction) == 0) return;
-    	
+
     	$disabled=0;
     	$ret='<div class="centpercent center"><select class="flat hideobject massaction massactionselect" name="massaction"'.($disabled?' disabled="disabled"':'').'>';
     	$ret.='<option value="0"'.($disabled?' disabled="disabled"':'').'>-- '.$langs->trans("SelectAction").' --</option>';
@@ -506,7 +506,7 @@ class Form
     	// Warning: if you set submit button to disabled, post using Enter will no more work
     	$ret.='<input type="submit" name="confirmmassaction" class="button hideobject massaction massactionconfirmed" value="'.dol_escape_htmltag($langs->trans("Confirm")).'">';
     	$ret.='</div>';
-    	
+
     	$ret.='<!-- JS CODE TO ENABLE mass action select -->
 		<script type="text/javascript">
     	jQuery(document).ready(function () {
@@ -546,10 +546,10 @@ class Form
     	});
 		</script>
     	';
-    	
+
     	return $ret;
     }
-    
+
     /**
      *  Return combo list of activated countries, into language of user
      *
@@ -1019,9 +1019,9 @@ class Form
             $textifempty='';
             // Do not use textifempty = ' ' or '&nbsp;' here, or search on key will search on ' key'.
             //if (! empty($conf->use_javascript_ajax) || $forcecombo) $textifempty='';
-            if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT)) 
+            if (! empty($conf->global->COMPANY_USE_SEARCH_TO_SELECT))
             {
-                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty); 
+                if ($showempty && ! is_numeric($showempty)) $textifempty=$langs->trans($showempty);
                 else $textifempty.=$langs->trans("All");
             }
             if ($showempty) $out.= '<option value="-1">'.$textifempty.'</option>'."\n";
@@ -1107,7 +1107,8 @@ class Form
         $sql = "SELECT re.rowid, re.amount_ht, re.amount_tva, re.amount_ttc,";
         $sql.= " re.description, re.fk_facture_source";
         $sql.= " FROM ".MAIN_DB_PREFIX ."societe_remise_except as re";
-        $sql.= " WHERE fk_soc = ".(int) $socid;
+        $sql.= " WHERE re.fk_soc = ".(int) $socid;
+        $sql.= " AND re.entity = " . $conf->entity;
         if ($filter) $sql.= " AND ".$filter;
         $sql.= " ORDER BY re.description ASC";
 
@@ -1340,7 +1341,7 @@ class Form
      *  @param	string	$show_every		0=default list, 1=add also a value "Everybody" at beginning of list
      *  @param	string	$enableonlytext	If option $enableonly is set, we use this text to explain into label why record is disabled. Not used if enableonly is empty.
      *  @param	string	$morecss		More css
-     *  @param  int     $noactive       Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on). 
+     *  @param  int     $noactive       Show only active users (this will also happened whatever is this option if USER_HIDE_INACTIVE_IN_COMBOBOX is on).
      * 	@return	string					HTML select string
      *  @see select_dolgroups
      */
@@ -1967,9 +1968,9 @@ class Form
 		}
 
 		// Price by customer
-		if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES)) 
+		if (empty($hidepriceinlabel) && !empty($conf->global->PRODUIT_CUSTOMER_PRICES))
 		{
-			if (!empty($objp->idprodcustprice)) 
+			if (!empty($objp->idprodcustprice))
 			{
 				$found = 1;
 
@@ -2161,11 +2162,11 @@ class Form
                 if ($filterkey && $filterkey != '') $label=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$label,1);
 
                 $opt.=$objp->ref;
-                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) 
+                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
                 	$opt.=' ('.$objp->ref_fourn.')';
                 $opt.=' - ';
                 $outval.=$objRef;
-                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn)) 
+                if (! empty($objp->idprodfournprice) && ($objp->ref != $objp->ref_fourn))
                 	$outval.=' ('.$objRefFourn.')';
                 $outval.=' - ';
                 $opt.=dol_trunc($label, 72).' - ';
@@ -2747,7 +2748,7 @@ class Form
         {
             // If not good status
             if ($active >= 0 && $arraytypes['active'] != $active) continue;
-            
+
             // On passe si on a demande de filtrer sur des modes de paiments particuliers
             if (count($filterarray) && ! in_array($arraytypes['type'],$filterarray)) continue;
 
@@ -3110,7 +3111,7 @@ class Form
         $langs->load("categories");
 
 		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-        
+
         $cat = new Categorie($this->db);
         $cate_arbo = $cat->get_full_arbo($type,$excludeafterid);
 
@@ -4024,7 +4025,7 @@ class Form
             $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
         }
         //var_dump($defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
-        
+
         // Check parameters
         if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
         {
@@ -4122,7 +4123,7 @@ class Form
         		$return.= '"';
         		if ($defaultcode)
         		{
-                    if ($defaultcode == $rate['code']) $return.= ' selected';    	
+                    if ($defaultcode == $rate['code']) $return.= ' selected';
         		}
         		elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
            		{
@@ -4131,7 +4132,7 @@ class Form
         		$return.= '>'.vatrate($rate['libtva']);
         		//$return.=($rate['code']?' '.$rate['code']:'');
         		$return.= $rate['nprtva'] ? ' *': '';
-        		
+
         		$return.= '</option>';
         	}
 
@@ -4435,7 +4436,7 @@ class Form
         {
             $tmparray=dol_getdate($adddateof);
             $retstring.=' - <button class="dpInvisibleButtons datenowlink" id="dateofinvoice" type="button" name="_dateofinvoice" value="now" onclick="jQuery(\'#re\').val(\''.dol_print_date($adddateof,'day').'\');jQuery(\'#reday\').val(\''.$tmparray['mday'].'\');jQuery(\'#remonth\').val(\''.$tmparray['mon'].'\');jQuery(\'#reyear\').val(\''.$tmparray['year'].'\');">'.$langs->trans("DateInvoice").'</a>';
-        }    
+        }
 
         if (! empty($nooutput)) return $retstring;
 
@@ -4638,19 +4639,19 @@ class Form
     static function selectArrayAjax($htmlname, $url, $id='', $moreparam='', $moreparamtourl='', $disabled=0, $minimumInputLength=1, $morecss='', $callurlonselect=0, $placeholder='', $acceptdelayedhtml=0)
     {
         global $langs;
-        global $delayedhtmlcontent;      
-        
+        global $delayedhtmlcontent;
+
     	$tmpplugin='select2';
-        
+
     	$out='<input type="text" class="'.$htmlname.($morecss?' '.$morecss:'').'" '.($moreparam?$moreparam.' ':'').'name="'.$htmlname.'">';
-    	
+
     	// TODO Use an internal dolibarr component instead of select2
     	$outdelayed='<!-- JS CODE TO ENABLE '.$tmpplugin.' for id '.$htmlname.' -->
 	    	<script type="text/javascript">
 	    	$(document).ready(function () {
-    	      
+
     	        '.($callurlonselect ? 'var saveRemoteData = [];':'').'
-    	    
+
                 $(".'.$htmlname.'").select2({
 			    	ajax: {
 				    	dir: "ltr",
@@ -4685,7 +4686,7 @@ class Form
 			    		},*/
 			    		cache: true
 			    	},
-			        dropdownCssClass: "css-'.$htmlname.'", 
+			        dropdownCssClass: "css-'.$htmlname.'",
 				    placeholder: "'.dol_escape_js($placeholder).'",
 			    	escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
 			    	minimumInputLength: '.$minimumInputLength.',
@@ -4693,9 +4694,9 @@ class Form
                         return escapeMarkup(result.text);
                     }
 			    });
-			    
+
                 '.($callurlonselect ? '
-                $(".'.$htmlname.'").change(function() { 
+                $(".'.$htmlname.'").change(function() {
 			    	var selected = $(".'.$htmlname.'").select2("val");
 			        $(".'.$htmlname.'").select2("val","");  /* reset visible combo value */
     			    $.each( saveRemoteData, function( key, value ) {
@@ -4706,7 +4707,7 @@ class Form
     			            }
                     });
     			});' : '' ) . '
-    			
+
     	   });
 	       </script>';
 
@@ -4742,7 +4743,7 @@ class Form
     	global $conf, $langs;
 
     	$out = '';
-    	
+
     	// Add code for jquery to use multiselect
     	if (! empty($conf->global->MAIN_USE_JQUERY_MULTISELECT) || defined('REQUIRE_JQUERY_MULTISELECT'))
     	{
@@ -4829,7 +4830,7 @@ class Form
     static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
     {
         global $user;
-        
+
         $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
         if (! empty($user->conf->$tmpvar))
         {
@@ -4843,33 +4844,33 @@ class Form
             }
         }
         //var_dump($array);
-            
+
         $lis='';
         $listcheckedstring='';
-        
+
         foreach($array as $key => $val)
         {
            /* var_dump($val);
             var_dump(array_key_exists('enabled', $val));
             var_dump(!$val['enabled']);*/
-           if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled']) 
+           if (array_key_exists('enabled', $val) && isset($val['enabled']) && ! $val['enabled'])
            {
                unset($array[$key]);     // We don't want this field
-               continue; 
+               continue;
            }
-           if ($val['label']) 
+           if ($val['label'])
 	       {
 	           $lis.='<li><input type="checkbox" value="'.$key.'"'.(empty($val['checked'])?'':' checked="checked"').'/>'.dol_escape_htmltag($val['label']).'</li>';
 	           $listcheckedstring.=(empty($val['checked'])?'':$key.',');
 	       }
         }
-        
-        $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' --> 
-            
-            <dl class="dropdown"> 
+
+        $out ='<!-- Component multiSelectArrayWithCheckbox '.$htmlname.' -->
+
+            <dl class="dropdown">
             <dt>
             <a href="#">
-              '.img_picto('','list').'    
+              '.img_picto('','list').'
               <input type="hidden" class="'.$htmlname.'" name="'.$htmlname.'" value="'.$listcheckedstring.'">
             </a>
             </dt>
@@ -4881,38 +4882,38 @@ class Form
                 </div>
             </dd>
         </dl>
-            
+
         <script type="text/javascript">
           $(".dropdown dt a").on(\'click\', function () {
               $(".dropdown dd ul").slideToggle(\'fast\');
           });
-    
+
           $(".dropdown dd ul li a").on(\'click\', function () {
               $(".dropdown dd ul").hide();
           });
-    
+
           function getSelectedValue(id) {
                return $("#" + id).find("dt a span.value").html();
           }
-    
+
           $(document).bind(\'click\', function (e) {
               var $clicked = $(e.target);
               if (!$clicked.parents().hasClass("dropdown")) $(".dropdown dd ul").hide();
           });
-    
+
           $(\'.multiselectcheckbox'.$htmlname.' input[type="checkbox"]\').on(\'click\', function () {
               console.log("A new field was added/removed")
               $("input:hidden[name=formfilteraction]").val(\'listafterchangingselectedfields\')
               var title = $(this).val() + ",";
               if ($(this).is(\':checked\')) {
                   $(\'.'.$htmlname.'\').val(title + $(\'.'.$htmlname.'\').val());
-              } 
+              }
               else {
                   $(\'.'.$htmlname.'\').val( $(\'.'.$htmlname.'\').val().replace(title, \'\') )
               }
-          });        
-        </script>            
-            
+          });
+        </script>
+
         ';
         return $out;
     }
@@ -5113,7 +5114,7 @@ class Form
 				}
 				print '</table>';
 				print '<div class="center"><input type="submit" class="button" value="' . $langs->trans('ToLink') . '">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<input type="submit" class="button" name="cancel" value="' . $langs->trans('Cancel') . '"></div>';
-				
+
 				print '</form>';
 				$this->db->free($resqlorderlist);
 			} else {
@@ -5319,9 +5320,9 @@ class Form
 
         //print "xx".$previous_ref."x".$next_ref;
         $ret.='<div style="vertical-align: middle">';
-        
+
 		$ret.='<div class="inline-block floatleft">'.$morehtmlleft.'</div>';
-        
+
         $ret.='<div class="inline-block floatleft valignmiddle refid'.(($shownav && ($previous_ref || $next_ref))?' refidpadding':'').'">';
 
         // For thirdparty and contact, the ref is the id, so we show something else
@@ -5359,7 +5360,7 @@ class Form
         }
 		if ($morehtmlright) $ret.='<div class="statusref">'.$morehtmlright.'</div>';
         $ret.='</div>';
-		
+
         return $ret;
     }
 
@@ -5418,7 +5419,7 @@ class Form
         if ($modulepart=='societe')
         {
             $dir=$conf->societe->multidir_output[$entity];
-            if (! empty($object->logo)) 
+            if (! empty($object->logo))
             {
                 if ((string) $imagesize == 'mini') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_mini');             // getImageFileNameForSize include the thumbs
                 else if ((string) $imagesize == 'small') $file=get_exdir(0, 0, 0, 0, $object, 'thirdparty').'/logos/'.getImageFileNameForSize($object->logo, '_small');
@@ -5453,7 +5454,7 @@ class Form
         else if ($modulepart=='memberphoto')
         {
             $dir=$conf->adherent->dir_output;
-            if (! empty($object->photo)) 
+            if (! empty($object->photo))
             {
                 if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_mini');
                 else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, 'member').'photos/'.getImageFileNameForSize($object->photo, '_small');
@@ -5462,11 +5463,11 @@ class Form
             }
             if (! empty($conf->global->MAIN_OLD_IMAGE_LINKS)) $altfile=$object->id.".jpg";	// For backward compatibility
             $email=$object->email;
-        } 
-        else 
+        }
+        else
         {
         	$dir=$conf->$modulepart->dir_output;
-        	if (! empty($object->photo)) 
+        	if (! empty($object->photo))
         	{
                 if ((string) $imagesize == 'mini') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_mini');
                 else if ((string) $imagesize == 'small') $file=get_exdir($id, 2, 0, 0, $object, $modulepart).'photos/'.getImageFileNameForSize($object->photo, '_small');
diff --git a/htdocs/install/mysql/tables/llx_societe_remise.sql b/htdocs/install/mysql/tables/llx_societe_remise.sql
index 14b4ea85639458fea05702be89a734ba87756c6f..a9d41fcd5021444047918c300964d88461114020 100644
--- a/htdocs/install/mysql/tables/llx_societe_remise.sql
+++ b/htdocs/install/mysql/tables/llx_societe_remise.sql
@@ -1,6 +1,6 @@
 -- ========================================================================
 -- Copyright (C) 2000-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
--- Copyright (C) 2011      Regis Houssin        <regis.houssin@capnetworks.com>
+-- Copyright (C) 2011-2016 Regis Houssin        <regis.houssin@capnetworks.com>
 --
 -- This program is free software; you can redistribute it and/or modify
 -- it under the terms of the GNU General Public License as published by
@@ -21,13 +21,14 @@
 
 create table llx_societe_remise
 (
-  rowid           integer AUTO_INCREMENT PRIMARY KEY,
-  fk_soc          integer NOT NULL,
-  tms             timestamp,
-  datec	          datetime,                            -- creation date
-  fk_user_author  integer,                             -- creation user
-  remise_client   double(6,3)  DEFAULT 0 NOT NULL,     -- discount
-  note            text
+  rowid				integer AUTO_INCREMENT PRIMARY KEY,
+  entity			integer DEFAULT 1 NOT NULL,			-- multi company id
+  fk_soc			integer NOT NULL,
+  tms				timestamp,
+  datec				datetime,							-- creation date
+  fk_user_author	integer,							-- creation user
+  remise_client		double(6,3)  DEFAULT 0 NOT NULL,	-- discount
+  note				text
 
 )ENGINE=innodb;
 
diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.sql
index 767dc4da0075555bcc1d63949b37cdd821efc56e..adfbfe9947c1b4516977046f794938a749867a05 100644
--- a/htdocs/install/mysql/tables/llx_societe_remise_except.sql
+++ b/htdocs/install/mysql/tables/llx_societe_remise_except.sql
@@ -22,6 +22,7 @@
 create table llx_societe_remise_except
 (
   rowid					integer AUTO_INCREMENT PRIMARY KEY,
+  entity				integer DEFAULT 1 NOT NULL,				-- multi company id
   fk_soc				integer NOT NULL, -- client
   datec					datetime,
   amount_ht				double(24,8) NOT NULL,
diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php
index 60f6e082f50599359f2ba3f488cf9ce06f7ac2b7..9385b8268333a14f947f204e79a338459c33394c 100644
--- a/htdocs/install/upgrade2.php
+++ b/htdocs/install/upgrade2.php
@@ -396,6 +396,24 @@ if (! GETPOST("action") || preg_match('/upgrade/i',GETPOST('action')))
         	migrate_reload_menu($db,$langs,$conf,$versionto);
         }
 
+        // Scripts for last version
+        $afterversionarray=explode('.','3.8.9');
+        $beforeversionarray=explode('.','3.9.9');
+        if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
+        {
+        	// Migrate to add entity value into llx_societe_remise
+        	migrate_remise_entity($db,$langs,$conf);
+
+        	// Migrate to add entity value into llx_societe_remise_except
+        	migrate_remise_except_entity($db,$langs,$conf);
+
+        	// Reload modules (this must be always and only into last targeted version)
+        	migrate_reload_modules($db,$langs,$conf);
+
+        	// Reload menus (this must be always and only into last targeted version)
+        	migrate_reload_menu($db,$langs,$conf,$versionto);
+        }
+
         print '<tr><td colspan="4"><br>'.$langs->trans("MigrationFinished").'</td></tr>';
 
         // On commit dans tous les cas.
@@ -1292,10 +1310,10 @@ function migrate_paiementfourn_facturefourn($db,$langs,$conf)
 function migrate_price_facture($db,$langs,$conf)
 {
     $err=0;
-    
+
     $tmpmysoc=new Societe($db);
     $tmpmysoc->setMysoc($conf);
-    
+
     $db->begin();
 
     print '<tr><td colspan="4">';
@@ -1412,7 +1430,7 @@ function migrate_price_propal($db,$langs,$conf)
 {
    	$tmpmysoc=new Societe($db);
 	$tmpmysoc->setMysoc($conf);
-    
+
     $db->begin();
 
     print '<tr><td colspan="4">';
@@ -1611,7 +1629,7 @@ function migrate_price_commande($db,$langs,$conf)
 
     $tmpmysoc=new Societe($db);
     $tmpmysoc->setMysoc($conf);
-    
+
     print '<tr><td colspan="4">';
 
     print '<br>';
@@ -1725,10 +1743,10 @@ function migrate_price_commande($db,$langs,$conf)
 function migrate_price_commande_fournisseur($db,$langs,$conf)
 {
     $db->begin();
-    
+
     $tmpmysoc=new Societe($db);
     $tmpmysoc->setMysoc($conf);
-    
+
     print '<tr><td colspan="4">';
 
     print '<br>';
@@ -3622,6 +3640,196 @@ function migrate_event_assignement($db,$langs,$conf)
 	print '</td></tr>';
 }
 
+/**
+ * Migrate to add entity value into llx_societe_remise
+ *
+ * @param	DoliDB		$db				Database handler
+ * @param	Translate	$langs			Object langs
+ * @param	Conf		$conf			Object conf
+ * @return	void
+ */
+function migrate_remise_entity($db,$langs,$conf)
+{
+	print '<tr><td colspan="4">';
+
+	print '<br>';
+	print '<b>'.$langs->trans('MigrationRemiseEntity')."</b><br>\n";
+
+	$error = 0;
+
+	dolibarr_install_syslog("upgrade2::migrate_remise_entity");
+
+	$db->begin();
+
+	$sqlSelect = "SELECT sr.rowid, s.entity";
+	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise as sr, ".MAIN_DB_PREFIX."societe as s";
+	$sqlSelect.= " WHERE sr.fk_soc = s.rowid";
+
+	//print $sqlSelect;
+
+	$resql = $db->query($sqlSelect);
+	if ($resql)
+	{
+		$i = 0;
+		$num = $db->num_rows($resql);
+
+		if ($num)
+		{
+			while ($i < $num)
+			{
+				$obj = $db->fetch_object($resql);
+
+				$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise SET";
+				$sqlUpdate.= " entity = " . $obj->entity;
+				$sqlUpdate.= " WHERE rowid = " . $obj->rowid;
+
+				$result=$db->query($sqlUpdate);
+				if (! $result)
+				{
+					$error++;
+					dol_print_error($db);
+				}
+
+				print ". ";
+				$i++;
+			}
+		}
+		else
+		{
+			print $langs->trans('AlreadyDone')."<br>\n";
+		}
+
+		if (! $error)
+		{
+			$db->commit();
+		}
+		else
+		{
+			$db->rollback();
+		}
+	}
+	else
+	{
+		dol_print_error($db);
+		$db->rollback();
+	}
+
+
+	print '</td></tr>';
+}
+
+/**
+ * Migrate to add entity value into llx_societe_remise_except
+ *
+ * @param	DoliDB		$db				Database handler
+ * @param	Translate	$langs			Object langs
+ * @param	Conf		$conf			Object conf
+ * @return	void
+ */
+function migrate_remise_except_entity($db,$langs,$conf)
+{
+	print '<tr><td colspan="4">';
+
+	print '<br>';
+	print '<b>'.$langs->trans('MigrationRemiseExceptEntity')."</b><br>\n";
+
+	$error = 0;
+
+	dolibarr_install_syslog("upgrade2::migrate_remise_except_entity");
+
+	$db->begin();
+
+	$sqlSelect = "SELECT sr.rowid, sr.fk_soc, sr.fk_facture_source, sr.fk_facture, sr.fk_facture_line";
+	$sqlSelect.= " FROM ".MAIN_DB_PREFIX."societe_remise_except as sr";
+	//print $sqlSelect;
+
+	$resql = $db->query($sqlSelect);
+	if ($resql)
+	{
+		$i = 0;
+		$num = $db->num_rows($resql);
+
+		if ($num)
+		{
+			while ($i < $num)
+			{
+				$obj = $db->fetch_object($resql);
+
+				if (!empty($obj->fk_facture_source) || !empty($obj->fk_facture))
+				{
+					$fk_facture = (!empty($obj->fk_facture_source) ? $obj->fk_facture_source : $obj->fk_facture);
+
+					$sqlSelect2 = "SELECT f.entity";
+					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f";
+					$sqlSelect2.= " WHERE f.rowid = " . $fk_facture;
+				}
+				else if (!empty($obj->fk_facture_line))
+				{
+					$sqlSelect2 = "SELECT f.entity";
+					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."facture as f, ".MAIN_DB_PREFIX."facturedet as fd";
+					$sqlSelect2.= " WHERE fd.rowid = " . $obj->fk_facture_line;
+					$sqlSelect2.= " AND fd.fk_facture = f.rowid";
+				}
+				else
+				{
+					$sqlSelect2 = "SELECT s.entity";
+					$sqlSelect2.= " FROM ".MAIN_DB_PREFIX."societe as s";
+					$sqlSelect2.= " WHERE s.rowid = " . $obj->fk_soc;
+				}
+
+				$resql2 = $db->query($sqlSelect2);
+				if ($resql2)
+				{
+					if ($db->num_rows($resql2) > 0)
+					{
+						$obj2 = $db->fetch_object($resql2);
+
+						$sqlUpdate = "UPDATE ".MAIN_DB_PREFIX."societe_remise_except SET";
+						$sqlUpdate.= " entity = " . $obj2->entity;
+						$sqlUpdate.= " WHERE rowid = " . $obj->rowid;
+
+						$result=$db->query($sqlUpdate);
+						if (! $result)
+						{
+							$error++;
+							dol_print_error($db);
+						}
+					}
+				}
+				else
+				{
+					$error++;
+					dol_print_error($db);
+				}
+
+				print ". ";
+				$i++;
+			}
+		}
+		else
+		{
+			print $langs->trans('AlreadyDone')."<br>\n";
+		}
+
+		if (! $error)
+		{
+			$db->commit();
+		}
+		else
+		{
+			$db->rollback();
+		}
+	}
+	else
+	{
+		dol_print_error($db);
+		$db->rollback();
+	}
+
+
+	print '</td></tr>';
+}
+
 /**
  * Migration directory
  *
@@ -3788,7 +3996,7 @@ function migrate_reload_modules($db,$langs,$conf,$listofmodule=array())
     	if (empty($moduletoreload) || empty($conf->global->$moduletoreload)) continue;
 
     	$mod=null;
-    	
+
 	    if ($moduletoreload == 'MAIN_MODULE_AGENDA')
 	    {
 	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Agenda module");
@@ -3951,7 +4159,7 @@ function migrate_reload_modules($db,$langs,$conf,$listofmodule=array())
 	    }
 
 		if (! empty($mod) && is_object($mod))
-		{	    
+		{
     		print '<tr><td colspan="4">';
         	print '<b>'.$langs->trans('Upgrade').'</b>: ';
         	print $langs->trans('MigrationReloadModule')." ".$mod->getName();
@@ -3983,7 +4191,7 @@ function migrate_reload_menu($db,$langs,$conf,$versionto)
 
     $versiontoarray=explode('.',$versionto);
 
-    // Migration required when target version is between 
+    // Migration required when target version is between
     $afterversionarray=explode('.','2.8.9');
     $beforeversionarray=explode('.','2.9.9');
     if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
@@ -3991,7 +4199,7 @@ function migrate_reload_menu($db,$langs,$conf,$versionto)
         $listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
     }
 
-    // Migration required when target version is between 
+    // Migration required when target version is between
     $afterversionarray=explode('.','3.1.9');
     $beforeversionarray=explode('.','3.2.9');
     if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
@@ -3999,7 +4207,7 @@ function migrate_reload_menu($db,$langs,$conf,$versionto)
         $listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
     }
 
-    // Migration required when target version is between 
+    // Migration required when target version is between
     $afterversionarray=explode('.','3.7.9');
     $beforeversionarray=explode('.','3.8.9');
     if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
diff --git a/htdocs/langs/en_US/install.lang b/htdocs/langs/en_US/install.lang
index ed692c074249fab9d4db6ac00028abc77b3c621d..8a26dadb623a1c52f585d958beaed73b8cfb70b6 100644
--- a/htdocs/langs/en_US/install.lang
+++ b/htdocs/langs/en_US/install.lang
@@ -202,6 +202,8 @@ MigrationActioncommElement=Update data on actions
 MigrationPaymentMode=Data migration for payment mode
 MigrationCategorieAssociation=Migration of categories
 MigrationEvents=Migration of events to add event owner into assignement table
+MigrationRemiseEntity=Update entity field value of llx_societe_remise
+MigrationRemiseExceptEntity=Update entity field value of llx_societe_remise_except
 MigrationReloadModule=Reload module %s
 ShowNotAvailableOptions=Show not available options
 HideNotAvailableOptions=Hide not available options
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 3282d8a9eba0259d7c8259b00e54f6a88ab8af2f..a7398588fbbe4629c2731896a07fe2630c8a3ded 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -1377,6 +1377,18 @@ class Societe extends CommonObject
                 }
             }
 
+            // Remove societe_remise_except
+            if (! $error)
+            {
+            	$sql = "DELETE FROM ".MAIN_DB_PREFIX."societe_remise";
+            	$sql.= " WHERE fk_soc = " . $id;
+            	if (! $this->db->query($sql))
+            	{
+            		$error++;
+            		$this->error = $this->db->lasterror();
+            	}
+            }
+
 		    // Remove societe_remise_except
             if (! $error)
             {
@@ -1488,7 +1500,7 @@ class Societe extends CommonObject
      */
     function set_remise_client($remise, $note, User $user)
     {
-        global $langs;
+        global $conf, $langs;
 
         // Nettoyage parametres
         $note=trim($note);
@@ -1520,8 +1532,8 @@ class Societe extends CommonObject
 
             // Ecrit trace dans historique des remises
             $sql = "INSERT INTO ".MAIN_DB_PREFIX."societe_remise";
-            $sql.= " (datec, fk_soc, remise_client, note, fk_user_author)";
-            $sql.= " VALUES ('".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
+            $sql.= " (entity, datec, fk_soc, remise_client, note, fk_user_author)";
+            $sql.= " VALUES (".$conf->entity.", '".$this->db->idate($now)."', ".$this->id.", '".$this->db->escape($remise)."',";
             $sql.= " '".$this->db->escape($note)."',";
             $sql.= " ".$user->id;
             $sql.= ")";
@@ -1853,10 +1865,10 @@ class Societe extends CommonObject
         $link.=(!empty($this->canvas)?'&canvas='.$this->canvas:'').'"';
         if (empty($notooltip))
         {
-            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) 
+            if (! empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
             {
                 $label=$langs->trans("ShowCompany");
-                $link.=' alt="'.dol_escape_htmltag($label, 1).'"'; 
+                $link.=' alt="'.dol_escape_htmltag($label, 1).'"';
             }
             $link.= ' title="'.dol_escape_htmltag($label, 1).'"';
             $link.=' class="classfortooltip"';
@@ -3078,7 +3090,7 @@ class Societe extends CommonObject
         }
         else return false;
     }
-    
+
     /**
      *  Check if we must use revenue stamps feature or not according to country (country of $mysocin most cases).
      *
@@ -3370,7 +3382,7 @@ class Societe extends CommonObject
 
 	}
 
-	
+
 	/**
 	 *  Create a document onto disk according to template module.
 	 *
@@ -3405,8 +3417,8 @@ class Societe extends CommonObject
 
 		return $result;
 	}
-	
-	
+
+
 	/**
 	 * Sets object to supplied categories.
 	 *
@@ -3481,13 +3493,10 @@ class Societe extends CommonObject
 		 * Thirdparty commercials cannot be the same in both thirdparties so we look for them and remove some
 		 * Because this function is meant to be executed within a transaction, we won't take care of it.
 		 */
-		$sql = 'SELECT rowid
-FROM '.MAIN_DB_PREFIX.'societe_commerciaux
-WHERE fk_soc = '.(int) $dest_id.' AND fk_user IN (
-  SELECT fk_user
-  FROM '.MAIN_DB_PREFIX.'societe_commerciaux
-  WHERE fk_soc = '.(int) $origin_id.'
-);';
+		$sql = 'SELECT rowid';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'societe_commerciaux';
+		$sql.= ' WHERE fk_soc = ' . (int) $dest_id;
+		$sql.= ' AND fk_user IN (SELECT fk_user FROM '.MAIN_DB_PREFIX.'societe_commerciaux WHERE fk_soc = '.(int) $origin_id.');';
 
 		$query = $db->query($sql);