From 08725003b9cc772ad980acce59714d286d1de72c Mon Sep 17 00:00:00 2001
From: Regis Houssin <regis.houssin@capnetworks.com>
Date: Thu, 7 Jul 2016 12:43:02 +0200
Subject: [PATCH] Fix: add entity field in llx_societe_remise, useful when
 third-sharing is used with multicompany

---
 htdocs/comm/remise.php                        | 15 ++--
 .../install/mysql/migration/3.9.0-4.0.0.sql   |  2 +
 .../mysql/tables/llx_societe_remise.sql       | 17 ++--
 htdocs/install/upgrade2.php                   | 81 +++++++++++++++++++
 htdocs/langs/en_US/install.lang               |  1 +
 htdocs/societe/class/societe.class.php        | 29 ++++---
 6 files changed, 120 insertions(+), 25 deletions(-)

diff --git a/htdocs/comm/remise.php b/htdocs/comm/remise.php
index a5c0a89f29d..4ea377a4487 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/install/mysql/migration/3.9.0-4.0.0.sql b/htdocs/install/mysql/migration/3.9.0-4.0.0.sql
index 5e0555c92a7..a83c2e5c7f0 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,8 @@ 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 ADD COLUMN entity integer DEFAULT 1 NOT NULL AFTER rowid;
+
 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;
diff --git a/htdocs/install/mysql/tables/llx_societe_remise.sql b/htdocs/install/mysql/tables/llx_societe_remise.sql
index 14b4ea85639..a9d41fcd502 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/upgrade2.php b/htdocs/install/upgrade2.php
index f7871088c6b..fdd1781d293 100644
--- a/htdocs/install/upgrade2.php
+++ b/htdocs/install/upgrade2.php
@@ -402,6 +402,9 @@ if (! GETPOST("action") || preg_match('/upgrade/i',GETPOST('action')))
         $beforeversionarray=explode('.','4.0.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);
 
@@ -3661,6 +3664,84 @@ 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
  *
diff --git a/htdocs/langs/en_US/install.lang b/htdocs/langs/en_US/install.lang
index 3d56c38e584..30d94255bcc 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
+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
diff --git a/htdocs/societe/class/societe.class.php b/htdocs/societe/class/societe.class.php
index 69eaa28541f..ea5fc138eaf 100644
--- a/htdocs/societe/class/societe.class.php
+++ b/htdocs/societe/class/societe.class.php
@@ -1422,6 +1422,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)
             {
@@ -1533,7 +1545,7 @@ class Societe extends CommonObject
      */
     function set_remise_client($remise, $note, User $user)
     {
-        global $langs;
+        global $conf, $langs;
 
         // Nettoyage parametres
         $note=trim($note);
@@ -1565,8 +1577,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.= ")";
@@ -3478,13 +3490,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);
 
-- 
GitLab