From e79f3715b4cfb5c07071c4edbf773503089ac75b Mon Sep 17 00:00:00 2001
From: Laurent Destailleur <eldy@destailleur.fr>
Date: Sat, 24 Jun 2017 16:21:25 +0200
Subject: [PATCH] FIX #7048 #6075

---
 htdocs/compta/bank/bankentries.php | 161 +++++++++++++++--------------
 1 file changed, 81 insertions(+), 80 deletions(-)

diff --git a/htdocs/compta/bank/bankentries.php b/htdocs/compta/bank/bankentries.php
index 4845012a3e0..c3afc9634cf 100644
--- a/htdocs/compta/bank/bankentries.php
+++ b/htdocs/compta/bank/bankentries.php
@@ -107,7 +107,7 @@ $offset = $limit * $page;
 $pageprev = $page - 1;
 $pagenext = $page + 1;
 if (! $sortorder) $sortorder='ASC';
-if (! $sortfield) $sortfield='b.datev';
+if (! $sortfield) $sortfield='b.datev, b.dateo, b.rowid';
 
 $mode_balance_ok=false;
 //if (($sortfield == 'b.datev' || $sortfield == 'b.datev, b.dateo, b.rowid'))    // TODO Manage balance when account not selected
@@ -194,7 +194,7 @@ if (GETPOST("button_removefilter_x") || GETPOST("button_removefilter.x") || GETP
 	$search_num_releve='';
 	$search_conciliated='';
 	$thirdparty='';
-	
+
 	$account="";
 	if ($id > 0 || ! empty($ref)) $account=$object->id;
 }
@@ -396,18 +396,18 @@ if ($id > 0 || ! empty($ref))
     foreach ($bankcateg->fetchAll() as $bankcategory) {
         $options[$bankcategory->id] = $bankcategory->label;
     }
-    
+
     // Bank card
-    
+
     $head=bank_prepare_head($object);
     dol_fiche_head($head,'journal',$langs->trans("FinancialAccount"),0,'account');
-    
+
     $linkback = '<a href="'.DOL_URL_ROOT.'/compta/bank/index.php">'.$langs->trans("BackToList").'</a>';
-    
+
     dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref, '', 0, '', '', 1);
-    
+
     dol_fiche_end();
- 
+
 
 
     /*
@@ -416,7 +416,7 @@ if ($id > 0 || ! empty($ref))
     if ($action != 'addline' && $action != 'reconcile')
     {
         print '<div class="tabsAction">';
-    
+
         if ($action != 'addline')
         {
             if (empty($conf->global->BANK_DISABLE_DIRECT_INPUT))
@@ -438,7 +438,7 @@ if ($id > 0 || ! empty($ref))
                 print '<a class="butActionRefused" title="'.$langs->trans("NotEnoughPermissions").'" href="#">'.$langs->trans("Conciliate").'</a>';
             }
         }
-    
+
         print '</div>';
     }
 }
@@ -524,10 +524,10 @@ if (($id > 0 || ! empty($ref)) && ((string) $page == ''))
     $offset = $limit * $page;
     if ($page < 0) $page = 0;
 }
-if ($page >= $nbtotalofpages) 
+if ($page >= $nbtotalofpages)
 {
     // If we made a search and result has low page than the page number we were on
-    $page = ($nbtotalofpages -1); 
+    $page = ($nbtotalofpages -1);
     $offset = $limit * $page;
     if ($page < 0) $page = 0;
 }
@@ -550,9 +550,9 @@ if ($resql)
 {
 	$var=True;
 	$num = $db->num_rows($resql);
-	
+
 	$arrayofselected=is_array($toselect)?$toselect:array();
-	
+
     // List of mass actions available
     $arrayofmassactions =  array(
         //'presend'=>$langs->trans("SendByMail"),
@@ -561,16 +561,16 @@ if ($resql)
     //if ($user->rights->bank->supprimer) $arrayofmassactions['delete']=$langs->trans("Delete");
     if ($massaction == 'presend') $arrayofmassactions=array();
     $massactionbutton=$form->selectMassAction('', $arrayofmassactions);
-    
-    
+
+
     // Confirmation delete
     if ($action == 'delete')
     {
         $text=$langs->trans('ConfirmDeleteTransaction');
         print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&rowid='.GETPOST("rowid"), $langs->trans('DeleteTransaction'), $text, 'confirm_delete', null, '', 1);
     }
-    
-    
+
+
     // Lines of title fields
 	print '<form method="post" action="'.$_SERVER["PHP_SELF"].'" name="search_form">'."\n";
 	if ($optioncss != '') print '<input type="hidden" name="optioncss" value="'.$optioncss.'">';
@@ -583,7 +583,7 @@ if ($resql)
 	print '<input type="hidden" name="id" value="'.$id.'">';
 	print '<input type="hidden" name="ref" value="'.$ref.'">';
 	if (GETPOST('bid')) print '<input type="hidden" name="bid" value="'.GETPOST("bid").'">';
-	
+
 	// Form to reconcile
 	if ($user->rights->banque->consolidate && $action == 'reconcile')
 	{
@@ -602,7 +602,7 @@ if ($resql)
 	    print '<input class="button" name="confirm_reconcile" type="submit" value="'.$langs->trans("Conciliate").'">';
 	    print ' '.$langs->trans("or").' ';
 	    print '<input type="submit" name="cancel" class="button" value="'.$langs->trans("Cancel").'">';
-	    
+
 	    // Show last bank statements
 	    $nbmax=15;      // We accept to show last 15 receipts (so we can have more than one year)
 	    $liste="";
@@ -644,7 +644,7 @@ if ($resql)
 	if ($user->rights->banque->modifier && $action == 'addline')
 	{
 	    print load_fiche_titre($langs->trans("AddBankRecordLong"),'','');
-	
+
 	    print '<table class="noborder" width="100%">';
 	    print '<tr class="liste_titre">';
 	    print '<td>'.$langs->trans("Date").'</td>';
@@ -656,7 +656,7 @@ if ($resql)
 	    print '<td align=right>'.$langs->trans("Credit").'</td>';
 	    print '<td colspan="2" align="center">&nbsp;</td>';
 	    print '</tr>';
-	
+
 	    print '<tr '.$bcnd[false].'>';
 	    print '<td class="nowrap" colspan="2">';
 	    $form->select_date(empty($dateop)?-1:$dateop,'op',0,0,0,'transaction');
@@ -680,9 +680,9 @@ if ($resql)
 	    print '</td></tr>';
 	    print '</table>';
 	    print '<br>';
-	}	
-	
-	
+	}
+
+
 	/// ajax to adjust value date with plus and less picto
 	print '
     <script type="text/javascript">
@@ -701,11 +701,11 @@ if ($resql)
     	});
     });
     </script>
-    	
-    ';	
-	
+
+    ';
+
 	$i = 0;
-	
+
 	// Title
 	$bankcateg=new BankCateg($db);
 	$morehtml='<div data-role="fieldcontain">';
@@ -713,7 +713,7 @@ if ($resql)
 	$morehtml.='<input type="text" name="pageplusone" id="pageplusone" size="1" class="flat" value="'.($page+1).'">';
 	$morehtml.='/'.$nbtotalofpages.' ';
 	$morehtml.='</div>';
-	
+
 	$picto='title_bank';
 	if ($id > 0 || ! empty($ref)) $picto='';
 	if (GETPOST("bid"))
@@ -725,13 +725,13 @@ if ($resql)
 	{
 		print_barre_liste($langs->trans("BankTransactions"), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $picto, 0, $morehtml, '', $limit);
 	}
-	
+
 	// We can add page now to param
 	if ($page != '') $param.='&page='.urlencode($page);
-	
-	
+
+
 	$moreforfilter = '';
-	
+
 	$moreforfilter.='<div class="divsearchfield">';
 	$moreforfilter .= $langs->trans('DateOperationShort').' : ';
 	$moreforfilter .= '<div class="nowrap'.($conf->browser->layout=='phone'?' centpercent':'').' inline-block">'.$langs->trans('From') . ' ';
@@ -739,7 +739,7 @@ if ($resql)
 	//$moreforfilter .= ' - ';
 	$moreforfilter .= '<div class="nowrap'.($conf->browser->layout=='phone'?' centpercent':'').' inline-block">'.$langs->trans('to') . ' ' . $form->select_date($search_dt_end, 'search_end_dt', 0, 0, 1, "search_form", 1, 0, 1).'</div>';
 	$moreforfilter .= '</div>';
-	
+
 	$moreforfilter.='<div class="divsearchfield">';
 	$moreforfilter .= $langs->trans('DateValueShort').' : ';
 	$moreforfilter .= '<div class="nowrap'.($conf->browser->layout=='phone'?' centpercent':'').' inline-block">'.$langs->trans('From') . ' ';
@@ -747,25 +747,25 @@ if ($resql)
 	//$moreforfilter .= ' - ';
 	$moreforfilter .= '<div class="nowrap'.($conf->browser->layout=='phone'?' centpercent':'').' inline-block">'.$langs->trans('to') . ' ' . $form->select_date($search_dv_end, 'search_end_dv', 0, 0, 1, "search_form", 1, 0, 1).'</div>';
 	$moreforfilter .= '</div>';
-	
+
 	$parameters=array();
 	$reshook=$hookmanager->executeHooks('printFieldPreListTitle',$parameters);    // Note that $action and $object may have been modified by hook
 	if (empty($reshook)) $moreforfilter .= $hookmanager->resPrint;
 	else $moreforfilter = $hookmanager->resPrint;
-	
-	if ($moreforfilter) 
+
+	if ($moreforfilter)
 	{
 		print '<div class="liste_titre liste_titre_bydiv centpercent">';
 		print $moreforfilter;
 		print '</div>'."\n";
 	}
-	
+
     $varpage=empty($contextpage)?$_SERVER["PHP_SELF"]:$contextpage;
     $selectedfields=$form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage);	// This also change content of $arrayfields
-	
+
     print '<div class="div-table-responsive">';
     print '<table class="tagtable liste'.($moreforfilter?" listwithfilterbefore":"").'">'."\n";
-	
+
 	// Fields title
 	print '<tr class="liste_titre">';
 	if (! empty($arrayfields['b.rowid']['checked']))            print_liste_field_titre($arrayfields['b.rowid']['label'],$_SERVER['PHP_SELF'],'b.rowid','',$param,'',$sortfield,$sortorder);
@@ -784,9 +784,9 @@ if ($resql)
 	// Extra fields
 	if (is_array($extrafields->attribute_label) && count($extrafields->attribute_label))
 	{
-	   foreach($extrafields->attribute_label as $key => $val) 
+	   foreach($extrafields->attribute_label as $key => $val)
 	   {
-           if (! empty($arrayfields["ef.".$key]['checked'])) 
+           if (! empty($arrayfields["ef.".$key]['checked']))
            {
 				$align=$extrafields->getAlignFlag($key);
 				print_liste_field_titre($extralabels[$key],$_SERVER["PHP_SELF"],"ef.".$key,"",$param,($align?'align="'.$align.'"':''),$sortfield,$sortorder);
@@ -802,7 +802,7 @@ if ($resql)
 	print "</tr>\n";
 
 	print '<tr class="liste_titre">';
-	if (! empty($arrayfields['b.rowid']['checked']))            
+	if (! empty($arrayfields['b.rowid']['checked']))
 	{
 	    print '<td class="liste_titre">';
     	print '<input type="text" class="flat" name="search_ref" size="2" value="'.dol_escape_htmltag($search_ref).'">';
@@ -884,25 +884,25 @@ if ($resql)
 
     $balance = 0;    // For balance
 	$balancecalculated = false;
-	
+
 	// Loop on each record
 	$sign = 1;
-	
+
     $totalarray=array();
-    while ($i < min($num,$limit)) 
+    while ($i < min($num,$limit))
     {
         $objp = $db->fetch_object($resql);
 
         // If we are in a situation where we need/can show balance, we calculate the start of balance
         if (! $balancecalculated && ! empty($arrayfields['balance']['checked']) && $mode_balance_ok)
         {
-            if (! $account) 
+            if (! $account)
             {
                 dol_print_error('', 'account is not defined but $mode_balance_ok is true');
                 exit;
             }
-            
-            //Loop on each record
+
+            // Loop on each record before
             $sign = 1;
             $i = 0;
             $sqlforbalance='SELECT SUM(b.amount) as balance';
@@ -912,7 +912,8 @@ if ($resql)
             $sqlforbalance.= " WHERE b.fk_account = ba.rowid";
             $sqlforbalance.= " AND ba.entity IN (".getEntity('bank_account', 1).")";
             $sqlforbalance.= " AND b.fk_account = ".$account;
-            $sqlforbalance.= " AND b.datev < '" . $db->idate($db->jdate($objp->dv)) . "'";
+            //$sqlforbalance.= " AND (b.datev < '" . $db->idate($db->jdate($objp->dv)) . "')";
+            $sqlforbalance.= " AND (b.datev < '" . $db->idate($db->jdate($objp->dv)) . "' OR (b.datev = '" . $db->idate($db->jdate($objp->dv)) . "' AND (b.dateo < '".$db->idate($db->jdate($objp->do))."' OR (b.dateo = '".$db->idate($db->jdate($objp->do))."' AND b.rowid < ".$objp->rowid."))))";
             $resqlforbalance = $db->query($sqlforbalance);
             //print $sqlforbalance;
             if ($resqlforbalance)
@@ -924,12 +925,12 @@ if ($resql)
                 }
             }
             else dol_print_error($db);
-            
+
             $balancecalculated=true;
         }
-        
+
         $balance = price2num($balance + ($sign * $objp->amount),'MT');
-        
+
         if (empty($cachebankaccount[$objp->bankid]))
         {
             $bankaccounttmp = new Account($db);
@@ -941,13 +942,13 @@ if ($resql)
         {
             $bankaccount = $cachebankaccount[$objp->bankid];
         }
-         
+
         $var=!$var;
 
         print "<tr ".$bc[$var].">";
 
         // Ref
-    	if (! empty($arrayfields['b.rowid']['checked']))            
+    	if (! empty($arrayfields['b.rowid']['checked']))
     	{
                 print '<td align="left" class="nowrap">';
                 print "<a href=\"ligne.php?rowid=".$objp->rowid.'">'.img_object($langs->trans("ShowPayment").': '.$objp->rowid, 'account', 'class="classfortooltip"').' '.$objp->rowid."</a> &nbsp; ";
@@ -959,14 +960,14 @@ if ($resql)
     	if (! empty($arrayfields['description']['checked']))
     	{
     	    print "<td>";
-    	
+
     	    //print "<a href=\"ligne.php?rowid=".$objp->rowid."&amp;account=".$objp->fk_account."\">";
     	    $reg=array();
     	    preg_match('/\((.+)\)/i',$objp->label,$reg);	// Si texte entoure de parenthee on tente recherche de traduction
     	    if ($reg[1] && $langs->trans($reg[1])!=$reg[1]) print $langs->trans($reg[1]);
     	    else print dol_trunc($objp->label,40);
     	    //print "</a>&nbsp;";
-    	
+
     	    // Add links after description
     	    $links = $bankaccountstatic->get_url($objp->rowid);
     	    $cachebankaccount=array();
@@ -1054,19 +1055,19 @@ if ($resql)
     	        }
     	        elseif ($links[$key]['type']=='company')
     	        {
-    	            	
+
     	        }
     	        elseif ($links[$key]['type']=='user')
     	        {
-    	            	
+
     	        }
     	        elseif ($links[$key]['type']=='member')
     	        {
-    	            	
+
     	        }
     	        elseif ($links[$key]['type']=='sc')
     	        {
-    	            	
+
     	        }
     	        else
     	        {
@@ -1086,20 +1087,20 @@ if ($resql)
     	            print '</a>';
     	        }
     	    }
-    	    	
+
     	    print '</td>';
     	    if (! $i) $totalarray['nbfield']++;
     	}
-    	
+
         // Date ope
-    	if (! empty($arrayfields['b.dateo']['checked']))            
+    	if (! empty($arrayfields['b.dateo']['checked']))
     	{
     	   print '<td align="center" class="nowrap">'.dol_print_date($db->jdate($objp->do),"day")."</td>\n";
                 if (! $i) $totalarray['nbfield']++;
     	}
 
         // Date value
-    	if (! empty($arrayfields['b.datev']['checked']))            
+    	if (! empty($arrayfields['b.datev']['checked']))
     	{
     	   print '<td align="center" class="nowrap">';
     	   print '<span id="datevalue_'.$objp->rowid.'">'.dol_print_date($db->jdate($objp->dv),"day")."</span>";
@@ -1115,7 +1116,7 @@ if ($resql)
     	}
 
         // Payment type
-    	if (! empty($arrayfields['type']['checked']))            
+    	if (! empty($arrayfields['type']['checked']))
     	{
         	print '<td align="center" class="nowrap">';
 	        $labeltype=($langs->trans("PaymentTypeShort".$objp->fk_type)!="PaymentTypeShort".$objp->fk_type)?$langs->trans("PaymentTypeShort".$objp->fk_type):$langs->getLabelFromKey($db,$objp->fk_type,'c_paiement','code','libelle');
@@ -1131,9 +1132,9 @@ if ($resql)
     	    print '<td class="nowrap" align="center">'.($objp->num_chq?$objp->num_chq:"")."</td>\n";
     	    if (! $i) $totalarray['nbfield']++;
     	}
-    	 
+
 		// Third party
-    	if (! empty($arrayfields['bu.label']['checked']))            
+    	if (! empty($arrayfields['bu.label']['checked']))
     	{
         	print "<td>";
 			if ($objp->url_id)
@@ -1156,16 +1157,16 @@ if ($resql)
 			print '</td>';
             if (! $i) $totalarray['nbfield']++;
     	}
-    	
+
     	// Bank account
-    	if (! empty($arrayfields['ba.ref']['checked']))            
+    	if (! empty($arrayfields['ba.ref']['checked']))
     	{
         	print '<td align="right" class="nowrap">';
 			print $bankaccount->getNomUrl(1);
 			print "</td>\n";
             if (! $i) $totalarray['nbfield']++;
     	}
-    	
+
     	// Debit
     	if (! empty($arrayfields['b.debit']['checked']))
     	{
@@ -1192,7 +1193,7 @@ if ($resql)
     	    if (! $i) $totalarray['nbfield']++;
     	    if (! $i) $totalarray['totalcredfield']=$totalarray['nbfield'];
     	}
-    	 
+
     	// Balance
     	if (! empty($arrayfields['balance']['checked']))
     	{
@@ -1212,7 +1213,7 @@ if ($resql)
         	    print '<td align="right">-</td>';
         	}
     	}
-    	
+
     	if (! empty($arrayfields['b.num_releve']['checked']))
     	{
             print '<td class="nowrap" align="center">';
@@ -1224,7 +1225,7 @@ if ($resql)
             	    print '<a href="releve.php?num='.$objp->num_releve.'&amp;account='.$objp->bankid.'">'.$objp->num_releve.'</a>';
             	}
             	else if ($action == 'reconcile')
-            	{ 
+            	{
             	    print '<input class="flat" name="rowid['.$objp->rowid.']" type="checkbox" value="'.$objp->rowid.'" size="1"'.(! empty($_POST['rowid'][$objp->rowid])?' checked':'').'>';
             	}
         	}
@@ -1239,7 +1240,7 @@ if ($resql)
         	print '</td>';
             if (! $i) $totalarray['nbfield']++;
     	}
-    	
+
     	// Action edit/delete
     	print '<td class="nowrap" align="center">';
     	// Transaction reconciliated or edit link
@@ -1279,8 +1280,8 @@ if ($resql)
     	    }
     	}
     	print '</td>';
-    	if (! $i) $totalarray['nbfield']++;    	
-    	
+    	if (! $i) $totalarray['nbfield']++;
+
     	// Action column
     	print '<td class="nowrap" align="center">';
     	if ($massactionbutton || $massaction)   // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
@@ -1296,7 +1297,7 @@ if ($resql)
 
 		$i++;
 	}
-	
+
 	// Show total line
 	if (isset($totalarray['totaldebfield']) || isset($totalarray['totalcredfield']))
 	{
@@ -1319,7 +1320,7 @@ if ($resql)
 
 	print "</table>";
 	print "</div>";
-	
+
     print '</form>';
 	$db->free($resql);
 }
-- 
GitLab