From 0b7f623c3195c70d66914e0672f741d46da9c62f Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Wed, 19 Feb 2014 17:04:21 +0100
Subject: [PATCH] New: Add an admin page to make a mass init of barcode values
 for all products.

---
 ChangeLog                     |   5 +-
 htdocs/barcode/codeinit.php   | 196 +++++++++++++++++++++++++++++++++-
 htdocs/barcode/printsheet.php |  16 +--
 htdocs/langs/en_US/admin.lang |   6 ++
 4 files changed, 210 insertions(+), 13 deletions(-)

diff --git a/ChangeLog b/ChangeLog
index b995520482e..654817fb168 100644
--- a/ChangeLog
+++ b/ChangeLog
@@ -16,11 +16,12 @@ For users:
        to automatically add timestamp and user line into editionf field when editing a note.
 - New: Add button cancel into edition of notes.
 - New: Improved Opensurvey module and added options to disable comments and disable
-       public votes
+       public votes.
 - New: The box "balance of bank accounts" show all opened accounts.
 - New: Add option MAIN_ADD_SALE_REP_SIGNATURE_IN_NOTE.
 - New: Add warning if supplier payment is higher that due amount.
-- New increase length of url into bookmark module.
+- New: Increase length of url into bookmark module.
+- New: Add an admin page to make a mass init of barcode values for all products. 
 
 TODO
 - New: Predefined product and free product use same form.
diff --git a/htdocs/barcode/codeinit.php b/htdocs/barcode/codeinit.php
index f016423f44b..bae8d90e589 100644
--- a/htdocs/barcode/codeinit.php
+++ b/htdocs/barcode/codeinit.php
@@ -46,16 +46,109 @@ $action=GETPOST('action');
 $producttmp=new Product($db);
 $thirdpartytmp=new Societe($db);
 
+$modBarCodeProduct='';
+
 
 /*
  * Actions
  */
 
-if ($action == 'init')
+// Define barcode template for products
+if (! empty($conf->global->BARCODE_PRODUCT_ADDON_NUM))
 {
-	$action='';
+	$dirbarcodenum=array_merge(array('/core/modules/barcode/'),$conf->modules_parts['barcode']);
+
+	foreach ($dirbarcodenum as $dirroot)
+	{
+		$dir = dol_buildpath($dirroot,0);
+
+		$handle = @opendir($dir);
+	    if (is_resource($handle))
+	    {
+	    	while (($file = readdir($handle))!==false)
+	    	{
+	    		if (preg_match('/^mod_barcode_product_.*php$/', $file))
+	    		{
+	    			$file = substr($file, 0, dol_strlen($file)-4);
+
+	    		    try {
+	        			dol_include_once($dirroot.$file.'.php');
+	    			}
+	    			catch(Exception $e)
+	    			{
+	    			    dol_syslog($e->getMessage(), LOG_ERR);
+	    			}
+
+	    			$modBarCodeProduct = new $file();
+	    			break;
+	    		}
+	    	}
+	    	closedir($handle);
+	    }
+	}
+}
+
+if ($action == 'initbarcodeproducts')
+{
+	if (! is_object($modBarCodeProduct))
+	{
+		$error++;
+		setEventMessage($langs->trans("NoBarcodeNumberingTemplateDefined"),'errors');
+	}
+
+	if (! $error)
+	{
+		$productstatic=new Product($db);
 
+		$db->begin();
 
+		$sql="SELECT rowid, ref, fk_product_type FROM ".MAIN_DB_PREFIX."product where barcode IS NULL or barcode = ''";
+		$resql=$db->query($sql);
+		if ($resql)
+		{
+			$num=$db->num_rows($resql);
+
+			$i=0; $nbok=$nbtry=0;
+			while ($i < $num)
+			{
+				$obj=$db->fetch_object($resql);
+				if ($obj)
+				{
+					$productstatic->id=$obj->rowid;
+					$productstatic->ref=$obj->ref;
+					$productstatic->type=$obj->fk_product_type;
+					$nextvalue=$modBarCodeProduct->getNextValue($productstatic,'');
+
+					print 'Set value '.$nextvalue.' to product '.$productstatic->id." ".$productstatic->ref." ".$productstatic->type."<br>\n";
+					$result=$productstatic->setValueFrom('barcode', $nextvalue);
+
+					$nbtry++;
+					if ($result > 0) $nbok++;
+				}
+
+				$i++;
+			}
+		}
+		else
+		{
+			$error++;
+			dol_print_error($db);
+		}
+
+		if (! $error)
+		{
+			setEventMessage($langs->trans("RecordsModified",$nbok),'mesgs');
+
+			//$db->rollback();
+			$db->commit();
+		}
+		else
+		{
+			$db->rollback();
+		}
+	}
+
+	$action='';
 }
 
 
@@ -64,6 +157,9 @@ if ($action == 'init')
  * View
  */
 
+if (!$user->admin) accessforbidden();
+if (empty($conf->barcode->enabled)) accessforbidden();
+
 $form=new Form($db);
 
 llxHeader('',$langs->trans("MassBarcodeInit"));
@@ -81,9 +177,101 @@ dol_htmloutput_errors($mesg);
 
 print '<form action="'.$_SERVER["PHP_SELF"].'" method="POST">';
 print '<input type="hidden" name="mode" value="label">';
-print '<input type="hidden" name="action" value="builddoc">';
+print '<input type="hidden" name="action" value="initbarcodeproducts">';
+
+print '<br>';
+
+// For thirdparty
+if ($conf->societe->enabled)
+{
+	$nbno=$nbtotal=0;
+
+	print_fiche_titre($langs->trans("BarcodeInitForThirdparties"),'','').'<br>'."\n";
+	$sql="SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe where barcode IS NULL or barcode = ''";
+	$resql=$db->query($sql);
+	if ($resql)
+	{
+		$obj=$db->fetch_object($resql);
+		$nbno=$obj->nb;
+	}
+	else dol_print_error($db);
+
+	$sql="SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."societe";
+	$resql=$db->query($sql);
+	if ($resql)
+	{
+		$obj=$db->fetch_object($resql);
+		$nbtotal=$obj->nb;
+	}
+	else dol_print_error($db);
+
+	print $langs->trans("CurrentlyNWithoutBarCode", $nbno, $nbtotal, $langs->transnoentitiesnoconv("Thirdparties")).'<br>'."\n";
+
+	print '<br><input class="button" type="submit" id="submitformbarcodethirdpartygen" '.((GETPOST("selectorforbarcode") && GETPOST("selectorforbarcode"))?'':'disabled="checked" ').'value="'.$langs->trans("InitEmptyBarCode",$nbno).'"';
+	print ' title="'.dol_escape_htmltag($langs->trans("FeatureNotYetAvailable")).'" disabled="disabled"';
+	print '>';
+	print '<br><br><br>';
+}
+
+
+// For products
+if ($conf->product->enabled || $conf->product->service)
+{
+	$nbno=$nbtotal=0;
+
+	print_fiche_titre($langs->trans("BarcodeInitForProductsOrServices"),'','').'<br>'."\n";
+	$sql="SELECT count(rowid) as nb, fk_product_type FROM ".MAIN_DB_PREFIX."product where barcode IS NULL or barcode = '' GROUP BY fk_product_type";
+	$resql=$db->query($sql);
+	if ($resql)
+	{
+		$num=$db->num_rows($resql);
+
+		$i=0;
+		while($i < $num)
+		{
+			$obj=$db->fetch_object($resql);
+			$nbno+=$obj->nb;
+
+			$i++;
+		}
+	}
+	else dol_print_error($db);
+
+	$sql="SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."product";
+	$resql=$db->query($sql);
+	if ($resql)
+	{
+		$obj=$db->fetch_object($resql);
+		$nbtotal=$obj->nb;
+	}
+	else dol_print_error($db);
+
+	print $langs->trans("CurrentlyNWithoutBarCode", $nbno, $nbtotal, $langs->transnoentitiesnoconv("ProductsOrServices")).'<br>'."\n";
+
+	if (is_object($modBarCodeProduct))
+	{
+		print $langs->trans("BarCodeNumberManager").": ";
+		$objproduct=new Product($db);
+		print '<b>'.$modBarCodeProduct->nom.'</b> - '.$langs->trans("NextValue").': <b>'.$modBarCodeProduct->getNextValue($objproduct).'</b><br>';
+		$disabled=0;
+	}
+	else
+	{
+		$disabled=1;
+		$titleno=$langs->trans("NoBarcodeNumberingTemplateDefined");
+		print '<font class="warning">'.$langs->trans("NoBarcodeNumberingTemplateDefined").'</font><br>';
+	}
+	if (empty($nbno))
+	{
+		$disabled=1;
+		$titleno=$langs->trans("NoRecordWithoutBarcodeDefined");
+		print '<font class="ok">'.$langs->trans("NoRecordWithoutBarcodeDefined").'</font><br>';
+	}
+
+	print '<br><input class="button" type="submit" id="submitformbarcodeproductgen" value="'.$langs->trans("InitEmptyBarCode",$nbno).'"'.($disabled?' disabled="disabled" title="'.dol_escape_htmltag($titleno).'"':'').'>';
+	print '<br><br><br>';
+}
 
-print '<br><input class="button" type="submit" id="submitformbarcodegen" '.((GETPOST("selectorforbarcode") && GETPOST("selectorforbarcode"))?'':'disabled="checked" ').'value="'.$langs->trans("InitEmptyBarCode").'">';
 
 print '</form>';
 print '<br>';
diff --git a/htdocs/barcode/printsheet.php b/htdocs/barcode/printsheet.php
index 5e2e52366fc..aa2be8d136f 100644
--- a/htdocs/barcode/printsheet.php
+++ b/htdocs/barcode/printsheet.php
@@ -63,12 +63,12 @@ if (GETPOST('submitproduct') && GETPOST('submitproduct'))
 		$producttmp->fetch(GETPOST('productid'));
 		$forbarcode=$producttmp->barcode;
 		$fk_barcode_type=$thirdpartytmp->barcode_type_code;
-	
+
 		if (empty($fk_barcode_type) && ! empty($conf->global->PRODUIT_DEFAULT_BARCODE_TYPE)) $fk_barcode_type = $conf->global->PRODUIT_DEFAULT_BARCODE_TYPE;
-		
+
 		if (empty($forbarcode) || empty($fk_barcode_type))
 		{
-			setEventMessage($langs->trans("DefinitionOfBarCodeForProductNotComplete",$producttmp->getNomUrl()), 'warnings');	
+			setEventMessage($langs->trans("DefinitionOfBarCodeForProductNotComplete",$producttmp->getNomUrl()), 'warnings');
 		}
 	}
 }
@@ -80,12 +80,12 @@ if (GETPOST('submitthirdparty') && GETPOST('submitthirdparty'))
 		$thirdpartytmp->fetch(GETPOST('socid'));
 		$forbarcode=$thirdpartytmp->barcode;
 		$fk_barcode_type=$thirdpartytmp->barcode_type_code;
-	
+
 		if (empty($fk_barcode_type) && ! empty($conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY)) $fk_barcode_type = $conf->global->GENBARCODE_BARCODETYPE_THIRDPARTY;
-		
+
 		if (empty($forbarcode) || empty($fk_barcode_type))
 		{
-			setEventMessage($langs->trans("DefinitionOfBarCodeForProductNotComplete",$thirdpartytmp->getNomUrl()), 'warnings');	
+			setEventMessage($langs->trans("DefinitionOfBarCodeForProductNotComplete",$thirdpartytmp->getNomUrl()), 'warnings');
 		}
 	}
 }
@@ -243,6 +243,8 @@ if ($action == 'builddoc')
  * View
  */
 
+if (empty($conf->barcode->enabled)) accessforbidden();
+
 $form=new Form($db);
 
 llxHeader('',$langs->trans("BarCodePrintsheet"));
@@ -329,7 +331,7 @@ jQuery(document).ready(function() {
 	jQuery(".radiobarcodeselect").click(function() {
 		init_selectors();
 	});
-	
+
 	function init_gendoc_button()
 	{
 		if (jQuery("#select_fk_barcode_type").val() > 0 && jQuery("#forbarcode").val())
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index a7bf4b21b18..2b0bbd05d78 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -379,6 +379,12 @@ KeepEmptyToUseDefault=Keep empty to use default value
 DefaultLink=Default link
 ValueOverwrittenByUserSetup=Warning, this value may be overwritten by user specific setup (each user can set his own clicktodial url)
 ExternalModule=External module - Installed into directory %s
+BarcodeInitForThirdparties=Mass barcode init for thirdparties
+BarcodeInitForProductsOrServices=Mass barcode init for products or services
+CurrentlyNWithoutBarCode=Currently, you have <strong>%s</strong> records on <strong>%s</strong> %s without barcode defined.
+InitEmptyBarCode=Init the %s barcode
+NoBarcodeNumberingTemplateDefined=No numbering barcode template enabled into barcode module setup.
+NoRecordWithoutBarcodeDefined=No record with no barcode value defined.
 
 # Modules
 Module0Name=Users & groups
-- 
GitLab