From 26e315c785e29adc1d00f2c29aa66cbc19d93e59 Mon Sep 17 00:00:00 2001
From: Cyrille de Lambert <cyrille.delambert@auguria.net>
Date: Wed, 27 Jul 2011 08:00:45 +0000
Subject: [PATCH] improves the simplified payment MAIN_JS_ON_PAYMENT must be
 set

---
 htdocs/compta/ajaxpayment.php  | 73 +++++++++++++++++++++++-----------
 htdocs/compta/paiement.php     | 12 +++---
 htdocs/langs/en_US/compta.lang |  2 +
 htdocs/langs/fr_FR/compta.lang |  2 +
 4 files changed, 60 insertions(+), 29 deletions(-)

diff --git a/htdocs/compta/ajaxpayment.php b/htdocs/compta/ajaxpayment.php
index 9b23a1bd67a..259dc4dbce5 100644
--- a/htdocs/compta/ajaxpayment.php
+++ b/htdocs/compta/ajaxpayment.php
@@ -35,49 +35,74 @@ if (! defined('NOREQUIREHTML'))  define('NOREQUIREHTML','1'); // If we don't nee
 
 require('../main.inc.php');
 
-//print_r($_POST);
+$langs->Load('compta');
+
+//init var
+$amountPayment = $_POST['amountPayment'];
+$amounts = $_POST['amounts'];				// from text inputs : invoice amount payment (check required)
+$remains = $_POST['remains'];				// from dolibarr's object (no need to check)
+$currentInvId = $_POST['imgClicked'];		// from DOM elements : imgId (equals invoice id)
+
 
 // Getting the posted keys=>values, sanitize the ones who are from text inputs
 // from text inputs : total amount
-$amountPayment = price2num($_POST['amountPayment']);
-$amountPayment = is_numeric($amountPayment)? $amountPayment : 0;					// is a value
-// from text inputs : invoice amount payment
-$amounts = $_POST['amounts'];														// is an array (need a foreach)
+$amountPayment = $amountPayment!='' ? 	( is_numeric(price2num($amountPayment))	? price2num($amountPayment)
+																				: ''
+										) 
+									: '';			// keep void if not a valid entry
+// Checkamounts
 foreach ($amounts as $key => $value)
 {
 	$value = price2num($value);
 	if (!is_numeric($value)) unset($amounts[$key]);
 }
-// from dolibarr's object (no need to check)
-$remains = $_POST['remains'];
-// from DOM elements : imgId (equals invoice id)
-$currentInvId = $_POST['imgClicked'];
-
 
 // Treatment
-$result = $amountPayment - array_sum($amounts);										// Remaining amountPayment
+$result = $amountPayment != '' ? $amountPayment - array_sum($amounts) : $amountPayment + array_sum($amounts);										// Remaining amountPayment
 $toJsonArray = 	array();
+$totalRemaining = price2num(array_sum($remains));
+$toJsonArray['label'] = $amountPayment == '' ? $langs->transnoentities('AmountToBeCharged') : $langs->transnoentities('RemainingAmountPayment');
 if($currentInvId)																	// Here to breakdown
 {
 	// Get the current amount (from form) and the corresponding remainToPay (from invoice)
 	$currentAmount = $amounts['amount_'.$currentInvId];
 	$currentRemain = $remains['remain_'.$currentInvId];
-
-	// Reset the substraction for this amount
-	$result += price2num($currentAmount);
-	$currentAmount = 0;
-	if($result >= 0)			// then we need to calculate the amount to breakdown
+	
+	// If amountPayment isn't filled, breakdown invoice amount, else breakdown from amountPayment
+	if($amountPayment == '')
+	{
+		// Check if current amount exists in amounts
+		$amountExists = array_key_exists('amount_'.$currentInvId,$amounts);
+		if($amountExists)
+		{
+			$remainAmount = $currentRemain - $currentAmount;	// To keep value between curRemain and curAmount
+			$result += $remainAmount;							// result must be deduced by
+			$currentAmount += $remainAmount;					// curAmount put to curRemain
+		}else 
+		{
+			$currentAmount = $currentRemain;
+			$result += $currentRemain;
+		}		
+	}else 
 	{
-		$amountToBreakdown = ($result - $currentRemain >= 0 ?
-									$currentRemain : 								// Remain can be fully paid
-									$currentRemain + ($result - $currentRemain));	// Remain can only partially be paid
-		$currentAmount = $amountToBreakdown;						// In both cases, amount will take breakdown value
-		$result -= $amountToBreakdown;								// And canceled substraction has been replaced by breakdown
-	}	// else there's no need to calc anything, just reset the field (result is still < 0)
+		// Reset the substraction for this amount
+		$result += price2num($currentAmount);
+		$currentAmount = 0;
+		
+		if($result >= 0)			// then we need to calculate the amount to breakdown
+		{
+			$amountToBreakdown = ($result - $currentRemain >= 0 ?
+										$currentRemain : 								// Remain can be fully paid
+										$currentRemain + ($result - $currentRemain));	// Remain can only partially be paid
+			$currentAmount = $amountToBreakdown;						// In both cases, amount will take breakdown value
+			$result -= $amountToBreakdown;								// And canceled substraction has been replaced by breakdown
+		}	// else there's no need to calc anything, just reset the field (result is still < 0)
+	}
 	$toJsonArray['amount_'.$currentInvId] = price2num($currentAmount)."";			// Param will exist only if an img has been clicked
 }
 // Encode to JSON to return
-$toJsonArray['result'] = price2num($result)."";
-echo json_encode($toJsonArray);										// Printing the call's result
+$toJsonArray['makeRed'] = $totalRemaining < price2num($result) || price2num($result) < 0 ? true : false;
+$toJsonArray['result'] = price2num($result);
+echo json_encode($toJsonArray);	// Printing the call's result
 
 ?>
\ No newline at end of file
diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php
index 68419253c60..d2f2a7aae7e 100644
--- a/htdocs/compta/paiement.php
+++ b/htdocs/compta/paiement.php
@@ -24,7 +24,7 @@
  *	\file       htdocs/compta/paiement.php
  *	\ingroup    compta
  *	\brief      Page to create a payment
- *	\version    $Id: paiement.php,v 1.111 2011/07/13 08:57:21 eldy Exp $
+ *	\version    $Id: paiement.php,v 1.112 2011/07/27 08:00:45 cdelambert Exp $
  */
 
 require('../main.inc.php');
@@ -290,6 +290,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 		            	json["amountPayment"] = jQuery("#amountpayment").attr("value");
 		            	json["amounts"] = elemToJson(form.find("input[name*=\"amount_\"]"));
 		            	json["remains"] = elemToJson(form.find("input[name*=\"remain_\"]"));
+		            	
 		            	if(imgId != null)json["imgClicked"] = imgId;
 
             			jQuery.post("ajaxpayment.php", json, function(data)
@@ -300,13 +301,14 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie
 
             				for(var key in json)
             				{
-            					if(key == "result")	{
-            						jQuery("#"+key).text(json[key]);
-            						if(json[key] < 0) {
+            					if(key == "result")	{      						
+            						if(json["makeRed"]) {            							
             							jQuery("#"+key).css("color", "red");
             						} else {
             							jQuery("#"+key).removeAttr("style");
             						}
+            						json[key]=json["label"]+" "+json[key];            						
+            						jQuery("#"+key).text(json[key]);
             					} else {
             						form.find("input[name*=\""+key+"\"]").each(function() {
             							jQuery(this).attr("value", json[key]);
@@ -671,5 +673,5 @@ if (! GETPOST('action'))
 
 $db->close();
 
-llxFooter('$Date: 2011/07/13 08:57:21 $ - $Revision: 1.111 $');
+llxFooter('$Date: 2011/07/27 08:00:45 $ - $Revision: 1.112 $');
 ?>
diff --git a/htdocs/langs/en_US/compta.lang b/htdocs/langs/en_US/compta.lang
index 50c3f887959..b1e399af7ef 100644
--- a/htdocs/langs/en_US/compta.lang
+++ b/htdocs/langs/en_US/compta.lang
@@ -13,6 +13,8 @@ OptionModeVirtualDesc=In this context, the turnover is calculated over invoices
 FeatureIsSupportedInInOutModeOnly=Feature only available in CREDITS-DEBTS accountancy mode (See Accountancy module configuration)
 VATReportBuildWithOptionDefinedInModule=Amounts shown here are calculated using rules defined by Tax module setup.
 Param=Setup
+RemainingAmountPayment=Amount payment remaining :
+AmountToBeCharged=Total amount to pay :
 AccountsGeneral=Accounts
 Account=Account
 Accounts=Accounts
diff --git a/htdocs/langs/fr_FR/compta.lang b/htdocs/langs/fr_FR/compta.lang
index f2d91f35f70..1bd9a474680 100644
--- a/htdocs/langs/fr_FR/compta.lang
+++ b/htdocs/langs/fr_FR/compta.lang
@@ -13,6 +13,8 @@ OptionModeVirtualDesc=Dans ce mode, le CA est calculé sur la base des factures
 FeatureIsSupportedInInOutModeOnly=Fonction disponible uniquement en mode compta CREANCES-DETTES (Voir configuration du module compta)
 VATReportBuildWithOptionDefinedInModule=Les montants obtenus sont ceux calculés à partir des règles de calcul paramétrées pour le module Taxes.
 Param=Paramétrage
+RemainingAmountPayment=Montant restant du paiement :
+AmountToBeCharged=Montant total à payer :
 AccountsGeneral=Comptes généraux
 Account=Compte
 Accounts=Comptes
-- 
GitLab