diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php
index b682b214da87e79148818aef40f7e8861878e250..9407553f325f993847427101b06920a6e9aa2aa7 100644
--- a/htdocs/comm/remx.php
+++ b/htdocs/comm/remx.php
@@ -248,7 +248,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);
@@ -318,7 +319,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 e256dbfb649912de730f27b91a12b1613488fdb9..9a59801f720fbaafdc84276a5a80bc1221725e28 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 507f45a12f8b48e8af3d1b60a647d92803982171..334aabbd3622b1d6bdbbfcdefe88de23ffd76e0c 100644
--- a/htdocs/core/class/html.form.class.php
+++ b/htdocs/core/class/html.form.class.php
@@ -203,7 +203,7 @@ class Form
                     $ret.=$doleditor->Create(1);
                 }
                 $ret.='</td>';
-               	
+
                 $ret.='<td align="left">';
                	$ret.='<input type="submit" class="button" name="modify" value="'.$langs->trans("Modify").'">';
                	if (preg_match('/ckeditor|textarea/',$typeofdata)) $ret.='<br>'."\n";
@@ -493,7 +493,7 @@ class Form
 
     /**
      * Generate select HTML to choose massaction
-     * 
+     *
      * @param	string	$selected		Selected value
      * @param	int		$arrayofaction	array('code'=>'label', ...). The code is the key stored into the GETPOST('massaction') when submitting action.
      * @return	string					Select list
@@ -501,9 +501,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>';
@@ -515,7 +515,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">
     		function initCheckForSelect()
@@ -534,7 +534,7 @@ class Form
 	  				jQuery(".massaction").hide();
 	  			}
     		}
-    	    
+
     	jQuery(document).ready(function () {
     		initCheckForSelect();
     		jQuery(".checkforselect").click(function() {
@@ -556,10 +556,10 @@ class Form
     	});
 		</script>
     	';
-    	
+
     	return $ret;
     }
-    
+
     /**
      *  Return combo list of activated countries, into language of user
      *
@@ -1029,9 +1029,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";
@@ -1117,7 +1117,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";
 
@@ -1350,7 +1351,7 @@ class Form
      *  @param	integer	$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
      */
@@ -1881,7 +1882,7 @@ class Form
         $outlabel=$objp->label;
         $outdesc=$objp->description;
         $outbarcode=$objp->barcode;
-        
+
         $outtype=$objp->fk_product_type;
         $outdurationvalue=$outtype == Product::TYPE_SERVICE?substr($objp->duration,0,dol_strlen($objp->duration)-1):'';
         $outdurationunit=$outtype == Product::TYPE_SERVICE?substr($objp->duration,-1):'';
@@ -1898,13 +1899,13 @@ class Form
         $opt.= $objp->ref;
         if ($outbarcode) $opt.=' ('.$outbarcode.')';
         $opt.=' - '.dol_trunc($label,$maxlengtharticle).' - ';
-        
+
         $objRef = $objp->ref;
         if (! empty($filterkey) && $filterkey != '') $objRef=preg_replace('/('.preg_quote($filterkey).')/i','<strong>$1</strong>',$objRef,1);
         $outval.=$objRef;
         if ($outbarcode) $outval.=' ('.$outbarcode.')';
         $outval.=' - '.dol_trunc($label,$maxlengtharticle).' - ';
-        
+
         $found=0;
 
         // Multiprice
@@ -1986,9 +1987,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;
 
@@ -2066,7 +2067,7 @@ class Form
     {
         global $langs,$conf;
         global $price_level, $status, $finished;
-        
+
         $selected_input_value='';
         if (! empty($conf->use_javascript_ajax) && ! empty($conf->global->PRODUIT_USE_SEARCH_TO_SELECT))
         {
@@ -2198,11 +2199,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).' - ';
@@ -2805,7 +2806,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;
 
@@ -3168,13 +3169,13 @@ class Form
         $langs->load("categories");
 
 		include_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
-        
+
 		// For backward compatibility
 		if (is_numeric($type))
 		{
 		    dol_syslog(__METHOD__ . ': using numeric value for parameter type is deprecated. Use string code instead.', LOG_WARNING);
 		}
-		
+
         $cat = new Categorie($this->db);
         $cate_arbo = $cat->get_full_arbo($type,$excludeafterid);
 
@@ -3794,7 +3795,7 @@ class Form
             }
         }
     }
-	
+
 	/**
      *    Show form with multicurrency code
      *
@@ -3824,7 +3825,7 @@ class Form
         	print !empty($selected) ? currency_name($selected,1) : '&nbsp;';
         }
     }
-	
+
 	/**
      *    Show form with multicurrency rate
      *
@@ -3837,7 +3838,7 @@ class Form
     function form_multicurrency_rate($page, $rate='', $htmlname='multicurrency_tx', $currency='')
     {
         global $langs, $mysoc, $conf;
-        
+
         if ($htmlname != "none")
         {
             print '<form method="POST" action="'.$page.'">';
@@ -4068,7 +4069,7 @@ class Form
 
 	/**
      *	Return array of currencies in user language
-	 * 
+	 *
      *  @param	string	$selected    preselected currency code
      *  @param  string	$htmlname    name of HTML select list
      *  @param  integer	$useempty    1=Add empty line
@@ -4081,7 +4082,7 @@ class Form
         $langs->loadCacheCurrencies('');        // Load ->cache_currencies
 
 		$TCurrency = array();
-		
+
 		$sql = 'SELECT code FROM '.MAIN_DB_PREFIX.'multicurrency';
 		$sql.= " WHERE entity IN ('".getEntity('mutlicurrency')."')";
 		$resql = $db->query($sql);
@@ -4089,7 +4090,7 @@ class Form
 		{
 			while ($obj = $db->fetch_object($resql)) $TCurrency[$obj->code] = $obj->code;
 		}
-		
+
 		$out='';
         $out.= '<select class="flat" name="'.$htmlname.'" id="'.$htmlname.'">';
 		if ($useempty) $out .= '<option value=""></option>';
@@ -4101,19 +4102,19 @@ class Form
 				{
 					if (!empty($selected) && $selected == $code_iso) $out.= '<option value="'.$code_iso.'" selected="selected">';
 		        	else $out.= '<option value="'.$code_iso.'">';
-		        	
+
 		        	$out.= $currency['label'];
 		        	$out.= ' ('.$langs->getCurrencySymbol($code_iso).')';
-		        	$out.= '</option>';	
+		        	$out.= '</option>';
 				}
 	        }
-	        
+
 		}
-        
+
         $out.= '</select>';
         return $out;
     }
-	
+
     /**
      *	Load into the cache vat rates of a country
      *
@@ -4204,7 +4205,7 @@ class Form
             $defaulttx=preg_replace('/\s*\(.*\)/','',$defaulttx);
         }
         //var_dump($selectedrate.'-'.$defaulttx.'-'.$defaultnpr.'-'.$defaultcode);
-        
+
         // Check parameters
         if (is_object($societe_vendeuse) && ! $societe_vendeuse->country_code)
         {
@@ -4303,7 +4304,7 @@ class Form
         		$return.= '"';
         		if ($defaultcode) // If defaultcode is defined, we used it in priority to select combo option instead of using rate+npr flag
         		{
-                    if ($defaultcode == $rate['code']) $return.= ' selected';    	
+                    if ($defaultcode == $rate['code']) $return.= ' selected';
         		}
         		elseif ($rate['txtva'] == $defaulttx && $rate['nprtva'] == $defaultnpr)
            		{
@@ -4312,7 +4313,7 @@ class Form
         		$return.= '>'.vatrate($rate['libtva']);
         		//$return.=($rate['code']?' '.$rate['code']:'');
         		$return.= (empty($rate['code']) && $rate['nprtva']) ? ' *': '';         // We show the *  (old behaviour only if new vat code is not used)
-        		
+
         		$return.= '</option>';
         	}
 
@@ -4616,7 +4617,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;
 
@@ -4821,19 +4822,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",
@@ -4868,7 +4869,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.',
@@ -4876,9 +4877,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 ) {
@@ -4889,7 +4890,7 @@ class Form
     			            }
                     });
     			});' : '' ) . '
-    			
+
     	   });
 	       </script>';
 
@@ -4925,7 +4926,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'))
     	{
@@ -5012,7 +5013,7 @@ class Form
     static function multiSelectArrayWithCheckbox($htmlname, &$array, $varpage)
     {
         global $user;
-        
+
         $tmpvar="MAIN_SELECTEDFIELDS_".$varpage;
         if (! empty($user->conf->$tmpvar))
         {
@@ -5026,33 +5027,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>
@@ -5064,41 +5065,41 @@ 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, \'\') )
               }
               // Now, we submit page
               $(this).parents(\'form:first\').submit();
         });
-                      
-        </script>            
-            
+
+        </script>
+
         ';
         return $out;
     }
@@ -5182,7 +5183,7 @@ class Form
         			$tplpath = $element.'/'.$subelement;
         		}
         		$tplname='linkedobjectblock';
-        		
+
         		// To work with non standard path
         		if ($objecttype == 'facture')          {
         			$tplpath = 'compta/'.$element;
@@ -5220,17 +5221,17 @@ class Form
         		else if ($objecttype == 'subscription')   {
         		    $tplpath = 'adherents';
         		}
-        		
+
                 global $linkedObjectBlock;
         		$linkedObjectBlock = $objects;
 
         		if (empty($numoutput))
         		{
         		    $numoutput++;
-        		    
+
         		    print '<br>';
         		    print load_fiche_titre($langs->trans('RelatedObjects'), '', '');
-        		    
+
         		    print '<table class="noborder allwidth">';
 
         		    print '<tr class="liste_titre">';
@@ -5243,7 +5244,7 @@ class Form
         			print '<td></td>';
         		    print '</tr>';
         		}
-        		        		
+
         		// Output template part (modules that overwrite templates must declare this into descriptor)
         		$dirtpls=array_merge($conf->modules_parts['tpl'],array('/'.$tplpath.'/tpl'));
         		foreach($dirtpls as $reldir)
@@ -5253,11 +5254,11 @@ class Form
         		}
         	}
 
-        	if ($numoutput) 
+        	if ($numoutput)
         	{
         	    print '</table>';
         	}
-        	    
+
         	return $num;
         }
     }
@@ -5336,7 +5337,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 {
@@ -5604,9 +5605,9 @@ class Form
 
         //print "xx".$previous_ref."x".$next_ref;
         $ret.='<div style="vertical-align: middle">';
-        
+
 		if ($morehtmlleft) $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
@@ -5626,7 +5627,7 @@ class Form
 		$ret.='</div>';
 
 		if ($morehtmlright) $ret.='<div class="inline-block floatleft">'.$morehtmlright.'</div>';
-		
+
         if ($previous_ref || $next_ref || $morehtml)
         {
         	$ret.='<div class="pagination"><ul>';
@@ -5646,7 +5647,7 @@ class Form
         }
 		if ($morehtmlstatus) $ret.='<div class="statusref">'.$morehtmlstatus.'</div>';
         $ret.='</div>';
-		
+
         return $ret;
     }
 
@@ -5705,7 +5706,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');
@@ -5740,7 +5741,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');
@@ -5749,11 +5750,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');
@@ -5931,10 +5932,10 @@ class Form
      *  @param	int  	$addcheckuncheckall        Add the check all uncheck all button
      *  @param  string  $cssclass                  CSS class
      *  @param  int     $calljsfunction            0=default. 1=call function initCheckForSelect() after changing status of checkboxes
-     *  @return	string                          
+     *  @return	string
      */
     function showFilterAndCheckAddButtons($addcheckuncheckall=0, $cssclass='checkforaction', $calljsfunction=0)
-    {   
+    {
         global $conf, $langs;
 
         $out='';
diff --git a/htdocs/install/mysql/migration/3.9.0-4.0.0.sql b/htdocs/install/mysql/migration/3.9.0-4.0.0.sql
index 0ddeaf8f3ade90b09c41fbf89e29831672f224db..5e0555c92a7f3938d8e0282ccb5ebc06fb9dea14 100644
--- a/htdocs/install/mysql/migration/3.9.0-4.0.0.sql
+++ b/htdocs/install/mysql/migration/3.9.0-4.0.0.sql
@@ -327,6 +327,7 @@ ALTER TABLE llx_paiement_facture ADD COLUMN multicurrency_amount double(24,8) DE
 ALTER TABLE llx_paiementfourn ADD COLUMN multicurrency_amount double(24,8) DEFAULT 0;
 ALTER TABLE llx_paiementfourn_facturefourn ADD COLUMN multicurrency_amount double(24,8) DEFAULT 0;
 
+ALTER TABLE llx_societe_remise_except ADD COLUMN entity integer DEFAULT 1 NOT NULL AFTER rowid;
 ALTER TABLE llx_societe_remise_except ADD COLUMN multicurrency_amount_ht double(24,8) DEFAULT 0 NOT NULL;
 ALTER TABLE llx_societe_remise_except ADD COLUMN multicurrency_amount_tva double(24,8) DEFAULT 0 NOT NULL;
 ALTER TABLE llx_societe_remise_except ADD COLUMN multicurrency_amount_ttc double(24,8) DEFAULT 0 NOT NULL;
diff --git a/htdocs/install/mysql/tables/llx_societe_remise_except.sql b/htdocs/install/mysql/tables/llx_societe_remise_except.sql
index f17d17670d22c405eaa229280afba5d0b9139ac6..4c55e34425cf8c8d0b6219e5e976f441c0fc9fc2 100644
--- a/htdocs/install/mysql/tables/llx_societe_remise_except.sql
+++ b/htdocs/install/mysql/tables/llx_societe_remise_except.sql
@@ -21,18 +21,19 @@
 
 create table llx_societe_remise_except
 (
-  rowid					integer AUTO_INCREMENT PRIMARY KEY,
-  fk_soc				integer NOT NULL, -- client
-  datec					datetime,
-  amount_ht				double(24,8) NOT NULL,
-  amount_tva			double(24,8) DEFAULT 0 NOT NULL,
-  amount_ttc			double(24,8) DEFAULT 0 NOT NULL,
-  tva_tx				double(6,3)  DEFAULT 0 NOT NULL,
-  fk_user				integer NOT NULL,
-  fk_facture_line		integer,
-  fk_facture			integer,
-  fk_facture_source		integer,
-  description			text NOT NULL,
+  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,
+  amount_tva				double(24,8) DEFAULT 0 NOT NULL,
+  amount_ttc				double(24,8) DEFAULT 0 NOT NULL,
+  tva_tx					double(6,3)  DEFAULT 0 NOT NULL,
+  fk_user					integer NOT NULL,
+  fk_facture_line			integer,
+  fk_facture				integer,
+  fk_facture_source			integer,
+  description				text NOT NULL,
   multicurrency_amount_ht	double(24,8) DEFAULT 0 NOT NULL,
   multicurrency_amount_tva	double(24,8) DEFAULT 0 NOT NULL,
   multicurrency_amount_ttc	double(24,8) DEFAULT 0 NOT NULL
diff --git a/htdocs/install/upgrade2.php b/htdocs/install/upgrade2.php
index d3eb23e99b6086c786cc220896763fa5d6696eb8..f7871088c6be8a67419eb3af9756acec5326d301 100644
--- a/htdocs/install/upgrade2.php
+++ b/htdocs/install/upgrade2.php
@@ -396,14 +396,17 @@ if (! GETPOST("action") || preg_match('/upgrade/i',GETPOST('action')))
         	// Reload menus (this must be always and only into last targeted version)
         	migrate_reload_menu($db,$langs,$conf,$versionto);
         }
-        
+
         // Scripts for last version
         $afterversionarray=explode('.','3.9.9');
         $beforeversionarray=explode('.','4.0.9');
         if (versioncompare($versiontoarray,$afterversionarray) >= 0 && versioncompare($versiontoarray,$beforeversionarray) <= 0)
         {
+        	// Migrate to add entity value into llx_societe_remise_except
+        	migrate_remise_except_entity($db,$langs,$conf);
+
             migrate_directories($db,$langs,$conf,'/fckeditor','/medias');
-            
+
         	// Reload modules (this must be always and only into last targeted version)
         	$listofmodule=array(
         	    'MAIN_MODULE_BARCODE'=>'newboxdefonly',
@@ -412,12 +415,12 @@ if (! GETPOST("action") || preg_match('/upgrade/i',GETPOST('action')))
         	    'MAIN_MODULE_PRINTING'=>'newboxdefonly',
         	);
         	migrate_reload_modules($db,$langs,$conf,$listofmodule);
-        
+
         	// Reload menus (this must be always and only into last targeted version)
         	migrate_reload_menu($db,$langs,$conf,$versionto);
         }
 
-        
+
         // Can force activation of some module during migration with third paramater = MAIN_MODULE_XXX,MAIN_MODULE_YYY,...
         if ($enablemodules)
         {
@@ -430,8 +433,8 @@ if (! GETPOST("action") || preg_match('/upgrade/i',GETPOST('action')))
             }
             migrate_reload_modules($db,$langs,$conf,$listofmodules,1);
         }
-        
-        
+
+
         print '<tr><td colspan="4"><br>'.$langs->trans("MigrationFinished").'</td></tr>';
 
         // On commit dans tous les cas.
@@ -1328,10 +1331,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">';
@@ -1448,7 +1451,7 @@ function migrate_price_propal($db,$langs,$conf)
 {
    	$tmpmysoc=new Societe($db);
 	$tmpmysoc->setMysoc($conf);
-    
+
     $db->begin();
 
     print '<tr><td colspan="4">';
@@ -1647,7 +1650,7 @@ function migrate_price_commande($db,$langs,$conf)
 
     $tmpmysoc=new Societe($db);
     $tmpmysoc->setMysoc($conf);
-    
+
     print '<tr><td colspan="4">';
 
     print '<br>';
@@ -1761,10 +1764,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>';
@@ -3658,6 +3661,118 @@ function migrate_event_assignement($db,$langs,$conf)
 	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
  *
@@ -3825,7 +3940,7 @@ function migrate_reload_modules($db,$langs,$conf,$listofmodule=array(),$force=0)
     	if (empty($moduletoreload) || (empty($conf->global->$moduletoreload) && ! $force)) continue; // Discard reload if module not enabled
 
     	$mod=null;
-    	
+
 	    if ($moduletoreload == 'MAIN_MODULE_AGENDA')
 	    {
 	        dolibarr_install_syslog("upgrade2::migrate_reload_modules Reactivate Agenda module");
@@ -3998,7 +4113,7 @@ function migrate_reload_modules($db,$langs,$conf,$listofmodule=array(),$force=0)
 	    }
 
 		if (! empty($mod) && is_object($mod))
-		{	    
+		{
     		print '<tr><td colspan="4">';
         	print '<b>'.$langs->trans('Upgrade').'</b>: ';
         	print $langs->trans('MigrationReloadModule').' '.$mod->getName();  // We keep getName outside of trans because getName is already encoded/translated
@@ -4030,7 +4145,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)
@@ -4038,7 +4153,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)
@@ -4053,7 +4168,7 @@ function migrate_reload_menu($db,$langs,$conf,$versionto)
     {
         $listofmenuhandler['auguria']=1;   // We set here only dynamic menu handlers
     }
-    
+
     foreach ($listofmenuhandler as $key => $val)
     {
         print '<tr><td colspan="4">';
diff --git a/htdocs/langs/en_US/install.lang b/htdocs/langs/en_US/install.lang
index f9d1d1338c69c41e14299166cf7efa8ec597ec99..3d56c38e584d59d44fba985f568a9a19f180b001 100644
--- a/htdocs/langs/en_US/install.lang
+++ b/htdocs/langs/en_US/install.lang
@@ -184,6 +184,7 @@ 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
+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 21bfed210fb69739353efd5804fc96907d28da6f..69eaa28541f936dd72168547104c9555a27bca12 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -357,7 +357,7 @@ class Societe extends CommonObject
 	// Multicurrency
 	var $fk_multicurrency;
 	var $multicurrency_code;
-	
+
     /**
      * To contains a clone of this when we need to save old properties of object
      *  @var Societe
@@ -406,14 +406,14 @@ class Societe extends CommonObject
         if (empty($this->client))      $this->client=0;
         if (empty($this->fournisseur)) $this->fournisseur=0;
         $this->import_key = trim($this->import_key);
-		
+
 		if (!empty($this->multicurrency_code)) $this->fk_multicurrency = MultiCurrency::getIdFromCode($this->db, $this->multicurrency_code);
 		if (empty($this->fk_multicurrency))
 		{
 			$this->multicurrency_code = '';
 			$this->fk_multicurrency = 0;
 		}
-		
+
         dol_syslog(get_class($this)."::create ".$this->name);
 
         // Check parameters
@@ -845,7 +845,7 @@ class Societe extends CommonObject
             $sql .= ",mode_reglement_supplier = ".(! empty($this->mode_reglement_supplier_id)?"'".$this->db->escape($this->mode_reglement_supplier_id)."'":"null");
             $sql .= ",cond_reglement_supplier = ".(! empty($this->cond_reglement_supplier_id)?"'".$this->db->escape($this->cond_reglement_supplier_id)."'":"null");
             $sql .= ",fk_shipping_method = ".(! empty($this->shipping_method_id)?"'".$this->db->escape($this->shipping_method_id)."'":"null");
-            
+
             $sql .= ",client = " . (! empty($this->client)?$this->client:0);
             $sql .= ",fournisseur = " . (! empty($this->fournisseur)?$this->fournisseur:0);
             $sql .= ",barcode = ".(! empty($this->barcode)?"'".$this->db->escape($this->barcode)."'":"null");
@@ -1055,7 +1055,7 @@ class Societe extends CommonObject
         else if ($idprof4) $sql .= " WHERE s.idprof4 = '".$this->db->escape($idprof4)."' AND s.entity IN (".getEntity($this->element, 1).")";
         else if ($idprof5) $sql .= " WHERE s.idprof5 = '".$this->db->escape($idprof5)."' AND s.entity IN (".getEntity($this->element, 1).")";
         else if ($idprof6) $sql .= " WHERE s.idprof6 = '".$this->db->escape($idprof6)."' AND s.entity IN (".getEntity($this->element, 1).")";
-        
+
         $resql=$this->db->query($sql);
         dol_syslog(get_class($this)."::fetch ".$sql);
         if ($resql)
@@ -1900,10 +1900,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"';
@@ -2733,7 +2733,7 @@ class Societe extends CommonObject
 
         $url='';
         $action = '';
-        
+
         $hookmanager->initHooks(array('idprofurl'));
         $parameters=array('idprof'=>$idprof, 'company'=>$thirdparty);
         $reshook=$hookmanager->executeHooks('getIdProfUrl',$parameters,$this,$action);    // Note that $action and $object may have been modified by some hooks
@@ -2745,14 +2745,14 @@ class Societe extends CommonObject
             if ($idprof == 1 && ($thirdparty->country_code == 'GB' || $thirdparty->country_code == 'UK')) $url='http://www.companieshouse.gov.uk/WebCHeck/findinfolink/';
             if ($idprof == 1 && $thirdparty->country_code == 'ES') $url='http://www.e-informa.es/servlet/app/portal/ENTP/screen/SProducto/prod/ETIQUETA_EMPRESA/nif/'.$thirdparty->idprof1;
             if ($idprof == 1 && $thirdparty->country_code == 'IN') $url='http://www.tinxsys.com/TinxsysInternetWeb/dealerControllerServlet?tinNumber='.$thirdparty->idprof1.';&searchBy=TIN&backPage=searchByTin_Inter.jsp';
-        
+
             if ($url) return '<a target="_blank" href="'.$url.'">'.$langs->trans("Check").'</a>';
         }
         else
         {
             return $hookmanager->resPrint;
         }
-        
+
         return '';
     }
 
@@ -3138,7 +3138,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).
      *
@@ -3367,7 +3367,7 @@ class Societe extends CommonObject
 
 	}
 
-	
+
 	/**
 	 *  Create a document onto disk according to template module.
 	 *
@@ -3402,8 +3402,8 @@ class Societe extends CommonObject
 
 		return $result;
 	}
-	
-	
+
+
 	/**
 	 * Sets object to supplied categories.
 	 *