From 570e4391a578e6df9a263daff144977fec28b057 Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Fri, 19 Apr 2013 14:51:39 +0200
Subject: [PATCH] Fix: Box with product out of stocks for pgsql

---
 .../core/boxes/box_produits_alerte_stock.php  |  16 ++-
 htdocs/core/class/html.formother.class.php    | 107 ++++++++----------
 .../install/mysql/tables/llx_product.key.sql  |   3 +-
 3 files changed, 62 insertions(+), 64 deletions(-)

diff --git a/htdocs/core/boxes/box_produits_alerte_stock.php b/htdocs/core/boxes/box_produits_alerte_stock.php
index 41070298cac..57c2cc4de4c 100644
--- a/htdocs/core/boxes/box_produits_alerte_stock.php
+++ b/htdocs/core/boxes/box_produits_alerte_stock.php
@@ -64,20 +64,23 @@ class box_produits_alerte_stock extends ModeleBoxes
 
 		if ($user->rights->produit->lire || $user->rights->service->lire)
 		{
-			$sql = "SELECT p.rowid, p.label, p.price, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte, s.reel";
+			$sql = "SELECT p.rowid, p.label, p.price, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte,";
+			$sql.= " SUM(".$db->ifsql("s.reel IS NULL","0","s.reel").") as total_stock";
 			$sql.= " FROM ".MAIN_DB_PREFIX."product as p";
 			$sql.= " LEFT JOIN ".MAIN_DB_PREFIX."product_stock as s on p.rowid = s.fk_product";
 			$sql.= ' WHERE p.entity IN ('.getEntity($productstatic->element, 1).')';
-			$sql.= " AND p.tosell = 1";
+			$sql.= " AND p.tosell = 1 AND p.seuil_stock_alerte > 0";
 			if (empty($user->rights->produit->lire)) $sql.=' AND p.fk_product_type != 0';
 			if (empty($user->rights->service->lire)) $sql.=' AND p.fk_product_type != 1';
-			$sql.= " HAVING s.reel < p.seuil_stock_alerte";
-			$sql.= $db->order('s.reel', 'DESC');
+			$sql.= " GROUP BY p.rowid, p.label, p.price, p.price_base_type, p.price_ttc, p.fk_product_type, p.tms, p.tosell, p.tobuy, p.seuil_stock_alerte";
+			$sql.= " HAVING SUM(".$db->ifsql("s.reel IS NULL","0","s.reel").") < p.seuil_stock_alerte";
+			$sql.= $db->order('p.seuil_stock_alerte', 'DESC');
 			$sql.= $db->plimit($max, 0);
 
 			$result = $db->query($sql);
 			if ($result)
 			{
+				$langs->load("stocks");
 				$num = $db->num_rows($result);
 				$i = 0;
 				while ($i < $num)
@@ -128,7 +131,8 @@ class box_produits_alerte_stock extends ModeleBoxes
                     'text' => $price_base_type);
 
 					$this->info_box_contents[$i][4] = array('td' => 'align="center"',
-                    'text' => $objp->reel . ' / '.$objp->seuil_stock_alerte);
+                    'text' => $objp->total_stock . ' / '.$objp->seuil_stock_alerte,
+					'text2'=>img_warning($langs->transnoentitiesnoconv("StockLowerThanLimit")));
 
 					$this->info_box_contents[$i][5] = array('td' => 'align="right" width="18"',
                     'text' => $productstatic->LibStatut($objp->tosell,3,0));
@@ -138,7 +142,7 @@ class box_produits_alerte_stock extends ModeleBoxes
 
                     $i++;
 				}
-				if ($num==0) $this->info_box_contents[$i][0] = array('td' => 'align="center"','text'=>$langs->trans("NoRecordedProducts"));
+				if ($num==0) $this->info_box_contents[$i][0] = array('td' => 'align="center"','text'=>$langs->trans("NoTooLowStockProducts"));
 			}
 			else
 			{
diff --git a/htdocs/core/class/html.formother.class.php b/htdocs/core/class/html.formother.class.php
index 3de291bbe76..8a964c9d846 100644
--- a/htdocs/core/class/html.formother.class.php
+++ b/htdocs/core/class/html.formother.class.php
@@ -893,9 +893,34 @@ class FormOther
             $selectboxlist=$form->selectarray('boxcombo', $arrayboxtoactivatelabel,'',1);
         }
 
+        // Javascript code for dynamic actions
         if (! empty($conf->use_javascript_ajax))
         {
 	        print '<script type="text/javascript" language="javascript">
+	        
+	        // To update list of activated boxes
+	        function updateBoxOrder(closing) {
+	        	var left_list = cleanSerialize(jQuery("#left").sortable("serialize"));
+	        	var right_list = cleanSerialize(jQuery("#right").sortable("serialize"));
+	        	var boxorder = \'A:\' + left_list + \'-B:\' + right_list;
+	        	if (boxorder==\'A:A-B:B\' && closing == 1)	// There is no more boxes on screen, and we are after a delete of a box so we must hide title
+	        	{
+	        		jQuery.ajax({
+	        			url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&zone='.$areacode.'&userid=\'+'.$user->id.',
+	        			async: false
+	        		});
+	        		// We force reload to be sure to get all boxes into list
+	        		window.location.search=\'mainmenu='.GETPOST("mainmenu").'&leftmenu='.GETPOST('leftmenu').'&action=delbox\';
+	        	}
+	        	else
+	        	{
+	        		jQuery.ajax({
+	        			url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&zone='.$areacode.'&userid=\'+'.$user->id.',
+	        			async: true
+	        		});
+	        	}
+	        }
+	        
 	        jQuery(document).ready(function() {
 	        	jQuery("#boxcombo").change(function() {
 	        	var boxid=jQuery("#boxcombo").val();
@@ -910,10 +935,31 @@ class FormOther
 	        			window.location.search=\'mainmenu='.GETPOST("mainmenu").'&leftmenu='.GETPOST('leftmenu').'&action=addbox&boxid=\'+boxid;
 	                }
 	        	});';
-	        if (! count($arrayboxtoactivatelabel)) print 'jQuery("#boxcombo").hide();';
-	        print  '
-	    	});
-	        </script>';
+	        	if (! count($arrayboxtoactivatelabel)) print 'jQuery("#boxcombo").hide();';
+	        	print  '
+	    	
+	        	jQuery("#left, #right").sortable({
+		        	/* placeholder: \'ui-state-highlight\', */
+	    	    	handle: \'.boxhandle\',
+	    	    	revert: \'invalid\',
+	       			items: \'.box\',
+	        		containment: \'.fiche\',
+	        		connectWith: \'.connectedSortable\',
+	        		stop: function(event, ui) {
+	        			updateBoxOrder(0);
+	        		}
+	    		});
+
+	        	jQuery(".boxclose").click(function() {
+	        		var self = this;	// because JQuery can modify this
+	        		var boxid=self.id.substring(8);
+	        		jQuery(\'#boxto_\'+boxid).remove();
+	        		updateBoxOrder(1);
+	        	});
+	        
+        	});'."\n";
+	        
+	        print '</script>'."\n";
         }
 
         $nbboxactivated=count($boxidactivatedforuser);
@@ -996,59 +1042,6 @@ class FormOther
 
             print "</td></tr>";
             print "</table>";
-
-            if ($conf->use_javascript_ajax)
-            {
-                print "\n";
-                print '<script type="text/javascript" language="javascript">';
-                // For moving
-                print 'jQuery(function() {
-                            jQuery("#left, #right").sortable({
-                                /* placeholder: \'ui-state-highlight\', */
-                                handle: \'.boxhandle\',
-                                revert: \'invalid\',
-                                items: \'.box\',
-                                containment: \'.fiche\',
-                                connectWith: \'.connectedSortable\',
-                                stop: function(event, ui) {
-                                    updateBoxOrder(0);
-                                }
-                            });
-                        });
-                '."\n";
-                // To update list of activated boxes
-                print 'function updateBoxOrder(closing) {
-	                		var left_list = cleanSerialize(jQuery("#left").sortable("serialize"));
-	                		var right_list = cleanSerialize(jQuery("#right").sortable("serialize"));
-	                		var boxorder = \'A:\' + left_list + \'-B:\' + right_list;
-	    					if (boxorder==\'A:A-B:B\' && closing == 1)	// There is no more boxes on screen, and we are after a delete of a box so we must hide title
-	    					{
-		    					jQuery.ajax({
-		    						url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&zone='.$areacode.'&userid=\'+'.$user->id.',
-		    						async: false
-		    					});
-	    						// We force reload to be sure to get all boxes into list
-			        			window.location.search=\'mainmenu='.GETPOST("mainmenu").'&leftmenu='.GETPOST('leftmenu').'&action=delbox\';
-	    					}
-	    					else
-	    					{
-	    						jQuery.ajax({
-		    						url: \''.DOL_URL_ROOT.'/core/ajax/box.php?boxorder=\'+boxorder+\'&zone='.$areacode.'&userid=\'+'.$user->id.',
-		    						async: true
-		    					});
-	    					}
-                		}'."\n";
-                // For closing
-                print 'jQuery(document).ready(function() {
-                          	jQuery(".boxclose").click(function() {
-                          		var self = this;	// because JQuery can modify this
-                              	var boxid=self.id.substring(8);
-                                jQuery(\'#boxto_\'+boxid).remove();
-                                updateBoxOrder(1);
-                           	});
-                       });'."\n";
-                print '</script>'."\n";
-            }
         }
 
         return count($boxactivated);
diff --git a/htdocs/install/mysql/tables/llx_product.key.sql b/htdocs/install/mysql/tables/llx_product.key.sql
index 06ad7ce2f0a..1500cfba762 100644
--- a/htdocs/install/mysql/tables/llx_product.key.sql
+++ b/htdocs/install/mysql/tables/llx_product.key.sql
@@ -1,6 +1,6 @@
 -- ============================================================================
 -- Copyright (C) 2002-2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
--- Copyright (C) 2004-2005 Laurent Destailleur  <eldy@users.sourceforge.net>
+-- Copyright (C) 2004-2013 Laurent Destailleur  <eldy@users.sourceforge.net>
 -- Copyright (C) 2005-2009 Regis Houssin        <regis.houssin@capnetworks.com>
 --
 -- This program is free software; you can redistribute it and/or modify
@@ -24,3 +24,4 @@ ALTER TABLE llx_product ADD UNIQUE INDEX uk_product_ref (ref, entity);
 ALTER TABLE llx_product ADD INDEX idx_product_label (label);
 ALTER TABLE llx_product ADD INDEX idx_product_barcode (barcode);
 ALTER TABLE llx_product ADD INDEX idx_product_import_key (import_key);
+ALTER TABLE llx_product ADD INDEX idx_product_seuil_stock_alerte (seuil_stock_alerte);
-- 
GitLab