From b9ea7d4d13c5e4995e3118b830c2dd26c78e5de4 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Sat, 29 Nov 2014 17:38:12 +0100
Subject: [PATCH] Fix: Stock decrease from POS

---
 htdocs/cashdesk/admin/cashdesk.php            |  2 -
 htdocs/cashdesk/include/environnement.php     |  1 +
 htdocs/cashdesk/index.php                     |  3 +-
 htdocs/cashdesk/index_verif.php               |  6 +-
 htdocs/cashdesk/validation_verif.php          | 56 ++++++++++++++++++-
 htdocs/compta/facture/class/facture.class.php |  4 +-
 htdocs/langs/en_US/agenda.lang                |  7 ++-
 7 files changed, 65 insertions(+), 14 deletions(-)

diff --git a/htdocs/cashdesk/admin/cashdesk.php b/htdocs/cashdesk/admin/cashdesk.php
index 46e7611b6ed..1ddde37b98b 100644
--- a/htdocs/cashdesk/admin/cashdesk.php
+++ b/htdocs/cashdesk/admin/cashdesk.php
@@ -50,8 +50,6 @@ if (GETPOST('action','alpha') == 'set')
 	$db->begin();
 
 	if (GETPOST('socid','int') < 0) $_POST["socid"]='';
-	/*if (GETPOST("CASHDESK_ID_BANKACCOUNT") < 0)  $_POST["CASHDESK_ID_BANKACCOUNT"]='';
-	if (GETPOST("CASHDESK_ID_WAREHOUSE") < 0)  $_POST["CASHDESK_ID_WAREHOUSE"]='';*/
 
 	$res = dolibarr_set_const($db,"CASHDESK_ID_THIRDPARTY",(GETPOST('socid','int') > 0 ? GETPOST('socid','int') : ''),'chaine',0,'',$conf->entity);
 	$res = dolibarr_set_const($db,"CASHDESK_ID_BANKACCOUNT_CASH",(GETPOST('CASHDESK_ID_BANKACCOUNT_CASH','alpha') > 0 ? GETPOST('CASHDESK_ID_BANKACCOUNT_CASH','alpha') : ''),'chaine',0,'',$conf->entity);
diff --git a/htdocs/cashdesk/include/environnement.php b/htdocs/cashdesk/include/environnement.php
index f0545181ff0..7411b998272 100644
--- a/htdocs/cashdesk/include/environnement.php
+++ b/htdocs/cashdesk/include/environnement.php
@@ -32,6 +32,7 @@ $conf_db_base = $dolibarr_main_db_name;
 $conf_fksoc = (! empty($_SESSION["CASHDESK_ID_THIRDPARTY"]))?$_SESSION["CASHDESK_ID_THIRDPARTY"]:($conf->global->CASHDESK_ID_THIRDPARTY>0?$conf->global->CASHDESK_ID_THIRDPARTY:0);
 // Identifiant unique correspondant a l'entrepot a utiliser
 $conf_fkentrepot = (! empty($_SESSION["CASHDESK_ID_WAREHOUSE"]))?$_SESSION["CASHDESK_ID_WAREHOUSE"]:($conf->global->CASHDESK_ID_WAREHOUSE>0?$conf->global->CASHDESK_ID_WAREHOUSE:0);
+if (! empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $conf_fkentrepot = 0;	// If option to disable stock decrease is on, we set warehouse id to 0.
 
 // Identifiant unique correspondant au compte caisse / liquide
 $conf_fkaccount_cash = (! empty($_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]))?$_SESSION["CASHDESK_ID_BANKACCOUNT_CASH"]:($conf->global->CASHDESK_ID_BANKACCOUNT_CASH>0?$conf->global->CASHDESK_ID_BANKACCOUNT_CASH:0);
diff --git a/htdocs/cashdesk/index.php b/htdocs/cashdesk/index.php
index 26dd0f941ef..fa1c6723d20 100644
--- a/htdocs/cashdesk/index.php
+++ b/htdocs/cashdesk/index.php
@@ -107,8 +107,7 @@ if (! empty($conf->stock->enabled) && empty($conf->global->CASHDESK_NO_DECREASE_
 	print '<td>';
 	$disabled=0;
 	if ($conf->global->CASHDESK_ID_WAREHOUSE > 0) $disabled=1;	// If a particular stock is defined, we disable choice
-	print $formproduct->selectWarehouses((GETPOST('warehouseid')?GETPOST('warehouseid'):(empty($conf->global->CASHDESK_ID_WAREHOUSE)?'ifone':$conf->global->CASHDESK_ID_WAREHOUSE)),'warehouseid','',!$disabled,$disabled);
-	//print '<input name="warehouse_id" class="texte_login" type="warehouse_id" value="" />';
+	print $formproduct->selectWarehouses((GETPOST('warehouseid')?GETPOST('warehouseid','int'):(empty($conf->global->CASHDESK_ID_WAREHOUSE)?'ifone':$conf->global->CASHDESK_ID_WAREHOUSE)),'warehouseid','',!$disabled,$disabled);
 	print '</td>';
 	print "</tr>\n";
 }
diff --git a/htdocs/cashdesk/index_verif.php b/htdocs/cashdesk/index_verif.php
index 3079de5e003..db80866a77f 100644
--- a/htdocs/cashdesk/index_verif.php
+++ b/htdocs/cashdesk/index_verif.php
@@ -117,8 +117,9 @@ if ( $retour >= 0 )
 		$_SESSION['uname'] = $username;
 		$_SESSION['lastname'] = $tab['lastname'];
 		$_SESSION['firstname'] = $tab['firstname'];
-		$_SESSION['CASHDESK_ID_THIRDPARTY'] = $thirdpartyid;
-        $_SESSION['CASHDESK_ID_WAREHOUSE'] = $warehouseid;
+		$_SESSION['CASHDESK_ID_THIRDPARTY'] = ($thirdpartyid > 0 ? $thirdpartyid : '');
+        $_SESSION['CASHDESK_ID_WAREHOUSE'] = ($warehouseid > 0 ? $warehouseid : '');
+        
         $_SESSION['CASHDESK_ID_BANKACCOUNT_CASH'] = ($bankid_cash > 0 ? $bankid_cash : '');
         $_SESSION['CASHDESK_ID_BANKACCOUNT_CHEQUE'] = ($bankid_cheque > 0 ? $bankid_cheque : '');
         $_SESSION['CASHDESK_ID_BANKACCOUNT_CB'] = ($bankid_cb > 0 ? $bankid_cb : '');
@@ -131,7 +132,6 @@ if ( $retour >= 0 )
 	{
 		dol_print_error($db);
 	}
-
 }
 else
 {
diff --git a/htdocs/cashdesk/validation_verif.php b/htdocs/cashdesk/validation_verif.php
index 173c1894555..a03256bfed4 100644
--- a/htdocs/cashdesk/validation_verif.php
+++ b/htdocs/cashdesk/validation_verif.php
@@ -218,7 +218,33 @@ switch ($action)
 			$resultcreate=$invoice->create($user,0,dol_stringtotime($obj_facturation->paiementLe()));
 			if ($resultcreate > 0)
 			{
-				$resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), (isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0));
+				$warehouseidtodecrease=(isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0);
+				if (! empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease=0;	// If a particular stock is defined, we disable choice
+				
+				$resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), 0);
+
+				if ($warehouseidtodecrease > 0)
+				{
+					// Decrease
+					require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
+					$langs->load("agenda");
+					// Loop on each line
+					$cpt=count($invoice->lines);
+					for ($i = 0; $i < $cpt; $i++)
+					{
+						if ($invoice->lines[$i]->fk_product > 0)
+						{
+							$mouvP = new MouvementStock($this->db);
+							$mouvP->origin = &$invoice;
+							// We decrease stock for product
+							if ($invoice->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $invoice->lines[$i]->fk_product, $idwarehouse, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref));
+							else $result=$mouvP->livraison($user, $invoice->lines[$i]->fk_product, $idwarehouse, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref));
+							if ($result < 0) {
+								$error++;
+							}
+						}
+					}
+				}
 			}
 			else
 			{
@@ -232,7 +258,33 @@ switch ($action)
 			$resultcreate=$invoice->create($user,0,0);
 			if ($resultcreate > 0)
 			{
-				$resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), (isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0));
+				$warehouseidtodecrease=(isset($_SESSION["CASHDESK_ID_WAREHOUSE"])?$_SESSION["CASHDESK_ID_WAREHOUSE"]:0);
+				if (! empty($conf->global->CASHDESK_NO_DECREASE_STOCK)) $warehouseidtodecrease=0;	// If a particular stock is defined, we disable choice
+				
+				$resultvalid=$invoice->validate($user, $obj_facturation->numInvoice(), 0);
+
+				if ($warehouseidtodecrease > 0)
+				{
+					// Decrease
+					require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
+					$langs->load("agenda");
+					// Loop on each line
+					$cpt=count($invoice->lines);
+					for ($i = 0; $i < $cpt; $i++)
+					{
+						if ($invoice->lines[$i]->fk_product > 0)
+						{
+							$mouvP = new MouvementStock($this->db);
+							$mouvP->origin = &$invoice;
+							// We decrease stock for product
+							if ($invoice->type == self::TYPE_CREDIT_NOTE) $result=$mouvP->reception($user, $invoice->lines[$i]->fk_product, $idwarehouse, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref));
+							else $result=$mouvP->livraison($user, $invoice->lines[$i]->fk_product, $idwarehouse, $invoice->lines[$i]->qty, $invoice->lines[$i]->subprice, $langs->trans("InvoiceValidatedInDolibarrFromPos",$invoice->newref));
+							if ($result < 0) {
+								$error++;
+							}
+						}
+					}
+				}
 
 				$id = $invoice->id;
 
diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php
index a6877ad9ed8..b924b059bfd 100644
--- a/htdocs/compta/facture/class/facture.class.php
+++ b/htdocs/compta/facture/class/facture.class.php
@@ -1600,7 +1600,7 @@ class Facture extends CommonInvoice
 	 *
 	 * @param	User	$user           Object user that validate
 	 * @param   string	$force_number	Reference to force on invoice
-	 * @param	int		$idwarehouse	Id of warehouse to use for stock decrease
+	 * @param	int		$idwarehouse	Id of warehouse to use for stock decrease if option to decreasenon stock is on (0=no decrease)
 	 * @param	int		$notrigger		1=Does not execute triggers, 0= execuete triggers
      * @return	int						<0 if KO, >0 if OK
 	 */
@@ -1728,7 +1728,7 @@ class Facture extends CommonInvoice
 				$result=$this->client->set_as_client();
 
 				// Si active on decremente le produit principal et ses composants a la validation de facture
-				if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL))
+				if ($this->type != self::TYPE_DEPOSIT && $result >= 0 && ! empty($conf->stock->enabled) && ! empty($conf->global->STOCK_CALCULATE_ON_BILL) && $idwarehouse > 0)
 				{
 					require_once DOL_DOCUMENT_ROOT.'/product/stock/class/mouvementstock.class.php';
 					$langs->load("agenda");
diff --git a/htdocs/langs/en_US/agenda.lang b/htdocs/langs/en_US/agenda.lang
index 45f5017671f..5781d5e3ac0 100644
--- a/htdocs/langs/en_US/agenda.lang
+++ b/htdocs/langs/en_US/agenda.lang
@@ -41,9 +41,10 @@ AutoActions= Automatic filling
 AgendaAutoActionDesc= Define here events for which you want Dolibarr to create automatically an event in agenda. If nothing is checked (by default), only manual actions will be included in agenda.
 AgendaSetupOtherDesc= This page provides options to allow export of your Dolibarr events into an external calendar (thunderbird, google calendar, ...)
 AgendaExtSitesDesc=This page allows to declare external sources of calendars to see their events into Dolibarr agenda.
-ActionsEvents= Events for which Dolibarr will create an action in agenda automatically
-PropalValidatedInDolibarr= Proposal %s validated
-InvoiceValidatedInDolibarr= Invoice %s validated
+ActionsEvents=Events for which Dolibarr will create an action in agenda automatically
+PropalValidatedInDolibarr=Proposal %s validated
+InvoiceValidatedInDolibarr=Invoice %s validated
+InvoiceValidatedInDolibarrFromPos=Invoice %s validated from POS
 InvoiceBackToDraftInDolibarr=Invoice %s go back to draft status
 InvoiceDeleteDolibarr=Invoice %s deleted
 OrderValidatedInDolibarr= Order %s validated
-- 
GitLab