From 87742cb3d8b539a6403d57dc6836afb05143a468 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Wed, 29 Aug 2012 14:13:13 +0200
Subject: [PATCH] Qual: Move an admin tools into admin menu. Fix: Fix 7 bugs
 into the mass vat update tool.

---
 htdocs/core/lib/product.lib.php         |  8 ---
 htdocs/core/menus/standard/eldy.lib.php | 12 +++-
 htdocs/langs/en_US/admin.lang           |  7 ++
 htdocs/langs/en_US/errors.lang          |  1 +
 htdocs/langs/en_US/main.lang            |  2 +
 htdocs/langs/fr_FR/admin.lang           |  7 ++
 htdocs/langs/fr_FR/errors.lang          |  1 +
 htdocs/langs/fr_FR/main.lang            |  2 +
 htdocs/product/admin/product_tools.php  | 95 ++++++++++++++-----------
 9 files changed, 84 insertions(+), 51 deletions(-)

diff --git a/htdocs/core/lib/product.lib.php b/htdocs/core/lib/product.lib.php
index eb2de353ca9..c78fb19af09 100644
--- a/htdocs/core/lib/product.lib.php
+++ b/htdocs/core/lib/product.lib.php
@@ -153,14 +153,6 @@ function product_admin_prepare_head($object=null)
 	$head[$h][2] = 'general';
 	$h++;
 
-	if ($conf->global->MAIN_FEATURES_LEVEL > 1)	// Link to page to make mass editing of products vat
-	{
-		$head[$h][0] = DOL_URL_ROOT.'/product/admin/product_tools.php';
-		$head[$h][1] = $langs->trans("Tools");
-		$head[$h][2] = 'tools';
-		$h++;
-	}
-
 	// Show more tabs from modules
 	// Entries must be declared in modules descriptor with line
 	// $this->tabs = array('entity:+tabname:Title:@mymodule:/mymodule/mypage.php?id=__ID__');   to add new tab
diff --git a/htdocs/core/menus/standard/eldy.lib.php b/htdocs/core/menus/standard/eldy.lib.php
index e0921df9638..14464ab77f9 100644
--- a/htdocs/core/menus/standard/eldy.lib.php
+++ b/htdocs/core/menus/standard/eldy.lib.php
@@ -702,7 +702,7 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after)
                     $newmenu->add('/admin/system/database-tables.php?mainmenu=home', $langs->trans('Tables'), 2);
                     $newmenu->add('/admin/system/database-tables-contraintes.php?mainmenu=home', $langs->trans('Constraints'), 2);
                 }
-                // System info
+                // Admin tools
                 $newmenu->add("/admin/tools/index.php?mainmenu=home&leftmenu=admintools", $langs->trans("SystemTools"), 0, 1, '', $mainmenu, 'admintools');
                 if ($leftmenu=="admintools")
                 {
@@ -715,6 +715,16 @@ function print_left_eldy_menu($db,$menu_array_before,$menu_array_after)
                     $newmenu->add("/admin/tools/purge.php?mainmenu=home", $langs->trans("Purge"),1);
                     $newmenu->add("/support/index.php?mainmenu=home", $langs->trans("HelpCenter"),1,1,'targethelp');
                 }
+				// Modules system tools
+                if (($conf->global->MAIN_FEATURES_LEVEL >= 1) && ! empty($conf->product->enabled) || ! empty($conf->service->enabled))
+	            {
+	            	$langs->load("products");
+	            	$newmenu->add("/admin/tools/index.php?mainmenu=home&leftmenu=modulesadmintools", $langs->trans("ModulesSystemTools"), 0, 1, '', $mainmenu, 'modulesadmintools');
+	            	if ($leftmenu=="modulesadmintools")
+	            	{
+	                	$newmenu->add("/product/admin/product_tools.php?mainmenu=home&leftmenu=modulesadmintools",$langs->trans("ProductVatMassChange"),1);
+	            	}
+	            }
             }
 
             $newmenu->add("/user/home.php?leftmenu=users", $langs->trans("MenuUsersAndGroups"), 0, 1, '', $mainmenu, 'users');
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index 53aa67bb881..c22863729bb 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -332,6 +332,13 @@ SecurityTokenIsUnique=Use a unique securekey parameter for each URL
 EnterRefToBuildUrl=Enter reference for object %s
 GetSecuredUrl=Get calculated URL
 ButtonHideUnauthorized=Hide buttons for unauthorized actions instead of showing disabled buttons
+ModulesSystemTools=Modules tools
+ProductVatMassChange=Mass VAT change
+ProductVatMassChangeDesc=This page can be used to modify a VAT rate defined on products or services from a value to another. Warning, this change is done on all database.
+OldVATRates=Old VAT rate
+NewVATRates=New VAT rate
+PriceBaseTypeToChange=Modify on prices with base reference value defined on
+MassConvert=Launch mass convert
 
 # Modules
 Module0Name=Users & groups
diff --git a/htdocs/langs/en_US/errors.lang b/htdocs/langs/en_US/errors.lang
index 6b9885eb4cb..a1f45f4ca1f 100644
--- a/htdocs/langs/en_US/errors.lang
+++ b/htdocs/langs/en_US/errors.lang
@@ -110,6 +110,7 @@ ErrorFileMustBeADolibarrPackage=The file %s must be a Dolibarr zip package
 ErrorFileRequired=It takes a package Dolibarr file
 ErrorPhpCurlNotInstalled=The PHP CURL is not installed, this is essential to talk with Paypal
 ErrorFailedToAddToMailmanList=Failed to add record to Mailman list or SPIP base
+ErrorNewVaueCantMatchOldValue=New value can't be equal to old one
 
 # Warnings
 WarningMandatorySetupNotComplete=Mandatory setup parameters are not yet defined
diff --git a/htdocs/langs/en_US/main.lang b/htdocs/langs/en_US/main.lang
index 3a40db19912..ff2318bc184 100644
--- a/htdocs/langs/en_US/main.lang
+++ b/htdocs/langs/en_US/main.lang
@@ -15,6 +15,7 @@ FormatDateHourTextShort=%b %d, %Y, %I:%M %p
 FormatDateHourText=%B %d, %Y, %I:%M %p
 DatabaseConnection=Database connection
 NoTranslation=No translation
+NoRecordFound=Aucun enregistrement trouvé
 NoError=No error
 Error=Error
 ErrorFieldRequired=Field '%s' is required
@@ -530,6 +531,7 @@ GoBack=Go back
 CanBeModifiedIfOk=Can be modified if valid
 CanBeModifiedIfKo=Can be modified if not valid
 RecordModifiedSuccessfully=Record modified successfully
+RecordsModified=%s records modified
 AutomaticCode=Automatic code
 NotManaged=Not managed
 FeatureDisabled=Feature disabled
diff --git a/htdocs/langs/fr_FR/admin.lang b/htdocs/langs/fr_FR/admin.lang
index 00c0082e1c7..4f7be5890d8 100644
--- a/htdocs/langs/fr_FR/admin.lang
+++ b/htdocs/langs/fr_FR/admin.lang
@@ -334,6 +334,13 @@ GetSecuredUrl=Obtenir l'URL calculée
 ButtonHideUnauthorized=Cacher les boutons non autorisés (au lieu de les voir grisés)
 TotalNumberOfActivatedModules=Nombre total de modules fonctionnels activés: <b>%s</b>
 YouMustEnableOneModule=Vous devez activer au moins une fonctionnalité
+ModulesSystemTools=Outils Modules
+ProductVatMassChange=Modif TVA en masse
+ProductVatMassChangeDesc=Cette page permet de modifier les taux de TVA définis sur les produits ou services d'une valeur vers une autre. Attention, la modification est réalisée en masse sur toute la base de donnée.
+OldVATRates=Ancien taux de TVA
+NewVATRates=Nouveau taux de TVA
+PriceBaseTypeToChange=Modifier sur les prix dont la référence de base est le
+MassConvert=Convertir en masse
 
 # Modules= undefined
 Module0Name= Utilisateurs & groupes
diff --git a/htdocs/langs/fr_FR/errors.lang b/htdocs/langs/fr_FR/errors.lang
index f14b4b22a30..6f4a790a6d6 100644
--- a/htdocs/langs/fr_FR/errors.lang
+++ b/htdocs/langs/fr_FR/errors.lang
@@ -111,6 +111,7 @@ ErrorFileMustBeADolibarrPackage=Le fichier doit être un package Dolibarr
 ErrorFileRequired=Il faut un fichier de package Dolibarr
 ErrorPhpCurlNotInstalled=L'extension PHP CURL n'est pas installée, ceci est indispensable pour dialoguer avec Paypal.
 ErrorFailedToAddToMailmanList=Echec de l'ajout à une liste Mailman ou base SPIP
+ErrorNewVaueCantMatchOldValue=La nouvelle valeur ne peut être égale à l'ancienne
 
 # Warnings
 WarningMandatorySetupNotComplete=Les informations de configuration obligatoire doivent être renseignées
diff --git a/htdocs/langs/fr_FR/main.lang b/htdocs/langs/fr_FR/main.lang
index 5236417cd85..198b7468028 100644
--- a/htdocs/langs/fr_FR/main.lang
+++ b/htdocs/langs/fr_FR/main.lang
@@ -15,6 +15,7 @@ FormatDateHourTextShort=%d %b %Y %H:%M
 FormatDateHourText=%d %B %Y %H:%M
 DatabaseConnection=Connexion à la base
 NoTranslation=Pas de traduction
+NoRecordFound=Aucun enregistrement trouvé
 NoError=Aucune erreur
 Error=Erreur
 ErrorFieldRequired=Le champ '%s' est obligatoire
@@ -532,6 +533,7 @@ GoBack=Retour arrière
 CanBeModifiedIfOk=Peut être modifié si valide
 CanBeModifiedIfKo=Peut être modifié si invalide
 RecordModifiedSuccessfully=Enregistrement modifié avec succès
+RecordsModified=%s enregistrements modifiés
 AutomaticCode=Création automatique du code
 NotManaged=Non géré
 FeatureDisabled=Fonction désactivée
diff --git a/htdocs/product/admin/product_tools.php b/htdocs/product/admin/product_tools.php
index dd8066cebed..cec370c1e2c 100644
--- a/htdocs/product/admin/product_tools.php
+++ b/htdocs/product/admin/product_tools.php
@@ -21,8 +21,8 @@
  *  \brief      Setup page of product module
  */
 
-// TODO We must add a sentence to explain goal of page
 // TODO We must add a confirmation on button because this will make a mass change
+// TODO Should also change table product_price for price levels
 
 require '../../main.inc.php';
 require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
@@ -38,7 +38,10 @@ if (! $user->admin) accessforbidden();
 $action = GETPOST('action','alpha');
 $oldvatrate=GETPOST('oldvatrate');
 $newvatrate=GETPOST('newvatrate');
-$price_base_type=GETPOST('price_base_type');
+//$price_base_type=GETPOST('price_base_type');
+
+$objectstatic = new Product($db);
+
 
 /*
  * Actions
@@ -48,53 +51,73 @@ if ($action == 'convert')
 {
 	$error=0;
 
-	$db->begin();
-
-	$sql = 'SELECT rowid';
-	$sql.= ' FROM '.MAIN_DB_PREFIX.'product';
-	$sql.= ' WHERE entity IN ('.getEntity('product',1).')';
-	$sql.= ' AND tva_tx = "'.$oldvatrate.'"';
+	if ($oldvatrate == $newvatrate)
+	{
+		$langs->load("errors");
+		setEventMessage($langs->trans("ErrorNewVaueCantMatchOldValue"),'errors');
+		$error++;
+	}
 
-	$resql=$db->query($sql);
-	if ($resql)
+	if (! $error)
 	{
-		$num = $db->num_rows($resql);
-		if ($num)
+		$db->begin();
+
+		$sql = 'SELECT rowid';
+		$sql.= ' FROM '.MAIN_DB_PREFIX.'product';
+		$sql.= ' WHERE entity IN ('.getEntity('product',1).')';
+		$sql.= " AND tva_tx = '".$db->escape($oldvatrate)."'";
+		//$sql.= ' AND price_base_type = "'..'"';
+		//print $sql;
+
+		$resql=$db->query($sql);
+		if ($resql)
 		{
-			$i = 0;
+			$num = $db->num_rows($resql);
+
+			$i = 0; $nbrecordsmodified=0;
 			while ($i < $num)
 			{
 				$obj = $db->fetch_object($resql);
 
-				$object = new Product($db);
-
-				$ret=$object->fetch($obj->rowid);
-				if ($ret)
+				$ret=$objectstatic->fetch($obj->rowid);
+				if ($ret > 0)
 				{
+					$price_base_type = $objectstatic->price_base_type;	// Get price_base_type of product/service to keep the same for update
 					if ($price_base_type == 'TTC')
 					{
-						$newprice=price2num($object->price_ttc,'MU');    // Second param must be MU (we want a unit price so 'MT'. If unit price was on 4 decimal, we must keep 4 decimals)
+						$newprice=price2num($objectstatic->price_ttc,'MU');    // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
+						$newminprice=$objectstatic->price_min_ttc;
 					}
 					else
 					{
-						$newprice=price2num($object->price,'MU');    // Second param must be MU (we want a unit price so 'MT'. If unit price was on 4 decimal, we must keep 4 decimals)
+						$newprice=price2num($objectstatic->price,'MU');    // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
+						$newminprice=$objectstatic->price_min;
 					}
-
+					if ($newminprice > $newprice) $newminprice=$newprice;
 					$newvat=str_replace('*','',$newvatrate);
+					$newnpr=$objectstatic->recuperableonly;
+					$newlevel=0;
 
-					$ret=$object->updatePrice($object->id, $newprice, $price_base_type, $user, $newvat);
+					$ret=$objectstatic->updatePrice($objectstatic->id, $newprice, $price_base_type, $user, $newvat, $newminprice, $newlevel, $newnpr);
 					if ($ret < 0) $error++;
+					else $nbrecordsmodified++;
+
+					// FIXME Now update all price levels. Call $objectstatic->updatePrice( as many times than exisitng price_level
+
 				}
 
-				$i++;
+				$i++;
 			}
 
 			if (! $error)
 			{
+				if ($nbrecordsmodified > 0) setEventMessage($langs->trans("RecordsModified",$nbrecordsmodified));
+				else setEventMessage($langs->trans("NoRecordFound"),'warnings');
 				$db->commit();
 			}
 			else
 			{
+				setEventMessage($langs->trans("Error"),'errors');
 				$db->rollback();
 			}
 		}
@@ -105,26 +128,13 @@ if ($action == 'convert')
  * View
  */
 
-$title = $langs->trans('ProductServiceSetup');
-$tab = $langs->trans("ProductsAndServices");
-if (empty($conf->produit->enabled))
-{
-	$title = $langs->trans('ServiceSetup');
-	$tab = $langs->trans('Services');
-}
-else if (empty($conf->service->enabled))
-{
-	$title = $langs->trans('ProductSetup');
-	$tab = $langs->trans('Products');
-}
+$title = $langs->trans('ModulesSystemTools');
 
 llxHeader('',$title);
 
-$linkback='<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
-print_fiche_titre($title,$linkback,'setup');
+print_fiche_titre($title,'','setup');
 
-$head = product_admin_prepare_head();
-dol_fiche_head($head, 'tools', $tab, 0, 'product');
+print $langs->trans("ProductVatMassChangeDesc").'<br><br>';
 
 $form=new Form($db);
 $var=true;
@@ -155,28 +165,29 @@ print $form->load_tva('newvatrate', $newvatrate);
 print '</td>'."\n";
 print '</tr>'."\n";
 
+/*
 $var=!$var;
 print '<tr '.$bc[$var].'>'."\n";
-print '<td>'.$langs->trans("PriceBaseType").'</td>'."\n";
+print '<td>'.$langs->trans("PriceBaseTypeToChange").'</td>'."\n";
 print '<td width="60" align="right">'."\n";
 print $form->load_PriceBaseType($price_base_type);
 print '</td>'."\n";
 print '</tr>'."\n";
+*/
 
 print '</table>';
 print '</div>';
 
 // Boutons actions
 print '<div class="tabsAction">';
-print '<input type="submit" id="convert_vatrate" name="convert_vatrate" value="'.$langs->trans("Convert").'" class="button" />';
+print '<input type="submit" id="convert_vatrate" name="convert_vatrate" value="'.$langs->trans("MassConvert").'" class="button" />';
 print '</div>';
 
 print '</form>';
 
-dol_htmloutput_mesg($mesg);
+dol_htmloutput_events();
 
 llxFooter();
 
 $db->close();
-
 ?>
-- 
GitLab