From 215f397f33a6e279e0f6d8dc39ab80d5eff74e64 Mon Sep 17 00:00:00 2001
From: florian HENRY <florian.henry@atm-consulting.fr>
Date: Thu, 30 Jun 2016 17:28:13 +0200
Subject: [PATCH] Cannot reproduce 4793 still fix other bug on PgSQL

---
 htdocs/compta/facture/class/facture.class.php | 140 +++++++++--------
 htdocs/core/class/commonobject.class.php      | 146 +++++++++---------
 .../mysql/data/llx_accounting_category.sql    |   2 +-
 htdocs/install/pgsql/functions/functions.sql  |   4 -
 4 files changed, 146 insertions(+), 146 deletions(-)

diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index aa51c63374d..73127f9a1f2 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -108,7 +108,7 @@ class Facture extends CommonInvoice
 	var $specimen;
 
 	var $fac_rec;
-	
+
 	// Multicurrency
 	var $fk_multicurrency;
 	var $multicurrency_code;
@@ -136,7 +136,7 @@ class Facture extends CommonInvoice
 	 * @var array Table of previous situations
 	 */
 	public $tab_previous_situation_invoice=array();
-	
+
 	/**
 	 * @var array Table of next situations
 	 */
@@ -249,7 +249,7 @@ class Facture extends CommonInvoice
 			$this->fk_multicurrency = 0;
 			$this->multicurrency_tx = 1;
 		}
-		
+
 		dol_syslog(get_class($this)."::create user=".$user->id);
 
 		// Check parameters
@@ -280,7 +280,7 @@ class Facture extends CommonInvoice
 			$result=$_facrec->fetch($this->fac_rec);
 
 			$this->socid 		     = $_facrec->socid;
-			
+
 			// Fields coming from GUI (priority on template). TODO Value of template should be used as default value on GUI so we can use here always value from GUI
 			$this->fk_project        = GETPOST('projectid','int') > 0 ? GETPOST('projectid','int') : $_facrec->fk_project;
 			$this->note_public       = GETPOST('note_public') ? GETPOST('note_public') : $_facrec->note_public;
@@ -289,7 +289,7 @@ class Facture extends CommonInvoice
 			$this->cond_reglement_id = GETPOST('cond_reglement_id') > 0 ? GETPOST('cond_reglement_id') : $_facrec->cond_reglement_id;
 			$this->mode_reglement_id = GETPOST('mode_reglement_id') > 0 ? GETPOST('mode_reglement_id') : $_facrec->mode_reglement_id;
 			$this->fk_account        = GETPOST('fk_account') > 0 ? GETPOST('fk_account') : $_facrec->fk_account;
-				
+
 			// Fields always coming from template
 			$this->remise_absolue    = $_facrec->remise_absolue;
 			$this->remise_percent    = $_facrec->remise_percent;
@@ -302,13 +302,13 @@ class Facture extends CommonInvoice
 			$this->note_public=trim($this->note_public);
 			$this->note_private=trim($this->note_private);
 		    $this->note_private=dol_concatdesc($this->note_private, $langs->trans("GeneratedFromRecurringInvoice", $_facrec->ref));
-		    
+
 			//if (! $this->remise) $this->remise = 0;
 			if (! $this->mode_reglement_id) $this->mode_reglement_id = 0;
 			$this->brouillon = 1;
-		
+
 			$forceduedate = $this->calculate_date_lim_reglement();
-			
+
 			// For recurrn invoices, update date and number of last generation of recurring template invoice, before inserting new invoice
 			if ($_facrec->frequency > 0)
 			{
@@ -658,7 +658,7 @@ class Facture extends CommonInvoice
 	function createFromCurrent($user,$invertdetail=0)
 	{
 		global $conf;
-		
+
 		// Charge facture source
 		$facture=new Facture($this->db);
 
@@ -712,15 +712,15 @@ class Facture extends CommonInvoice
 		elseif ($this->type == self::TYPE_SITUATION && !empty($conf->global->INVOICE_USE_SITUATION))
 		{
 			$this->fetchObjectLinked('', '', $object->id, 'facture');
-			
-			foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object) 
+
+			foreach ($this->linkedObjectsIds as $typeObject => $Tfk_object)
 			{
-				foreach ($Tfk_object as $fk_object)     
+				foreach ($Tfk_object as $fk_object)
 				{
 					$facture->add_object_linked($typeObject, $fk_object);
 				}
 			}
-			
+
 			$facture->add_object_linked('facture', $this->fk_facture_source);
 		}
 
@@ -1107,7 +1107,7 @@ class Facture extends CommonInvoice
 				$this->multicurrency_total_ht 	= $obj->multicurrency_total_ht;
 				$this->multicurrency_total_tva 	= $obj->multicurrency_total_tva;
 				$this->multicurrency_total_ttc 	= $obj->multicurrency_total_ttc;
-				
+
 				if ($this->type == self::TYPE_SITUATION && $fetch_situation)
 				{
 					$this->fetchPreviousNextSituationInvoice();
@@ -1229,7 +1229,7 @@ class Facture extends CommonInvoice
 				$line->situation_percent= $objp->situation_percent;
 				$line->fk_prev_id       = $objp->fk_prev_id;
 				$line->fk_unit	        = $objp->fk_unit;
-				
+
 				// Multicurrency
 				$line->fk_multicurrency 		= $objp->fk_multicurrency;
 				$line->multicurrency_code 		= $objp->multicurrency_code;
@@ -1237,7 +1237,7 @@ class Facture extends CommonInvoice
 				$line->multicurrency_total_ht 	= $objp->multicurrency_total_ht;
 				$line->multicurrency_total_tva 	= $objp->multicurrency_total_tva;
 				$line->multicurrency_total_ttc 	= $objp->multicurrency_total_ttc;
-				
+
 				$this->lines[$i] = $line;
 
 				$i++;
@@ -1255,17 +1255,17 @@ class Facture extends CommonInvoice
 	/**
 	 * Fetch previous and next situations invoices
 	 *
-	 * @return	void 
+	 * @return	void
 	 */
 	function fetchPreviousNextSituationInvoice()
 	{
 		global $conf;
-		
+
 		$this->tab_previous_situation_invoice = array();
 		$this->tab_next_situation_invoice = array();
-		
+
 		$sql = 'SELECT rowid, situation_counter FROM '.MAIN_DB_PREFIX.'facture WHERE rowid <> '.$this->id.' AND entity = '.$conf->entity.' AND situation_cycle_ref = '.(int) $this->situation_cycle_ref.' ORDER BY situation_counter ASC';
-		
+
 		dol_syslog(get_class($this).'::fetchPreviousNextSituationInvoice ', LOG_DEBUG);
 		$result = $this->db->query($sql);
 		if ($result && $this->db->num_rows($result) > 0)
@@ -1274,13 +1274,13 @@ class Facture extends CommonInvoice
 			{
 				$invoice = new Facture($this->db);
 				if ($invoice->fetch($objp->rowid) > 0)
-				{                                       
+				{
 					if ($objp->situation_counter < $this->situation_counter) $this->tab_previous_situation_invoice[] = $invoice;
 					else $this->tab_next_situation_invoice[] = $invoice;
 				}
 			}
 		}
-	
+
 	}
 
 	/**
@@ -2061,7 +2061,7 @@ class Facture extends CommonInvoice
 				$this->brouillon=0;
 				$this->date_validation=$now;
 				$i = 0;
-				
+
                 if (!empty($conf->global->INVOICE_USE_SITUATION))
                 {
     				$final = True;
@@ -2094,7 +2094,7 @@ class Facture extends CommonInvoice
 
 	/**
 	 * Update price of next invoice
-	 * 
+	 *
 	 * @param	Translate	$langs	Translate object
 	 * @return bool		false if KO, true if OK
 	 */
@@ -2103,13 +2103,13 @@ class Facture extends CommonInvoice
 		foreach ($this->tab_next_situation_invoice as $next_invoice)
 		{
 			$is_last = $next_invoice->is_last_in_cycle();
-			
-			if ($next_invoice->brouillon && $is_last != 1) 
+
+			if ($next_invoice->brouillon && $is_last != 1)
 			{
 				$this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
 				return false;
 			}
-			
+
 			$next_invoice->brouillon = 1;
 			foreach ($next_invoice->lines as $line)
 			{
@@ -2117,17 +2117,17 @@ class Facture extends CommonInvoice
 														$line->date_start, $line->date_end, $line->tva_tx, $line->localtax1_tx, $line->localtax2_tx, 'HT', $line->info_bits, $line->product_type,
 														$line->fk_parent_line, 0, $line->fk_fournprice, $line->pa_ht, $line->label, $line->special_code, $line->array_options, $line->situation_percent,
 														$line->fk_unit);
-				
-				if ($result < 0) 
+
+				if ($result < 0)
 				{
 					$this->error = $langs->trans('updatePriceNextInvoiceErrorUpdateline', $next_invoice->ref);
 					return false;
 				}
 			}
-			
+
 			break; // Only the next invoice and not each next invoice
 		}
-		
+
 		return true;
 	}
 
@@ -2280,7 +2280,7 @@ class Facture extends CommonInvoice
 		if (empty($fk_parent_line) || $fk_parent_line < 0) $fk_parent_line=0;
 		if (empty($fk_prev_id)) $fk_prev_id = 'null';
 		if (! isset($situation_percent) || $situation_percent > 100 || (string) $situation_percent == '') $situation_percent = 100;
-		    
+
 		$remise_percent=price2num($remise_percent);
 		$qty=price2num($qty);
 		$pu_ht=price2num($pu_ht);
@@ -2342,7 +2342,7 @@ class Facture extends CommonInvoice
 			$multicurrency_total_ht  = $tabprice[16];
             $multicurrency_total_tva = $tabprice[17];
             $multicurrency_total_ttc = $tabprice[18];
-			
+
 			// Rank to use
 			$rangtouse = $rang;
 			if ($rangtouse == -1)
@@ -2355,14 +2355,14 @@ class Facture extends CommonInvoice
 			$this->line=new FactureLigne($this->db);
 
 			$this->line->context = $this->context;
-			
+
 			$this->line->fk_facture=$this->id;
 			$this->line->label=$label;	// deprecated
 			$this->line->desc=$desc;
-			
+
 			$this->line->qty=            ($this->type==self::TYPE_CREDIT_NOTE?abs($qty):$qty);	    // For credit note, quantity is always positive and unit price negative
 			$this->line->subprice=       ($this->type==self::TYPE_CREDIT_NOTE?-abs($pu_ht):$pu_ht); // For credit note, unit price always negative, always positive otherwise
-					
+
 			$this->line->tva_tx=$txtva;
 			$this->line->localtax1_tx=$txlocaltax1;
 			$this->line->localtax2_tx=$txlocaltax2;
@@ -2374,7 +2374,7 @@ class Facture extends CommonInvoice
 			$this->line->total_tva=      (($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_tva):$total_tva);  // For credit note and if qty is negative, total is negative
 			$this->line->total_localtax1=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax1):$total_localtax1);  // For credit note and if qty is negative, total is negative
 			$this->line->total_localtax2=(($this->type==self::TYPE_CREDIT_NOTE||$qty<0)?-abs($total_localtax2):$total_localtax2);  // For credit note and if qty is negative, total is negative
-			
+
 			$this->line->fk_product=$fk_product;
 			$this->line->product_type=$product_type;
 			$this->line->remise_percent=$remise_percent;
@@ -2384,7 +2384,7 @@ class Facture extends CommonInvoice
 			$this->line->rang=$rangtouse;
 			$this->line->info_bits=$info_bits;
 			$this->line->fk_remise_except=$fk_remise_except;
-			
+
 			$this->line->special_code=$special_code;
 			$this->line->fk_parent_line=$fk_parent_line;
 			$this->line->origin=$origin;
@@ -2396,7 +2396,7 @@ class Facture extends CommonInvoice
 			// infos marge
 			$this->line->fk_fournprice = $fk_fournprice;
 			$this->line->pa_ht = $pa_ht;
-			
+
 			// Multicurrency
 			$this->line->fk_multicurrency			= $this->fk_multicurrency;
 			$this->line->multicurrency_code			= $this->multicurrency_code;
@@ -2404,7 +2404,7 @@ class Facture extends CommonInvoice
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
-			
+
 			if (is_array($array_options) && count($array_options)>0) {
 				$this->line->array_options=$array_options;
 			}
@@ -2489,7 +2489,7 @@ class Facture extends CommonInvoice
 					return -3;
 				}
 			}
-			
+
 			$this->db->begin();
 
 			// Clean parameters
@@ -2515,7 +2515,7 @@ class Facture extends CommonInvoice
 
 			$localtaxes_type=getLocalTaxesFromRate($txtva,0,$this->thirdparty, $mysoc);
 			$txtva = preg_replace('/\s*\(.*\)/','',$txtva);  // Remove code into vatrate.
-					
+
 			$tabprice=calcul_price_total($qty, $pu, $remise_percent, $txtva, $txlocaltax1, $txlocaltax2, 0, $price_base_type, $info_bits, $type, $mysoc, $localtaxes_type, $situation_percent, $this->multicurrency_tx);
 
 			$total_ht  = $tabprice[0];
@@ -2531,7 +2531,7 @@ class Facture extends CommonInvoice
 			$multicurrency_total_ht  = $tabprice[16];
             $multicurrency_total_tva = $tabprice[17];
             $multicurrency_total_ttc = $tabprice[18];
-			
+
 			// Old properties: $price, $remise (deprecated)
 			$price = $pu;
 			$remise = 0;
@@ -2607,7 +2607,7 @@ class Facture extends CommonInvoice
 			$this->line->multicurrency_total_ht 	= $multicurrency_total_ht;
             $this->line->multicurrency_total_tva 	= $multicurrency_total_tva;
             $this->line->multicurrency_total_ttc 	= $multicurrency_total_ttc;
-			
+
 			if (is_array($array_options) && count($array_options)>0) {
 				$this->line->array_options=$array_options;
 			}
@@ -2638,28 +2638,28 @@ class Facture extends CommonInvoice
 	}
 
 	/**
-	 * Check if the percent edited is lower of next invoice line 
-	 * 
+	 * Check if the percent edited is lower of next invoice line
+	 *
 	 * @param	int		$idline				id of line to check
 	 * @param	float	$situation_percent	progress percentage need to be test
 	 * @return false if KO, true if OK
 	 */
 	function checkProgressLine($idline, $situation_percent)
 	{
-		$sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd 
-				INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid) 
-				WHERE fd.fk_prev_id = '.$idline.' 
+		$sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd
+				INNER JOIN '.MAIN_DB_PREFIX.'facture f ON (fd.fk_facture = f.rowid)
+				WHERE fd.fk_prev_id = '.$idline.'
 				AND f.fk_statut <> 0';
-		
+
 		$result = $this->db->query($sql);
 		if (! $result)
 		{
 			$this->error=$this->db->error();
 			return false;
 		}
-		
+
 		$obj = $this->db->fetch_object($result);
-		
+
 		if ($obj === null) return true;
 		else return $situation_percent < $obj->situation_percent;
 	}
@@ -2674,7 +2674,7 @@ class Facture extends CommonInvoice
 	function update_percent($line, $percent)
 	{
 	    global $mysoc,$user;
-	    
+
 		include_once(DOL_DOCUMENT_ROOT . '/core/lib/price.lib.php');
 
 		// Cap percentages to 100
@@ -3555,6 +3555,10 @@ class Facture extends CommonInvoice
 				$prodids[$i] = $row[0];
 			}
 		}
+		//Avoid php warning Warning: mt_rand(): max(0) is smaller than min(1) when no product exists
+		if (empty($num_prods)) {
+			$num_prods=1;
+		}
 
 		// Initialize parameters
 		$this->id=0;
@@ -3788,7 +3792,7 @@ class Facture extends CommonInvoice
 	function get_prev_sits()
 	{
 		global $conf;
-		
+
 		$sql = 'SELECT rowid FROM ' . MAIN_DB_PREFIX . 'facture';
 		$sql .= ' where situation_cycle_ref = ' . $this->situation_cycle_ref;
 		$sql .= ' and situation_counter < ' . $this->situation_counter;
@@ -3818,9 +3822,9 @@ class Facture extends CommonInvoice
 	 */
 	function setFinal()
 	{
-		
+
         $this->db->begin();
-        
+
 		$this->situation_final = 1;
 		$sql = 'update ' . MAIN_DB_PREFIX . 'facture set situation_final = ' . $this->situation_final . ' where rowid = ' . $this->id;
 		$resql = $this->db->query($sql);
@@ -3845,12 +3849,12 @@ class Facture extends CommonInvoice
 	function is_last_in_cycle()
 	{
 		global $conf;
-		
+
 		if (!empty($this->situation_cycle_ref)) {
 			// No point in testing anything if we're not inside a cycle
 			$sql = 'SELECT max(situation_counter) FROM ' . MAIN_DB_PREFIX . 'facture WHERE situation_cycle_ref = ' . $this->situation_cycle_ref . ' AND entity = ' . ($this->entity > 0 ? $this->entity : $conf->entity);
 			$resql = $this->db->query($sql);
-	
+
 			if ($resql && $resql->num_rows > 0) {
 				$res = $this->db->fetch_array($resql);
 				$last = $res['max(situation_counter)'];
@@ -3895,7 +3899,7 @@ class Facture extends CommonInvoice
 
 		// Paid invoices have status STATUS_CLOSED
 		if ($this->statut != Facture::STATUS_VALIDATED) return false;
-		
+
 		return $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay);
 	}
 }
@@ -3984,7 +3988,7 @@ class FactureLigne extends CommonInvoiceLine
 	var $multicurrency_total_ht;
 	var $multicurrency_total_tva;
 	var $multicurrency_total_ttc;
-	
+
 	/**
 	 *	Load invoice line from database
 	 *
@@ -4074,7 +4078,7 @@ class FactureLigne extends CommonInvoiceLine
 		$error=0;
 
         $pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
-		
+
         dol_syslog(get_class($this)."::insert rang=".$this->rang, LOG_DEBUG);
 
 		// Clean parameters
@@ -4100,9 +4104,9 @@ class FactureLigne extends CommonInvoiceLine
 		if (empty($this->multicurrency_total_ht)) $this->multicurrency_total_ht=0;
 		if (empty($this->multicurrency_total_tva)) $this->multicurrency_total_tva=0;
 		if (empty($this->multicurrency_total_ttc)) $this->multicurrency_total_ttc=0;
-		
+
 		// if buy price not defined, define buyprice as configured in margin admin
-		if ($this->pa_ht == 0 && $pa_ht_isemptystring) 
+		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
 		{
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
 			{
@@ -4286,7 +4290,7 @@ class FactureLigne extends CommonInvoiceLine
 		$error=0;
 
 		$pa_ht_isemptystring = (empty($this->pa_ht) && $this->pa_ht == ''); // If true, we can use a default value. If this->pa_ht = '0', we must use '0'.
-		
+
 		// Clean parameters
 		$this->desc=trim($this->desc);
 		if (empty($this->tva_tx)) $this->tva_tx=0;
@@ -4308,7 +4312,7 @@ class FactureLigne extends CommonInvoiceLine
 		if ($this->product_type < 0) return -1;
 
 		// if buy price not defined, define buyprice as configured in margin admin
-		if ($this->pa_ht == 0 && $pa_ht_isemptystring) 
+		if ($this->pa_ht == 0 && $pa_ht_isemptystring)
 		{
 			if (($result = $this->defineBuyPrice($this->subprice, $this->remise_percent, $this->fk_product)) < 0)
 			{
@@ -4355,13 +4359,13 @@ class FactureLigne extends CommonInvoiceLine
 		if (! empty($this->rang)) $sql.= ", rang=".$this->rang;
 		$sql .= ", situation_percent=" . $this->situation_percent;
 		$sql .= ", fk_unit=".(!$this->fk_unit ? 'NULL' : $this->fk_unit);
-		
+
 		// Multicurrency
 		$sql.= " , multicurrency_subprice=".price2num($this->multicurrency_subprice)."";
         $sql.= " , multicurrency_total_ht=".price2num($this->multicurrency_total_ht)."";
         $sql.= " , multicurrency_total_tva=".price2num($this->multicurrency_total_tva)."";
         $sql.= " , multicurrency_total_ttc=".price2num($this->multicurrency_total_ttc)."";
-		
+
 		$sql.= " WHERE rowid = ".$this->rowid;
 
 		dol_syslog(get_class($this)."::update", LOG_DEBUG);
@@ -4477,7 +4481,7 @@ class FactureLigne extends CommonInvoiceLine
 
 	/**
 	 * Returns situation_percent of the previous line.
-	 * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line. 
+	 * Warning: If invoice is a replacement invoice, this->fk_prev_id is id of the replaced line.
 	 *
 	 * @param  int     $invoiceid      Invoice id
 	 * @return int                     >= 0
diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php
index 620047014d4..aa36fa74624 100644
--- a/htdocs/core/class/commonobject.class.php
+++ b/htdocs/core/class/commonobject.class.php
@@ -444,7 +444,7 @@ abstract class CommonObject
     	global $conf, $langs;
 
     	$countriesusingstate=array('AU','US','IN','GB','ES','UK','TR');    // See also option MAIN_FORCE_STATE_INTO_ADDRESS
-    	
+
     	$contactid=0;
     	$thirdpartyid=0;
     	if ($this->element == 'societe')
@@ -461,12 +461,12 @@ abstract class CommonObject
     		$contactid=$this->contact_id;
 			$thirdpartyid=$object->fk_soc;
     	}
-    	
+
 		$out='<!-- BEGIN part to show address block -->';
-		
+
 		$outdone=0;
 		$coords = $this->getFullAddress(1,', ');
-		if ($coords) 
+		if ($coords)
 		{
 			if (! empty($conf->use_javascript_ajax))
 			{
@@ -481,7 +481,7 @@ abstract class CommonObject
 		}
 
 		if (! in_array($this->country_code,$countriesusingstate) && empty($conf->global->MAIN_FORCE_STATE_INTO_ADDRESS)   // If MAIN_FORCE_STATE_INTO_ADDRESS is on, state is already returned previously with getFullAddress
-				&& empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state) 
+				&& empty($conf->global->SOCIETE_DISABLE_STATE) && $this->state)
 		{
 			$out.=($outdone?' - ':'').$this->state;
 			$outdone++;
@@ -512,15 +512,15 @@ abstract class CommonObject
 		if (! empty($this->office_fax)) {
 			$out.=dol_print_phone($this->fax,$this->country_code,$contactid,$thirdpartyid,'AC_FAX','&nbsp;','fax',$langs->trans("Fax")); $outdone++;
 		}
-		
+
 		$out.='<div style="clear: both;"></div>';
 		$outdone=0;
-		if (! empty($this->email)) 
+		if (! empty($this->email))
 		{
 			$out.=dol_print_email($this->email,$this->id,$object->id,'AC_EMAIL',0,0,1);
 			$outdone++;
 		}
-    	if (! empty($this->url)) 
+    	if (! empty($this->url))
 		{
 			$out.=dol_print_url($this->url,'',0,1);
 			$outdone++;
@@ -531,12 +531,12 @@ abstract class CommonObject
 			if ($this->skype) $out.=dol_print_skype($this->skype,$this->id,$object->id,'AC_SKYPE');
 			$outdone++;
 		}
-		
+
 		$out.='<!-- END Part to show address block -->';
-		
+
 		return $out;
     }
-        
+
     /**
      *  Add a link between element $this->element and a contact
      *
@@ -592,7 +592,7 @@ abstract class CommonObject
         }
 
         $datecreate = dol_now();
-        
+
         $this->db->begin();
 
         // Insertion dans la base
@@ -610,9 +610,9 @@ abstract class CommonObject
             if (! $notrigger)
             {
             	$result=$this->call_trigger(strtoupper($this->element).'_ADD_CONTACT', $user);
-	            if ($result < 0) 
-	            { 
-	                $this->db->rollback(); 
+	            if ($result < 0)
+	            {
+	                $this->db->rollback();
 	                return -1;
 	            }
             }
@@ -883,9 +883,9 @@ abstract class CommonObject
 
         if (empty($order)) $order='position';
         if ($order == 'position') $order.=',code';
-        
+
         $tab = array();
-        $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle";
+        $sql = "SELECT DISTINCT tc.rowid, tc.code, tc.libelle, tc.position";
         $sql.= " FROM ".MAIN_DB_PREFIX."c_type_contact as tc";
         $sql.= " WHERE tc.element='".$this->element."'";
         if ($activeonly == 1) $sql.= " AND tc.active=1"; // only the active types
@@ -1196,7 +1196,7 @@ abstract class CommonObject
 		if (!empty($id) && !empty($field) && !empty($table)) {
 	        $sql = "SELECT ".$field." FROM ".MAIN_DB_PREFIX.$table;
 	        $sql.= " WHERE rowid = ".$id;
-	
+
 	        dol_syslog(get_class($this).'::getValueFrom', LOG_DEBUG);
 	        $resql = $this->db->query($sql);
 	        if ($resql)
@@ -1428,7 +1428,7 @@ abstract class CommonObject
     	if ($this->statut >= 0 || $this->element == 'societe')
     	{
     		$fieldname = 'multicurrency_code';
-			
+
     		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
     		$sql .= ' SET '.$fieldname.' = "'.$this->db->escape($code).'"';
     		$sql .= ' WHERE rowid='.$this->id;
@@ -1436,10 +1436,10 @@ abstract class CommonObject
     		if ($this->db->query($sql))
     		{
     			$this->multicurrency_code = $code;
-				
+
 				list($fk_multicurrency, $rate) = MultiCurrency::getIdAndTxFromCode($this->db, $code);
 				if ($rate) $this->setMulticurrencyRate($rate);
-				
+
     			return 1;
     		}
     		else
@@ -1456,7 +1456,7 @@ abstract class CommonObject
     		return -2;
     	}
     }
-	
+
 	/**
      *  Change the multicurrency rate
      *
@@ -1469,7 +1469,7 @@ abstract class CommonObject
     	if ($this->statut >= 0 || $this->element == 'societe')
     	{
     		$fieldname = 'multicurrency_tx';
-			
+
     		$sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
     		$sql .= ' SET '.$fieldname.' = '.$rate;
     		$sql .= ' WHERE rowid='.$this->id;
@@ -1477,11 +1477,11 @@ abstract class CommonObject
     		if ($this->db->query($sql))
     		{
     			$this->multicurrency_tx = $rate;
-				
+
 				// Update line price
 				if (!empty($this->lines))
 				{
-					foreach ($this->lines as &$line) 
+					foreach ($this->lines as &$line)
 					{
 						switch ($this->element) {
 							case 'propal':
@@ -1503,10 +1503,10 @@ abstract class CommonObject
 								dol_syslog(get_class($this).'::setMulticurrencyRate no updateline defined', LOG_DEBUG);
 								break;
 						}
-						
+
 					}
 				}
-				
+
     			return 1;
     		}
     		else
@@ -2244,7 +2244,7 @@ abstract class CommonObject
                 $this->total_localtax1 += $obj->total_localtax1;
                 $this->total_localtax2 += $obj->total_localtax2;
                 $this->total_ttc       += $obj->total_ttc;
-                
+
                 if (! isset($total_ht_by_vats[$obj->vatrate]))  $total_ht_by_vats[$obj->vatrate]=0;
                 if (! isset($total_tva_by_vats[$obj->vatrate])) $total_tva_by_vats[$obj->vatrate]=0;
                 if (! isset($total_ttc_by_vats[$obj->vatrate])) $total_ttc_by_vats[$obj->vatrate]=0;
@@ -2290,12 +2290,12 @@ abstract class CommonObject
 					$this->total_ttc -= $sit->total_ttc;
 				}
 			}
-			
+
 			// Multicurrency
 			$this->multicurrency_total_ht	+= $this->total_ht * $multicurrency_tx;
             $this->multicurrency_total_tva	+= $this->total_tva * $multicurrency_tx;
             $this->multicurrency_total_ttc	+= $this->total_ttc * $multicurrency_tx;
-			
+
             $this->db->free($resql);
 
             // Now update global field total_ht, total_ttc and tva
@@ -2398,8 +2398,8 @@ abstract class CommonObject
      *  - all parameters empty -> we look all link to current object (current object can be source or target)
      *  - one couple id+type is provided -> this will set $justsource or $justtarget
      *  - one couple id+type is provided and other type is provided -> this will set $justsource or $justtarget + criteria on other type
-     *  
-     *  
+     *
+     *
      *	@param	int		$sourceid		Object source id (if not defined, id of object)
      *	@param  string	$sourcetype		Object source type (if not defined, element name of object)
      *	@param  int		$targetid		Object target id (if not defined, id of object)
@@ -2508,7 +2508,7 @@ abstract class CommonObject
                 {
                     // Parse element/subelement (ex: project_task)
                     $module = $element = $subelement = $objecttype;
-                    if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier' 
+                    if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
                         && preg_match('/^([^_]+)_([^_]+)/i',$objecttype,$regs))
                     {
                         $module = $element = $regs[1];
@@ -2544,10 +2544,10 @@ abstract class CommonObject
                     else if ($objecttype == 'subscription')			{
                         $classpath = 'adherents/class'; $module = 'adherent';
                     }
-                    
+
                     // Set classfile
                     $classfile = strtolower($subelement); $classname = ucfirst($subelement);
-                    
+
                     if ($objecttype == 'invoice_supplier') {
                         $classfile = 'fournisseur.facture'; $classname = 'FactureFournisseur';
                     }
@@ -2563,7 +2563,7 @@ abstract class CommonObject
                     else if ($objecttype == 'subscription')   {
                         $classfile = 'cotisation'; $classname = 'Cotisation';
                     }
-                    
+
                     // Here $module, $classfile and $classname are set
                     if ($conf->$module->enabled && (($element != $this->element) || $alsosametype))
                     {
@@ -2936,7 +2936,7 @@ abstract class CommonObject
         return price2num($total_discount);
     }
 
-    
+
     /**
      * Return into unit=0, the calculated total of weight and volume of all lines * qty
      * Calculate by adding weight and volume of each product line, so properties ->volume/volume_units/weight/weight_units must be loaded on line.
@@ -2951,13 +2951,13 @@ abstract class CommonObject
         $totalVolume = '';
         $totalOrdered = '';     // defined for shipment only
         $totalToShip = '';      // defined for shipment only
-        
+
         foreach ($this->lines as $line)
         {
-        
+
             $totalOrdered+=$line->qty_asked;    // defined for shipment only
             $totalToShip+=$line->qty_shipped;   // defined for shipment only
-            
+
             // Define qty, weight, volume, weight_units, volume_units
             if ($this->element == 'shipping') $qty=$line->qty_shipped;     // for shipments
             else $qty=$line->qty;
@@ -2965,12 +2965,12 @@ abstract class CommonObject
             $volume=$line->volume;
             $weight_units=$line->weight_units;
             $volume_units=$line->volume_units;
-                        
+
             $weightUnit=0;
             $volumeUnit=0;
             if (! empty($weight_units)) $weightUnit = $weight_units;
             if (! empty($volume_units)) $volumeUnit = $volume_units;
-    
+
             //var_dump($line->volume_units);
             if ($weight_units < 50)   // >50 means a standard unit (power of 10 of official unit) > 50 means an exotic unit (like inch)
             {
@@ -2993,11 +2993,11 @@ abstract class CommonObject
                 $totalVolume += $volume * $qty;   // This may be wrong if we mix different units
             }
         }
-        
+
         return array('weight'=>$totalWeight, 'volume'=>$totalVolume, 'ordered'=>$totalOrdered, 'toship'=>$totalToShip);
-    }    
-    
-    
+    }
+
+
     /**
      *	Set extra parameters
      *
@@ -3267,7 +3267,7 @@ abstract class CommonObject
 
 		// Multicurrency
 		if (!empty($conf->multicurrency->enabled)) print '<td class="linecoluht_currency" align="right" width="80">'.$langs->trans('PriceUHTCurrency').'</td>';
-		
+
 		if ($inputalsopricewithtax) print '<td align="right" width="80">'.$langs->trans('PriceUTTC').'</td>';
 
 		// Qty
@@ -3430,7 +3430,7 @@ abstract class CommonObject
 				$text.= ' - '.(! empty($line->label)?$line->label:$label);
 				$description.=(! empty($conf->global->PRODUIT_DESC_IN_FORM)?'':dol_htmlentitiesbr($line->description));	// Description is what to show on popup. We shown nothing if already into desc.
 			}
-			
+
 			$line->pu_ttc = price2num($line->subprice * (1 + ($line->tva_tx/100)), 'MU');
 
 			// Output template part (modules that overwrite templates must declare this into descriptor)
@@ -3871,7 +3871,7 @@ abstract class CommonObject
                     return -1;
                 }
             }
-    
+
 			// We save charset_output to restore it because write_file can change it if needed for
 			// output format that does not support UTF8.
 			$sav_charset_output=$outputlangs->charset_output;
@@ -3935,13 +3935,13 @@ abstract class CommonObject
     /* For default values */
 
     /**
-     * Return the default value to use for a field when showing the create form of object. 
+     * Return the default value to use for a field when showing the create form of object.
      * Return values in this order:
      * 1) If parameter is available into POST, we return it first.
      * 2) If not but an alternate value was provided as parameter of function, we return it.
-     * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table). 
+     * 3) If not but a constant $conf->global->OBJECTELEMENT_FIELDNAME is set, we return it (It is better to use the dedicated table).
      * 4) Return value found into database (TODO No yet implemented)
-     * 
+     *
      * @param   string              $fieldname          Name of field
      * @param   string              $alternatevalue     Alternate value to use
      * @return  string|string[]                         Default value (can be an array if the GETPOST return an array)
@@ -3952,27 +3952,27 @@ abstract class CommonObject
 
         // If param here has been posted, we use this value first.
         if (isset($_POST[$fieldname])) return GETPOST($fieldname, 2);
-        
+
         if (isset($alternatevalue)) return $alternatevalue;
-        
+
         $newelement=$this->element;
         if ($newelement == 'facture') $newelement='invoice';
         if ($newelement == 'commande') $newelement='order';
-        if (empty($newelement)) 
+        if (empty($newelement))
         {
             dol_syslog("Ask a default value using common method getDefaultCreateValueForField on an object with no property ->element defined. Return empty string.", LOG_WARNING);
             return '';
         }
-        
+
         $keyforfieldname=strtoupper($newelement.'_DEFAULT_'.$fieldname);
         //var_dump($keyforfieldname);
         if (isset($conf->global->$keyforfieldname)) return $conf->global->$keyforfieldname;
-        
-        // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname 
-        
+
+        // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname
+
     }
-	
-    
+
+
 	/* For triggers */
 
 
@@ -3989,7 +3989,7 @@ abstract class CommonObject
     function call_trigger($trigger_name, $user)
     {
     	global $langs,$conf;
-    	
+
     	include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
     	$interface=new Interfaces($this->db);
     	$result=$interface->run_triggers($trigger_name,$this,$user,$langs,$conf);
@@ -4171,7 +4171,7 @@ abstract class CommonObject
     						{
     							$res=$object->fetch(0,$value);
     							if ($res > 0) $this->array_options[$key]=$object->id;
-    							else 
+    							else
     							{
     							    $this->error="Ref '".$value."' for object '".$object->element."' not found";
                                     $this->db->rollback();
@@ -4235,7 +4235,7 @@ abstract class CommonObject
         }
         else return 0;
     }
-    
+
     /**
      *	Update an exta field value for the current object.
      *  Data to describe values to insert/update are stored into $this->array_options=array('options_codeforfield1'=>'valueforfield1', 'options_codeforfield2'=>'valueforfield2', ...)
@@ -4300,7 +4300,7 @@ abstract class CommonObject
                     }
                     break;
             }
-            
+
             $this->db->begin();
             $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element."_extrafields SET ".$key."='".$this->db->escape($this->array_options["options_".$key])."'";
             $sql .= " WHERE fk_object = ".$this->id;
@@ -4478,7 +4478,7 @@ abstract class CommonObject
 	 * @param  int 		   $origin_id     Old thirdparty id (the thirdparty to delete)
 	 * @param  int 		   $dest_id       New thirdparty id (the thirdparty that will received element of the other)
 	 * @param  string[]    $tables        Tables that need to be changed
-	 * @param  int         $ignoreerrors  Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old thirdparty may already exists on new one) 
+	 * @param  int         $ignoreerrors  Ignore errors. Return true even if errors. We need this when replacement can fails like for categories (categorie of old thirdparty may already exists on new one)
 	 * @return bool
 	 */
 	public static function commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
@@ -4487,7 +4487,7 @@ abstract class CommonObject
 		{
 			$sql = 'UPDATE '.MAIN_DB_PREFIX.$table.' SET fk_soc = '.$dest_id.' WHERE fk_soc = '.$origin_id;
 
-			if (! $db->query($sql)) 
+			if (! $db->query($sql))
 			{
 			    if ($ignoreerrors) return true;
 				//$this->errors = $db->lasterror();
@@ -4497,26 +4497,26 @@ abstract class CommonObject
 
 		return true;
 	}
-	
+
 	/**
 	 * Get buy price to use for margin calculation. This function is called when buy price is unknown.
 	 *	set buy price = sell price if ForceBuyingPriceIfNull configured,
 	 *   else if calculation MARGIN_TYPE = 'costprice' and costprice is defined, use costprice as buyprice
 	 *	 else if calculation MARGIN_TYPE = 'pmp' and pmp is calculated, use pmp as buyprice
 	 *	 else set min buy price as buy price
-	 *	 
+	 *
 	 * @param float		$unitPrice		 product unit price
 	 * @param float		$discountPercent line discount percent
 	 * @param int		$fk_product		 product id
 	 *
 	 * @return	float <0 if ko, buyprice if ok
 	 */
-	public function defineBuyPrice($unitPrice = 0, $discountPercent = 0, $fk_product = 0) 
+	public function defineBuyPrice($unitPrice = 0, $discountPercent = 0, $fk_product = 0)
 	{
 		global $conf;
-	
+
 		$buyPrice = 0;
-		
+
 		if (($unitPrice > 0) && (isset($conf->global->ForceBuyingPriceIfNull) && $conf->global->ForceBuyingPriceIfNull == 1)) // In most cases, test here is false
 		{
 			$buyPrice = $unitPrice * (1 - $discountPercent / 100);
@@ -4560,7 +4560,7 @@ abstract class CommonObject
 						$buyPrice = $product->pmp;
 					}
 				}
-				
+
 				if (empty($buyPrice) && isset($conf->global->MARGIN_TYPE) && in_array($conf->global->MARGIN_TYPE, array('1','pmp','costprice')))
 				{
 					require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
diff --git a/htdocs/install/mysql/data/llx_accounting_category.sql b/htdocs/install/mysql/data/llx_accounting_category.sql
index 5769d291563..8e69ca6331e 100644
--- a/htdocs/install/mysql/data/llx_accounting_category.sql
+++ b/htdocs/install/mysql/data/llx_accounting_category.sql
@@ -25,5 +25,5 @@
 --
 
 INSERT INTO llx_c_accounting_category (rowid, code, label, range_account, sens, category_type, formula, position, fk_country, active) VALUES (  1,'VTE','Ventes de marchandises', '707xxx', 0, 0, '', '10', 1, 1);
-INSERT INTO llx_c_accounting_category (rowid, code, label, range_account, sens, category_type, formula, position, fk_country, active) VALUES (  2,'MAR','Coût d\'achats marchandises vendues', '603xxx | 607xxx | 609xxx', 0, 0, '', '20', 1, 1);
+INSERT INTO llx_c_accounting_category (rowid, code, label, range_account, sens, category_type, formula, position, fk_country, active) VALUES (  2,'MAR','Coût d achats marchandises vendues', '603xxx | 607xxx | 609xxx', 0, 0, '', '20', 1, 1);
 INSERT INTO llx_c_accounting_category (rowid, code, label, range_account, sens, category_type, formula, position, fk_country, active) VALUES (  3,'MARGE','Marge commerciale', '', 0, 1, '1 + 2', '30', 1, 1);
\ No newline at end of file
diff --git a/htdocs/install/pgsql/functions/functions.sql b/htdocs/install/pgsql/functions/functions.sql
index 307c88c3007..df0c64855b1 100644
--- a/htdocs/install/pgsql/functions/functions.sql
+++ b/htdocs/install/pgsql/functions/functions.sql
@@ -56,16 +56,12 @@ CREATE OR REPLACE FUNCTION dol_util_triggerall(DoEnable boolean) RETURNS integer
 CREATE OR REPLACE FUNCTION update_modified_column_tms()	RETURNS TRIGGER AS $$ BEGIN NEW.tms = now(); RETURN NEW; END; $$ LANGUAGE plpgsql;
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_accounting_account FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_accounting_fiscalyear FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
-CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_accountingtransaction FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_actioncomm FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_actioncomm_extrafields FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_adherent FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_adherent_extrafields FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_adherent_type FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_adherent_type_extrafields FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
-CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_askpricesupplier FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
-CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_askpricesupplier_extrafields FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
-CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_askpricesupplierdet_extrafields FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_bank FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_bank_account FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
 CREATE TRIGGER update_customer_modtime BEFORE UPDATE ON llx_bank_account_extrafields FOR EACH ROW EXECUTE PROCEDURE update_modified_column_tms();
-- 
GitLab