From 01001592e68a0b79fa4c855bd0f4bb3f5466f7ab Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Tue, 6 May 2014 18:31:39 +0200
Subject: [PATCH] Finished task to merge form of free product and predefined
 product.

---
 htdocs/core/tpl/objectline_create.tpl.php |  85 ++++-----
 htdocs/core/tpl/objectline_edit.tpl.php   |   2 +-
 htdocs/fourn/facture/fiche.php            | 201 +++++++++++++---------
 3 files changed, 166 insertions(+), 122 deletions(-)

diff --git a/htdocs/core/tpl/objectline_create.tpl.php b/htdocs/core/tpl/objectline_create.tpl.php
index 8e664a89c3c..64769fa704f 100644
--- a/htdocs/core/tpl/objectline_create.tpl.php
+++ b/htdocs/core/tpl/objectline_create.tpl.php
@@ -18,21 +18,32 @@
  * along with this program. If not, see <http://www.gnu.org/licenses/>.
  *
  * Need to have following variables defined:
+ * $object (invoice, order, ...)
  * $conf
  * $langs
  * $dateSelector
- * $this (invoice, order, ...)
- * $inputalsopricewithtax
  * $forceall (0 by default, 1 for supplier invoices/orders)
  * $senderissupplier (0 by default, 1 for supplier invoices/orders)
+ * $inputalsopricewithtax (0 by default, 1 to also show column with unit price including tax)
  */
 
-global $dateSelector, $forceall, $senderissupplier;
 
 $usemargins=0;
 if (! empty($conf->margin->enabled) && ! empty($object->element) && in_array($object->element,array('facture','propal','commande'))) $usemargins=1;
+
+global $dateSelector, $forceall, $senderissupplier, $inputalsopricewithtax;
+if (empty($dateSelector)) $dateSelector=0;
 if (empty($forceall)) $forceall=0;
 if (empty($senderissupplier)) $senderissupplier=0;
+if (empty($inputalsopricewithtax)) $inputalsopricewithtax=0;
+
+
+// Define colspan for button Add
+$colspan = 3;	// Col total ht + col edit + col delete
+if (! empty($inputalsopricewithtax)) $colspan++;	// We add 1 if col total ttc
+if (in_array($object->element,array('propal','facture','invoice','commande','order'))) $colspan++;	// With this, there is a column move
+if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARGIN_RATES)) $colspan++;
+if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARK_RATES))   $colspan++;
 ?>
 
 <!-- BEGIN PHP TEMPLATE objectline_create.tpl.php -->
@@ -49,7 +60,6 @@ if (empty($senderissupplier)) $senderissupplier=0;
 	<td align="right"><?php echo $langs->trans('Qty'); ?></td>
 	<td align="right"><?php echo $langs->trans('ReductionShort'); ?></td>
 	<?php
-	$colspan = 4;
 	if (! empty($usemargins))
 	{
 		?>
@@ -62,22 +72,8 @@ if (empty($senderissupplier)) $senderissupplier=0;
 		?>
 		</td>
 		<?php
-		if ($user->rights->margins->creer)
-		{
-			if(! empty($conf->global->DISPLAY_MARGIN_RATES))
-			{
-				echo '<td align="right">'.$langs->trans('MarginRate').'</td>';
-			}
-			if(! empty($conf->global->DISPLAY_MARK_RATES))
-			{
-				echo '<td align="right">'.$langs->trans('MarkRate').'</td>';
-			}
-		}
-		else
-		{
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) $colspan++;
-			if (! empty($conf->global->DISPLAY_MARK_RATES))   $colspan++;
-		}
+		if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARGIN_RATES)) echo '<td align="right">'.$langs->trans('MarginRate').'</td>';
+		if ($user->rights->margins->creer && ! empty($conf->global->DISPLAY_MARK_RATES)) 	echo '<td align="right">'.$langs->trans('MarkRate').'</td>';
 	}
 	?>
 	<td colspan="<?php echo $colspan; ?>">&nbsp;</td>
@@ -98,20 +94,30 @@ else {
 	// Free line
 	echo '<span>';
 	// Show radio free line
-	if (! empty($conf->product->enabled) || ! empty($conf->service->enabled)) echo '<input type="radio" name="prod_entry_mode" id="prod_entry_mode_free" value="free"'.(GETPOST('prod_entry_mode')=='free'?' checked="true"':'').'> ';
+	if (! empty($conf->product->enabled) || ! empty($conf->service->enabled))
+	{
+		echo '<input type="radio" name="prod_entry_mode" id="prod_entry_mode_free" value="free"';
+		//echo (GETPOST('prod_entry_mode')=='free' ? ' checked="true"' : ((empty($forceall) && (empty($conf->product->enabled) || empty($conf->service->enabled)))?' checked="true"':'') );
+		echo (GETPOST('prod_entry_mode')=='free' ? ' checked="true"' : '');
+		echo '> ';
+	}
 	else echo '<input type="hidden" id="prod_entry_mode_free" name="prod_entry_mode" value="free">';
 	// Show type selector
-	if (empty($conf->product->enabled) && empty($conf->service->enabled))
+/*	if (empty($conf->product->enabled) && empty($conf->service->enabled))
 	{
 		// If module product and service disabled, by default this is a product except for contracts it is a service
 		print '<input type="hidden" name="type" value="'.((! empty($object->element) && $object->element == 'contrat')?'1':'0').'">';
 	}
-	else {
-		if (! empty($conf->product->enabled) && ! empty($conf->service->enabled)) echo $langs->trans("FreeLineOfType").' ';
+	else {*/
+		echo $langs->trans("FreeLineOfType");
+		/*
+		if (empty($conf->product->enabled) && empty($conf->service->enabled)) echo $langs->trans("Type");
+		else if (! empty($forceall) || (! empty($conf->product->enabled) && ! empty($conf->service->enabled))) echo $langs->trans("FreeLineOfType");
 		else if (empty($conf->product->enabled) && ! empty($conf->service->enabled)) echo $langs->trans("FreeLineOfType").' '.$langs->trans("Service");
-		else if (! empty($conf->product->enabled) && empty($conf->service->enabled)) echo $langs->trans("FreeLineOfType").' '.$langs->trans("Product");
-		echo $form->select_type_of_lines(isset($_POST["type"])?$_POST["type"]:-1,'type',1,1,$forceall);
-	}
+		else if (! empty($conf->product->enabled) && empty($conf->service->enabled)) echo $langs->trans("FreeLineOfType").' '.$langs->trans("Product");*/
+		echo ' ';
+		echo $form->select_type_of_lines(isset($_POST["type"])?$_POST["type"]:-1,'type',1,1,1);
+//	}
 	echo '</span>';
 
 	// Predefined product/service
@@ -200,8 +206,8 @@ else {
 	<td align="right"><input type="text" size="2" name="qty" class="flat" value="<?php echo (isset($_POST["qty"])?$_POST["qty"]:1); ?>">
 	</td>
 	<td align="right" class="nowrap"><input type="text" size="1" class="flat" value="<?php echo (isset($_POST["remise_percent"])?$_POST["remise_percent"]:$buyer->remise_client); ?>" name="remise_percent"><span class="hideonsmartphone">%</span></td>
+
 	<?php
-	$colspan = 4;
 	if (! empty($usemargins))
 	{
 		?>
@@ -214,32 +220,25 @@ else {
 			<input type="text" size="5" id="buying_price" name="buying_price" class="flat" value="<?php echo (isset($_POST["buying_price"])?$_POST["buying_price"]:''); ?>">
 		</td>
 		<?php
-		$colspan++;
-		$coldisplay++;
 
+		$coldisplay++;
 		if ($user->rights->margins->creer)
 		{
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES))
+			{
 				echo '<td align="right" class="nowrap"><input type="text" size="2" name="np_marginRate" value="'.(isset($_POST["np_marginRate"])?$_POST["np_marginRate"]:'').'"><span class="hideonsmartphone">%</span></td>';
-				$colspan++;
 				$coldisplay++;
 			}
-			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
+			if (! empty($conf->global->DISPLAY_MARK_RATES))
+			{
 				echo '<td align="right" class="nowrap"><input type="text" size="2" name="np_markRate" value="'.(isset($_POST["np_markRate"])?$_POST["np_markRate"]:'').'"><span class="hideonsmartphone">%</span></td>';
-				$colspan++;
 				$coldisplay++;
 			}
 		}
 		else
 		{
-			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) {
-				$colspan++;
-				$coldisplay++;
-			}
-			if (! empty($conf->global->DISPLAY_MARK_RATES)) {
-				$colspan++;
-				$coldisplay++;
-			}
+			if (! empty($conf->global->DISPLAY_MARGIN_RATES)) $coldisplay++;
+			if (! empty($conf->global->DISPLAY_MARK_RATES))   $coldisplay++;
 		}
 	}
 	?>
@@ -491,6 +490,7 @@ function setforfree() {
 	jQuery("#prod_entry_mode_free").attr('checked',true);
 	jQuery("#prod_entry_mode_predef").attr('checked',false);
 	jQuery("#price_ht").show();
+	jQuery("#price_ttc").show();	// May no exists
 	jQuery("#tva_tx").show();
 	jQuery("#buying_price").val('').show();
 	jQuery("#fournprice_predef").hide();
@@ -503,6 +503,7 @@ function setforpredef() {
 	jQuery("#prod_entry_mode_free").attr('checked',false);
 	jQuery("#prod_entry_mode_predef").attr('checked',true);
 	jQuery("#price_ht").hide();
+	jQuery("#price_ttc").hide();	// May no exists
 	jQuery("#tva_tx").hide();
 	jQuery("#buying_price").show();
 	jQuery("#title_vat").hide();
diff --git a/htdocs/core/tpl/objectline_edit.tpl.php b/htdocs/core/tpl/objectline_edit.tpl.php
index c9e8ded2e9e..94ad11c991c 100644
--- a/htdocs/core/tpl/objectline_edit.tpl.php
+++ b/htdocs/core/tpl/objectline_edit.tpl.php
@@ -93,7 +93,7 @@ $coldisplay=-1; // We remove first td
     $nbrows=ROWS_2;
     if (! empty($conf->global->MAIN_INPUT_DESC_HEIGHT)) $nbrows=$conf->global->MAIN_INPUT_DESC_HEIGHT;
     $enable=(isset($conf->global->FCKEDITOR_ENABLE_DETAILS)?$conf->global->FCKEDITOR_ENABLE_DETAILS:0);
-	$doleditor=new DolEditor('product_desc',$line->description,'',164,'dolibarr_details','',false,true,$enable,$nbrows,70);
+	$doleditor=new DolEditor('product_desc',$line->description,'',164,'dolibarr_details','',false,true,$enable,$nbrows,'98%');
 	$doleditor->Create();
 	?>
 	</td>
diff --git a/htdocs/fourn/facture/fiche.php b/htdocs/fourn/facture/fiche.php
index 5fd66e90f55..a787930471a 100644
--- a/htdocs/fourn/facture/fiche.php
+++ b/htdocs/fourn/facture/fiche.php
@@ -515,55 +515,73 @@ elseif ($action == 'update_line' && $user->rights->fournisseur->facture->creer)
 
 elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer)
 {
+    $ret=$object->fetch($id);
+    if ($ret < 0)
+    {
+        dol_print_error($db,$object->error);
+        exit;
+    }
+    $ret=$object->fetch_thirdparty();
+
     $langs->load('errors');
 	$error=0;
 
 	// Set if we used free entry or predefined product
-	if (GETPOST('addline_libre')
-			|| (GETPOST('dp_desc') && ! GETPOST('addline_libre') && ! GETPOST('idprod', 'int')>0)	// we push enter onto qty field
-			)
+	$predef='';
+	$product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
+	if (GETPOST('prod_entry_mode') == 'free')
 	{
-		$predef='';
 		$idprod=0;
-		$product_desc=(GETPOST('dp_desc')?GETPOST('dp_desc'):'');
 		$price_ht = GETPOST('price_ht');
-		$tva_tx=(GETPOST('tva_tx')?GETPOST('tva_tx'):0);
+		$tva_tx = (GETPOST('tva_tx') ? GETPOST('tva_tx') : 0);
 	}
-	if (GETPOST('addline_predefined')
-			|| (! GETPOST('dp_desc') && ! GETPOST('addline_predefined') && GETPOST('idprod', 'int')>0)	// we push enter onto qty field
-			)
+	else
 	{
-		$predef=(($conf->global->MAIN_FEATURES_LEVEL < 2) ? '_predef' : '');
 		$idprod=GETPOST('idprod', 'int');
-		$product_desc = (GETPOST('product_desc')?GETPOST('product_desc'):(GETPOST('np_desc')?GETPOST('np_desc'):''));
 		$price_ht = '';
 		$tva_tx = '';
 	}
+
 	$qty = GETPOST('qty'.$predef);
 	$remise_percent=GETPOST('remise_percent'.$predef);
 
-
-    $ret=$object->fetch($id);
-    if ($ret < 0)
+    if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht') < 0 && $qty < 0)
     {
-        dol_print_error($db,$object->error);
-        exit;
+        setEventMessage($langs->trans('ErrorBothFieldCantBeNegative', $langs->transnoentitiesnoconv('UnitPrice'), $langs->transnoentitiesnoconv('Qty')), 'errors');
+        $error++;
+    }
+    if (GETPOST('prod_entry_mode')=='free'  && ! GETPOST('idprodfournprice') && GETPOST('type') < 0)
+    {
+        setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Type')), 'errors');
+        $error++;
+    }
+    if (GETPOST('prod_entry_mode')=='free' && GETPOST('price_ht')==='' && GETPOST('price_ttc')==='') // Unit price can be 0 but not ''
+    {
+        setEventMessage($langs->trans($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('UnitPrice'))), 'errors');
+        $error++;
+    }
+    if (GETPOST('prod_entry_mode')=='free' && ! GETPOST('dp_desc'))
+    {
+        setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Description')), 'errors');
+        $error++;
+    }
+    if (! GETPOST('qty'))
+    {
+        setEventMessage($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv('Qty')), 'errors');
+        $error++;
     }
-    $ret=$object->fetch_thirdparty();
 
-    if (GETPOST('addline_predefined') || GETPOST('search_idprodfournprice') || GETPOST('idprodfournprice'))	// With combolist idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
+    if (GETPOST('prod_entry_mode') != 'free')	// With combolist mode idprodfournprice is > 0 or -1. With autocomplete, idprodfournprice is > 0 or ''
     {
     	$idprod=0;
     	$productsupplier=new ProductFournisseur($db);
 
-    	if (GETPOST('idprodfournprice') == '')
-		{
-			$idprod=-1;
-		}
+        if (GETPOST('idprodfournprice') == -1 || GETPOST('idprodfournprice') == '') $idprod=-2;	// Same behaviour than with combolist. When not select idprodfournprice is now -2 (to avoid conflict with next action that may return -1)
+
     	if (GETPOST('idprodfournprice') > 0)
-        {
-    	    $idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty);    // Just to see if a price exists for the quantity. Not used to found vat
-        }
+    	{
+    		$idprod=$productsupplier->get_buyprice(GETPOST('idprodfournprice'), $qty);    // Just to see if a price exists for the quantity. Not used to found vat.
+    	}
 
         if ($idprod > 0)
         {
@@ -584,7 +602,7 @@ elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer)
 
             $result=$object->addline($desc, $productsupplier->fourn_pu, $tvatx, $localtax1tx, $localtax2tx, $qty, $idprod, $remise_percent, '', '', 0, $npr);
         }
-        if ($idprod == 0)
+    	if ($idprod == -2 || $idprod == 0)
         {
             // Product not selected
             $error++;
@@ -599,39 +617,37 @@ elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer)
             $mesg='<div class="error">'.$langs->trans("ErrorQtyTooLowForThisSupplier").'</div>';
         }
     }
-    else
-    {
-        $npr = preg_match('/\*/', $_POST['tauxtva']) ? 1 : 0 ;
-        $tauxtva = str_replace('*','',$_POST["tauxtva"]);
-        $tauxtva = price2num($tauxtva);
-        $localtax1tx= get_localtax($tauxtva, 1, $mysoc,$object->thirdparty);
-        $localtax2tx= get_localtax($tauxtva, 2, $mysoc,$object->thirdparty);
+    else if( GETPOST('price_ht')!=='' || GETPOST('price_ttc')!=='' )
+	{
+		$pu_ht = price2num($price_ht, 'MU');
+		$pu_ttc = price2num(GETPOST('price_ttc'), 'MU');
+		$tva_npr = (preg_match('/\*/', $tva_tx) ? 1 : 0);
+		$tva_tx = str_replace('*', '', $tva_tx);
+		$label = (GETPOST('product_label') ? GETPOST('product_label') : '');
+		$desc = $product_desc;
+		$type = GETPOST('type');
 
-        if (! $product_desc)
-        {
-        	$error++;
-            $mesg='<div class="error">'.$langs->trans("ErrorFieldRequired",$langs->transnoentities("Description")).'</div>';
-        }
-        else
-       {
-            $type = $_POST["type"];
+    	$tva_tx = price2num($tva_tx);	// When vat is text input field
 
-	        if (! empty($_POST['amount']))
-            {
-                $ht = price2num($_POST['amount']);
-                $price_base_type = 'HT';
+    	// Local Taxes
+    	$localtax1_tx= get_localtax($tva_tx, 1,$mysoc,$object->thirdparty);
+    	$localtax2_tx= get_localtax($tva_tx, 2,$mysoc,$object->thirdparty);
 
-                //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0
-                $result=$object->addline($product_desc, $ht, $tauxtva, $localtax1tx, $localtax2tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type);
-            }
-            else
-            {
-                $ttc = price2num($_POST['amountttc']);
-                $ht = $ttc / (1 + ($tauxtva / 100));
-                $price_base_type = 'HT';
-                //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0
-                $result=$object->addline($product_desc, $ht, $tauxtva,$localtax1tx, $localtax2tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type);
-            }
+    	if (!empty($_POST['price_ht']))
+    	{
+    		$ht = price2num($_POST['price_ht']);
+            $price_base_type = 'HT';
+
+            //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0
+            $result=$object->addline($product_desc, $ht, $tva_tx, $localtax1tx, $localtax2tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type);
+        }
+        else
+		{
+    		$ttc = price2num($_POST['price_ttc']);
+            $ht = $ttc / (1 + ($tva_tx / 100));
+            $price_base_type = 'HT';
+            //print $product_desc, $pu, $txtva, $qty, $fk_product=0, $remise_percent=0, $date_start='', $date_end='', $ventil=0, $info_bits='', $price_base_type='HT', $type=0
+            $result=$object->addline($product_desc, $ht, $tva_tx,$localtax1tx, $localtax2tx, $qty, 0, $remise_percent, $datestart, $dateend, 0, $npr, $price_base_type, $type);
         }
     }
 
@@ -657,22 +673,35 @@ elseif ($action == 'addline' && $user->rights->fournisseur->facture->creer)
         	}
         }
 
-        unset($_POST['qty']);
-        unset($_POST['type']);
-        unset($_POST['remise_percent']);
-        unset($_POST['dp_desc']);
-        unset($_POST['pu']);
-        unset($_POST['tva_tx']);
-        unset($_POST['label']);
-        unset($localtax1_tx);
-        unset($localtax2_tx);
-
-        unset($_POST['idprodfournprice']);
-		unset($_POST['qty_predef']);
-		unset($_POST['remise_percent_predef']);
-		unset($_POST['fournprice_predef']);
-		unset($_POST['buying_price_predef']);
-		unset($_POST['np_desc']);
+		unset($_POST ['prod_entry_mode']);
+
+    	unset($_POST['qty']);
+    	unset($_POST['type']);
+    	unset($_POST['remise_percent']);
+    	unset($_POST['pu']);
+    	unset($_POST['price_ht']);
+    	unset($_POST['price_ttc']);
+    	unset($_POST['tva_tx']);
+    	unset($_POST['label']);
+    	unset($localtax1_tx);
+    	unset($localtax2_tx);
+		unset($_POST['np_marginRate']);
+		unset($_POST['np_markRate']);
+    	unset($_POST['dp_desc']);
+		unset($_POST['idprodfournprice']);
+
+    	unset($_POST['date_starthour']);
+    	unset($_POST['date_startmin']);
+    	unset($_POST['date_startsec']);
+    	unset($_POST['date_startday']);
+    	unset($_POST['date_startmonth']);
+    	unset($_POST['date_startyear']);
+    	unset($_POST['date_endhour']);
+    	unset($_POST['date_endmin']);
+    	unset($_POST['date_endsec']);
+    	unset($_POST['date_endday']);
+    	unset($_POST['date_endmonth']);
+    	unset($_POST['date_endyear']);
     }
     else if (empty($mesg))
     {
@@ -2021,13 +2050,10 @@ else
 
         }
 
-        /*
-         * Form to add new line
-         */
-
+		// Form to add new line
         if ($object->statut == 0 && $action != 'edit_line')
         {
-            print '<tr class="liste_titre">';
+            /*print '<tr class="liste_titre">';
             print '<td>';
             print '<a name="add"></a>'; // ancre
             print $langs->trans('AddNewLine').' - '.$langs->trans("FreeZone").'</td>';
@@ -2040,9 +2066,26 @@ else
             print '<td align="right">&nbsp;</td>';
             print '<td>&nbsp;</td>';
             print '<td>&nbsp;</td>';
-            print '</tr>';
+            print '</tr>';*/
+
+       		global $forceall, $senderissupplier, $dateSelector, $inputalsopricewithtax;
+			$forceall=1; $senderissupplier=1; $dateSelector=0; $inputalsopricewithtax=1;
+			if ($object->statut == 0 && $user->rights->propal->creer)
+			{
+				if ($action != 'editline')
+				{
+					$var = true;
+
+					// Add free products/services
+					$object->formAddObjectLine(1, $mysoc, $soc);
+
+					$parameters = array();
+					$reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
+				}
+			}
 
             // Add free products/services form
+			/*
             $var=true;
             print '<tr '.$bc[$var].'>';
             print '<td>';
@@ -2141,7 +2184,7 @@ else
                 print '<td>&nbsp;</td>';
                 print '<td align="center" valign="middle" colspan="2"><input type="submit" id="addPredefinedProductButton" class="button" value="'.$langs->trans("Add").'" name="addline_predefined"></td>';
                 print '</tr>';
-            }
+            }*/
         }
 
         print '</table>';
-- 
GitLab