Browse Source

Merge branch '12.0' of git@github.com:Dolibarr/dolibarr.git into develop

Conflicts:
	htdocs/compta/prelevement/class/bonprelevement.class.php
	htdocs/core/class/evalmath.class.php
	htdocs/core/class/extrafields.class.php
	htdocs/install/mysql/migration/11.0.0-12.0.0.sql
	htdocs/langs/en_US/cashdesk.lang
	htdocs/societe/class/societe.class.php
Laurent Destailleur 5 years ago
parent
commit
83eaddb17b

+ 7 - 8
ChangeLog

@@ -115,8 +115,8 @@ NEW: class tool for converting units
 NEW: Close #13011 Add button create thirdparty when creating intervention
 NEW: Colorful theme for TakePOS
 NEW: columns units in product list
-NEW: compatibility of translabel with more dict
-NEW: Confirm file delete on fracture card
+NEW: compatibility of translabel with more dictionaries
+NEW: Confirm file delete on invoice card
 NEW: "contact_civility" for ODT templates
 NEW: CUPS printing compatibility for TakePOS
 NEW: Customer command list - Add date start & date end
@@ -124,16 +124,11 @@ NEW: display weight in shipment list
 NEW: Documentation about PHP support in Dolibarr
 NEW: Donation - Update FR CERFA to 11580*04
 NEW: Easier way to setup the different types of tax. Better visibility.
-NEW: enable put for agendaevents api
 NEW: Expedition list - Add date start & date end
 NEW: Experiment supplier packaging with option PRODUCT_USE_SUPPLIER_PACKAGING: Using price according to the minimum quantity
 NEW: Export module, add extrafields for Contract and Contract line
 NEW: Extend retained warranty to be  available for all invoices
-NEW: filter by product on supplier order API
 NEW: French new regions
-NEW: get documents for categories with RESP API
-NEW: get proposal by ref with API
-NEW: Hidden option MAIN_TEMP_DIR
 NEW: hook and data id
 NEW: hook on ics generation to add more events in eventarray
 NEW: hook on product load stats
@@ -206,7 +201,6 @@ NEW: API filter bankaccounts by category
 NEW: API filter contacts by category
 NEW: API filter members by category
 NEW: API filter projects by category
-NEW: API filter thirdpartie by category
 NEW: API filter thirdparty by category
 NEW: API filter user by category
 NEW: API filter warehouses by categorie
@@ -220,6 +214,11 @@ NEW: Bookkeeping by account - Add selectfields & hook
 NEW: Can force position of legend of graph on right (instead of top)
 NEW: Can change destination of "Back to list" using a "backtolist" parameter
 NEW: add more category types from hook
+NEW: enable put for agendaevents api
+NEW: filter by product on supplier order API
+NEW: get documents for categories with RESP API
+NEW: get proposal by ref with API
+NEW: Hidden option MAIN_TEMP_DIR
 
 WARNING:
 

+ 1 - 1
htdocs/comm/card.php

@@ -934,7 +934,7 @@ if ($object->id > 0)
 				$late = '';
 				foreach ($contrat->lines as $line) {
 					if ($contrat->statut == Contrat::STATUS_VALIDATED && $line->statut == ContratLigne::STATUS_OPEN) {
-						if (($line->date_fin_validite + $conf->contrat->services->expires->warning_delay) < $now) $late = img_warning($langs->trans("Late"));
+						if (((!empty($line->date_fin_validite)?$line->date_fin_validite:0) + $conf->contrat->services->expires->warning_delay) < $now) $late = img_warning($langs->trans("Late"));
 					}
 				}
 

+ 7 - 8
htdocs/comm/propal/card.php

@@ -192,7 +192,7 @@ if (empty($reshook))
 					}
 				}
 
-				$result = $object->createFromClone($user, $socid);
+				$result = $object->createFromClone($user, $socid, (GETPOSTISSET('entity') ? GETPOST('entity', 'int') : null));
 				if ($result > 0) {
 					header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
 					exit();
@@ -1750,10 +1750,9 @@ if ($action == 'create')
 
 		print '<tr><td class="tdtop"><input type="radio" name="createmode" value="empty" checked></td>';
 		print '<td valign="top" colspan="2">'.$langs->trans("CreateEmptyPropal").'</td></tr>';
+		print '</table>';
 	}
 
-	if (!empty($conf->global->PROPAL_CLONE_ON_CREATE_PAGE)) print '</table>';
-
 	dol_fiche_end();
 
 	$langs->load("bills");
@@ -1796,11 +1795,11 @@ if ($action == 'create')
 	if ($action == 'clone') {
 		// Create an array for form
 		$formquestion = array(
-							// 'text' => $langs->trans("ConfirmClone"),
-							// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
-							// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' =>
-							// 1),
-							array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)')));
+			// 'text' => $langs->trans("ConfirmClone"),
+			// array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1),
+			// array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1),
+			array('type' => 'other', 'name' => 'socid', 'label' => $langs->trans("SelectThirdParty"), 'value' => $form->select_company(GETPOST('socid', 'int'), 'socid', '(s.client=1 OR s.client=2 OR s.client=3)'))
+		);
 		if (!empty($conf->global->PROPAL_CLONE_DATE_DELIVERY) && !empty($object->date_livraison)) {
 			$formquestion[] = array('type' => 'date', 'name' => 'date_delivery', 'label' => $langs->trans("DeliveryDate"), 'value' => $object->date_livraison);
 		}

+ 3 - 1
htdocs/comm/propal/class/propal.class.php

@@ -1289,9 +1289,10 @@ class Propal extends CommonObject
 	 *
 	 *      @param	    User	$user		    User making the clone
 	 *		@param		int		$socid			Id of thirdparty
+	 *		@param		int		$forceentity	Entity id to force
 	 * 	 	@return		int						New id of clone
 	 */
-    public function createFromClone(User $user, $socid = 0)
+	public function createFromClone(User $user, $socid = 0, $forceentity = null)
 	{
 		global $conf, $hookmanager;
 
@@ -1345,6 +1346,7 @@ class Propal extends CommonObject
 
 		$object->id = 0;
 		$object->ref = '';
+		$object->entity = (! empty($forceentity) ? $forceentity : $object->entity);
 		$object->statut = self::STATUS_DRAFT;
 
 		// Clear fields

+ 1 - 1
htdocs/compta/facture/card.php

@@ -1417,7 +1417,7 @@ if (empty($reshook))
 						$result = $srcobject->fetch($object->origin_id);
 
 						$typeamount = GETPOST('typedeposit', 'aZ09');
-						$valuedeposit = GETPOST('valuedeposit', 'int');
+						$valuedeposit = price2num(GETPOST('valuedeposit', 'alpha'), 'MU');
 
 						// If deposit invoice
 						if ($_POST['type'] == Facture::TYPE_DEPOSIT && in_array($typeamount, array('amount', 'variable')))

+ 52 - 24
htdocs/compta/facture/prelevement.php

@@ -48,13 +48,12 @@ $ref = GETPOST('ref', 'alpha');
 $socid = GETPOST('socid', 'int');
 $action = GETPOST('action', 'alpha');
 $type = GETPOST('type', 'aZ09');
-$mode = GETPOST('mode', 'aZ09');
 
 $fieldid = (!empty($ref) ? 'ref' : 'rowid');
 if ($user->socid) $socid = $user->socid;
 $result = restrictedArea($user, 'facture', $id, '', '', 'fk_soc', $fieldid);
 
-if ($mode == 'bank-transfer') {
+if ($type == 'bank-transfer') {
 	$object = new FactureFournisseur($db);
 } else {
 	$object = new Facture($db);
@@ -94,6 +93,7 @@ if (empty($reshook))
             $sourcetype = 'facture';
             if ($type == 'bank-transfer') {
             	$sourcetype = 'supplier_invoice';
+            	$newtype = 'bank-transfer';
             }
 
             $result = $object->demande_prelevement($user, price2num(GETPOST('withdraw_request_amount', 'alpha')), $newtype, $sourcetype);
@@ -117,7 +117,7 @@ if (empty($reshook))
             $result = $object->demande_prelevement_delete($user, GETPOST('did', 'int'));
             if ($result == 0)
             {
-                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id.'&mode='.$mode);
+                header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id.'&type='.$type);
                 exit;
             }
         }
@@ -133,7 +133,7 @@ $form = new Form($db);
 
 $now = dol_now();
 
-if ($mode == 'bank-transfer') {
+if ($type == 'bank-transfer') {
 	$title = $langs->trans('InvoiceSupplier')." - ".$langs->trans('CreditTransfer');
 	$helpurl = "";
 } else {
@@ -168,7 +168,7 @@ if ($object->id > 0)
 	if ($object->paye) $resteapayer = 0;
 	$resteapayeraffiche = $resteapayer;
 
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		if (!empty($conf->global->FACTURE_DEPOSITS_ARE_JUST_PAYMENTS)) {	// Never use this
 			$filterabsolutediscount = "fk_invoice_supplier_source IS NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
 			$filtercreditnote = "fk_invoice_supplier_source IS NOT NULL"; // If we want deposit to be substracted to payments only and not to total of final invoice
@@ -202,7 +202,7 @@ if ($object->id > 0)
 		$author->fetch($object->user_author);
 	}
 
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		$head = facturefourn_prepare_head($object);
 	} else {
 		$head = facture_prepare_head($object);
@@ -211,7 +211,7 @@ if ($object->id > 0)
 	dol_fiche_head($head, 'standingorders', $title, -1, 'bill');
 
 	// Invoice content
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		$linkback = '<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
 	} else {
 		$linkback = '<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?restore_lastsearch_values=1'.(!empty($socid) ? '&socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
@@ -219,7 +219,7 @@ if ($object->id > 0)
 
 	$morehtmlref = '<div class="refidno">';
 	// Ref customer
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		$morehtmlref .= $form->editfieldkey("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', 0, 1);
 		$morehtmlref .= $form->editfieldval("RefSupplier", 'ref_supplier', $object->ref_supplier, $object, 0, 'string', '', null, null, '', 1);
 	} else {
@@ -228,7 +228,7 @@ if ($object->id > 0)
 	}
 	// Thirdparty
 	$morehtmlref .= '<br>'.$langs->trans('ThirdParty').' : '.$object->thirdparty->getNomUrl(1);
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/fourn/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
 	} else {
 		if (empty($conf->global->MAIN_DISABLE_OTHER_LINK) && $object->thirdparty->id > 0) $morehtmlref .= ' (<a href="'.DOL_URL_ROOT.'/compta/facture/list.php?socid='.$object->thirdparty->id.'&search_company='.urlencode($object->thirdparty->name).'">'.$langs->trans("OtherBills").'</a>)';
@@ -288,7 +288,7 @@ if ($object->id > 0)
 	}
 	if ($object->type == $object::TYPE_REPLACEMENT)
 	{
-		if ($mode == 'bank-transfer') {
+		if ($type == 'bank-transfer') {
 			$facreplaced = new FactureFournisseur($db);
 		} else {
 			$facreplaced = new Facture($db);
@@ -298,7 +298,7 @@ if ($object->id > 0)
 	}
 	if ($object->type == $object::TYPE_CREDIT_NOTE)
 	{
-		if ($mode == 'bank-transfer') {
+		if ($type == 'bank-transfer') {
 			$facusing = new FactureFournisseur($db);
 		} else {
 			$facusing = new Facture($db);
@@ -316,7 +316,7 @@ if ($object->id > 0)
 		{
 			if ($i == 0) print ' ';
 			else print ',';
-			if ($mode == 'bank-transfer') {
+			if ($type == 'bank-transfer') {
 				$facavoir = new FactureFournisseur($db);
 			} else {
 				$facavoir = new Facture($db);
@@ -339,7 +339,7 @@ if ($object->id > 0)
 	// Discounts
 	print '<tr><td>'.$langs->trans('Discounts').'</td><td colspan="3">';
 
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		//$societe = new Fournisseur($db);
 		//$result = $societe->fetch($object->socid);
 		$thirdparty = $object->thirdparty;
@@ -355,7 +355,7 @@ if ($object->id > 0)
 	print '</td></tr>';
 
 	// Label
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		print '<tr>';
 		print '<td>'.$form->editfieldkey("Label", 'label', $object->label, $object, 0).'</td>';
 		print '<td>'.$form->editfieldval("Label", 'label', $object->label, $object, 0).'</td>';
@@ -417,7 +417,7 @@ if ($object->id > 0)
 	if ($object->type != $object::TYPE_CREDIT_NOTE)
 	{
 		$duedate = $object->date_lim_reglement;
-		if ($mode == 'bank-transfer') {
+		if ($type == 'bank-transfer') {
 			$duedate = $object->date_echeance;
 		}
 
@@ -470,7 +470,7 @@ if ($object->id > 0)
 	print '</tr>';
 
 	$title = 'CustomerIBAN';
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		$title = 'SupplierIBAN';
 	}
 	print '<tr><td>'.$langs->trans($title).'</td><td colspan="3">';
@@ -627,7 +627,7 @@ if ($object->id > 0)
 	print "\n<div class=\"tabsAction\">\n";
 
 	$buttonlabel = $langs->trans("MakeWithdrawRequest");
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		$buttonlabel = $langs->trans("MakeBankTransferOrder");
 	}
 
@@ -643,6 +643,7 @@ if ($object->id > 0)
     			print '<form method="POST" action="">';
     			print '<input type="hidden" name="token" value="'.newToken().'" />';
     			print '<input type="hidden" name="id" value="'.$object->id.'" />';
+    			print '<input type="hidden" name="type" value="'.$type.'" />';
     			print '<input type="hidden" name="action" value="new" />';
     			print '<label for="withdraw_request_amount">'.$langs->trans('BankTransferAmount').' </label>';
     			print '<input type="text" id="withdraw_request_amount" name="withdraw_request_amount" value="'.$remaintopaylesspendingdebit.'" size="9" />';
@@ -667,7 +668,7 @@ if ($object->id > 0)
 	print "</div><br>\n";
 
 
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		print '<div class="opacitymedium">'.$langs->trans("DoCreditTransferBeforePayments").'</div><br>';
 	} else {
 		print '<div class="opacitymedium">'.$langs->trans("DoStandingOrdersBeforePayments").'</div><br>';
@@ -684,7 +685,7 @@ if ($object->id > 0)
 	print '<td class="left">'.$langs->trans("DateRequest").'</td>';
 	print '<td class="center">'.$langs->trans("User").'</td>';
 	print '<td class="center">'.$langs->trans("Amount").'</td>';
-	if ($mode == 'bank-transfer') {
+	if ($type == 'bank-transfer') {
 		print '<td class="center">'.$langs->trans("BankTransferReceipt").'</td>';
 	} else {
 		print '<td class="center">'.$langs->trans("WithdrawalReceipt").'</td>';
@@ -696,7 +697,7 @@ if ($object->id > 0)
 
 	$sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande as date_demande,";
 	$sql .= " pfd.date_traite as date_traite, pfd.amount,";
-	$sql .= " u.rowid as user_id, u.lastname, u.firstname, u.login";
+	$sql .= " u.rowid as user_id, u.email, u.lastname, u.firstname, u.login, u.statut as user_status";
 	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on pfd.fk_user_demande = u.rowid";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb ON pb.rowid = pfd.fk_prelevement_bons";
@@ -716,14 +717,29 @@ if ($object->id > 0)
 	{
 		$i = 0;
 
+		$tmpuser = new User($db);
+
 		$num = $db->num_rows($result);
 		while ($i < $num)
 		{
 			$obj = $db->fetch_object($result_sql);
 
+			$tmpuser->id = $obj->user_id;
+			$tmpuser->login = $obj->login;
+			$tmpuser->ref = $obj->login;
+			$tmpuser->email = $obj->email;
+			$tmpuser->lastname = $obj->lastname;
+			$tmpuser->firstname = $obj->firstname;
+			$tmpuser->statut = $obj->user_status;
+
 			print '<tr class="oddeven">';
+
 			print '<td class="left">'.dol_print_date($db->jdate($obj->date_demande), 'dayhour')."</td>\n";
-			print '<td align="center"><a href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->user_id.'">'.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.'</a></td>';
+
+			print '<td align="center">';
+			print $tmpuser->getNomUrl(1, '', 0, 0, 0, 0, 'login');
+			print '</td>';
+
 			print '<td class="center">'.price($obj->amount).'</td>';
 			print '<td align="center">-</td>';
 			print '<td>&nbsp;</td>';
@@ -731,7 +747,7 @@ if ($object->id > 0)
 			print '<td class="center">'.$langs->trans("OrderWaiting").'</td>';
 
 			print '<td class="right">';
-			print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete&did='.$obj->rowid.'&mode='.$mode.'">';
+			print '<a href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&action=delete&did='.$obj->rowid.'&type='.$type.'">';
 			print img_delete();
 			print '</a></td>';
 
@@ -749,7 +765,7 @@ if ($object->id > 0)
 
 	$sql = "SELECT pfd.rowid, pfd.traite, pfd.date_demande, pfd.date_traite, pfd.fk_prelevement_bons, pfd.amount,";
 	$sql .= " pb.ref,";
-	$sql .= " u.rowid as user_id, u.lastname, u.firstname, u.login";
+	$sql .= " u.rowid as user_id, u.email, u.lastname, u.firstname, u.login, u.statut as user_status";
 	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."user as u on pfd.fk_user_demande = u.rowid";
 	$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."prelevement_bons as pb ON pb.rowid = pfd.fk_prelevement_bons";
@@ -769,15 +785,27 @@ if ($object->id > 0)
 		$numclosed = $num;
 		$i = 0;
 
+		$tmpuser = new User($db);
+
 		while ($i < $num)
 		{
 			$obj = $db->fetch_object($result);
 
+			$tmpuser->id = $obj->user_id;
+			$tmpuser->login = $obj->login;
+			$tmpuser->ref = $obj->login;
+			$tmpuser->email = $obj->email;
+			$tmpuser->lastname = $obj->lastname;
+			$tmpuser->firstname = $obj->firstname;
+			$tmpuser->statut = $obj->user_status;
+
 			print '<tr class="oddeven">';
 
 			print '<td class="left">'.dol_print_date($db->jdate($obj->date_demande), 'day')."</td>\n";
 
-			print '<td align="center"><a href="'.DOL_URL_ROOT.'/user/card.php?id='.$obj->user_id.'">'.img_object($langs->trans("ShowUser"), 'user').' '.$obj->login.'</a></td>';
+			print '<td align="center">';
+			print $tmpuser->getNomUrl(1, '', 0, 0, 0, 0, 'login');
+			print '</td>';
 
 			print '<td class="center">'.price($obj->amount).'</td>';
 

+ 12 - 8
htdocs/compta/paymentbybanktransfer/index.php

@@ -94,11 +94,11 @@ print '</td></tr></table></div><br>';
  */
 $sql = "SELECT f.ref, f.rowid, f.total_ttc, f.fk_statut, f.paye, f.type,";
 $sql .= " pfd.date_demande, pfd.amount,";
-$sql .= " s.nom as name, s.rowid as socid";
-$sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
+$sql .= " s.nom as name, s.email, s.rowid as socid";
+$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f,";
 $sql .= " ".MAIN_DB_PREFIX."societe as s";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
-$sql .= " , ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
+$sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
 $sql .= " WHERE s.rowid = f.fk_soc";
 $sql .= " AND f.entity IN (".getEntity('supplier_invoice').")";
 $sql .= " AND f.total_ttc > 0";
@@ -106,7 +106,9 @@ if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS))
 {
 	$sql .= " AND f.fk_statut = ".FactureFournisseur::STATUS_VALIDATED;
 }
-$sql .= " AND pfd.traite = 0 AND pfd.fk_facture_fourn = f.rowid";
+$sql .= " AND pfd.traite = 0";
+$sql .= " AND pfd.ext_payment_id IS NULL";
+$sql .= " AND pfd.fk_facture_fourn = f.rowid";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
 if ($socid) $sql .= " AND f.fk_soc = ".$socid;
 
@@ -133,14 +135,15 @@ if ($resql)
             $invoicestatic->type = $obj->type;
             $alreadypayed = $invoicestatic->getSommePaiement();
 
+            $thirdpartystatic->id = $obj->socid;
+            $thirdpartystatic->name = $obj->name;
+            $thirdpartystatic->email = $obj->email;
 
             print '<tr class="oddeven"><td>';
             print $invoicestatic->getNomUrl(1, 'withdraw');
             print '</td>';
 
             print '<td>';
-            $thirdpartystatic->id = $obj->socid;
-            $thirdpartystatic->name = $obj->name;
             print $thirdpartystatic->getNomUrl(1, 'customer');
             print '</td>';
 
@@ -190,7 +193,8 @@ if ($result)
     print"\n<!-- debut table -->\n";
     print '<div class="div-table-responsive-no-min">';
     print '<table class="noborder centpercent">';
-    print '<tr class="liste_titre"><th>'.$langs->trans("LatestBankTransferReceipts", $limit).'</th>';
+    print '<tr class="liste_titre">';
+    print '<th>'.$langs->trans("LatestBankTransferReceipts", $limit).'</th>';
     print '<th>'.$langs->trans("Date").'</th>';
     print '<th class="right">'.$langs->trans("Amount").'</th>';
     print '<th class="right">'.$langs->trans("Status").'</th>';
@@ -217,7 +221,7 @@ if ($result)
 	        $i++;
 	    }
     } else {
-    	print '<tr><td class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+    	print '<tr><td class="opacitymedium" colspan="4">'.$langs->trans("None").'</td></tr>';
     }
 
     print "</table></div><br>";

+ 282 - 183
htdocs/compta/prelevement/class/bonprelevement.class.php

@@ -28,6 +28,7 @@
 
 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
+require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
 require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
@@ -118,7 +119,7 @@ class BonPrelevement extends CommonObject
 	/**
 	 * Add invoice to withdrawal
 	 *
-	 * @param	int		$facture_id 	id invoice to add
+	 * @param	int		$invoice_id 	id invoice to add
 	 * @param	int		$client_id  	id invoice customer
 	 * @param	string	$client_nom 	customer name
 	 * @param	int		$amount 		amount of invoice
@@ -126,14 +127,16 @@ class BonPrelevement extends CommonObject
 	 * @param	string	$code_guichet 	code of bank's office
 	 * @param	string	$number bank 	account number
 	 * @param	string	$number_key 	number key of account number
+	 * @param	string	$type			'debit-order' or 'bank-transfer'
 	 * @return	int						>0 if OK, <0 if KO
 	 */
-	public function AddFacture($facture_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key)
+	public function AddFacture($invoice_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $type = 'debit-order')
 	{
 		// phpcs:enable
 		$result = 0;
 		$line_id = 0;
 
+		// Add lines
 		$result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key);
 
 		if ($result == 0)
@@ -141,10 +144,14 @@ class BonPrelevement extends CommonObject
 			if ($line_id > 0)
 			{
 				$sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_facture (";
-				$sql .= "fk_facture";
+				if ($type != 'bank-transfer') {
+					$sql .= "fk_facture";
+				} else {
+					$sql .= "fk_facture_fourn";
+				}
 				$sql .= ",fk_prelevement_lignes";
 				$sql .= ") VALUES (";
-				$sql .= $facture_id;
+				$sql .= $invoice_id;
 				$sql .= ", ".$line_id;
 				$sql .= ")";
 
@@ -153,15 +160,15 @@ class BonPrelevement extends CommonObject
 					$result = 0;
 				} else {
 					$result = -1;
-					dol_syslog(get_class($this)."::AddFacture Erreur $result");
+					dol_syslog(get_class($this)."::AddFacture Error $result");
 				}
 			} else {
 				$result = -2;
-				dol_syslog(get_class($this)."::AddFacture Erreur $result");
+				dol_syslog(get_class($this)."::AddFacture Error $result");
 			}
 		} else {
 			$result = -3;
-			dol_syslog(get_class($this)."::AddFacture Erreur $result");
+			dol_syslog(get_class($this)."::AddFacture Error $result");
 		}
 
 		return $result;
@@ -645,7 +652,7 @@ class BonPrelevement extends CommonObject
 
 	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
-	 *	Returns amount of withdrawal
+	 *	Returns amount waiting for direct debit payment or credit transfer payment
 	 *
 	 *	@param	string	$mode		'direct-debit' or 'bank-transfer'
 	 *	@return	double	 			<O if KO, Total amount
@@ -662,11 +669,19 @@ class BonPrelevement extends CommonObject
 			$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f,";
 		}
 		$sql .= " ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
-		$sql .= " WHERE f.fk_statut = 1";
-		$sql .= " AND f.entity IN (".getEntity('invoice').")";
-		$sql .= " AND f.rowid = pfd.fk_facture";
+		$sql .= " WHERE f.entity IN (".getEntity('invoice').")";
+		if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS))
+		{
+			$sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
+		}
+		if ($mode != 'bank-transfer') {
+			$sql .= " AND f.rowid = pfd.fk_facture";
+		} else {
+			$sql .= " AND f.rowid = pfd.fk_facture_fourn";
+		}
 		$sql .= " AND f.paye = 0";
 		$sql .= " AND pfd.traite = 0";
+		$sql .= " AND pfd.ext_payment_id IS NULL";
 		$sql .= " AND f.total_ttc > 0";
 
 		$resql = $this->db->query($sql);
@@ -699,18 +714,18 @@ class BonPrelevement extends CommonObject
 
 	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
-	 *	Get number of invoices to withdrawal
+	 *	Get number of invoices to pay
 	 *
-	 *	@param	string	$mode		'direct-debit' or 'bank-transfer'
+	 *	@param	string	$type		'direct-debit' or 'bank-transfer'
 	 *	@return	int					<O if KO, number of invoices if OK
 	 */
-	public function NbFactureAPrelever($mode = 'direct-debit')
+	public function NbFactureAPrelever($type = 'direct-debit')
 	{
 		// phpcs:enable
 		global $conf;
 
 		$sql = "SELECT count(f.rowid) as nb";
-		if ($mode == 'bank-transfer') {
+		if ($type == 'bank-transfer') {
 			$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
 		} else {
 			$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
@@ -721,12 +736,13 @@ class BonPrelevement extends CommonObject
 		{
 			$sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
 		}
-		if ($mode == 'bank-transfer') {
+		if ($type == 'bank-transfer') {
 			$sql .= " AND f.rowid = pfd.fk_facture_fourn";
 		} else {
 			$sql .= " AND f.rowid = pfd.fk_facture";
 		}
 		$sql .= " AND pfd.traite = 0";
+		$sql .= " AND pfd.ext_payment_id IS NULL";
 		$sql .= " AND f.total_ttc > 0";
 
 		dol_syslog(get_class($this)."::NbFactureAPrelever");
@@ -748,18 +764,19 @@ class BonPrelevement extends CommonObject
 
 	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
 	/**
-	 *	Create a withdraw
-	 *  TODO delete params banque and agence when not necesary
+	 *	Create a direct debit order or a credit transfer order
+	 *  TODO delete params banque and agence when not necessary
 	 *
-	 *	@param 	int		  $banque		dolibarr mysoc bank
-	 *	@param	int		  $agence		dolibarr mysoc bank office (guichet)
-	 *	@param	string	$mode		real=do action, simu=test only
-	 *  @param	string	$format		FRST, RCUR or ALL
+	 *	@param 	int		$banque			dolibarr mysoc bank
+	 *	@param	int		$agence			dolibarr mysoc bank office (guichet)
+	 *	@param	string	$mode			real=do action, simu=test only
+	 *  @param	string	$format			FRST, RCUR or ALL
 	 *  @param  string  $executiondate	Date to execute the transfer
 	 *  @param	int	    $notrigger		Disable triggers
-	 *	@return	int					<0 if KO, nbre of invoice withdrawed if OK
+	 *  @param	string	$type			'direct-debit' or 'bank-transfer'
+	 *	@return	int						<0 if KO, No of invoice included into file if OK
 	 */
-	public function Create($banque = 0, $agence = 0, $mode = 'real', $format = 'ALL', $executiondate = '', $notrigger = 0)
+	public function create($banque = 0, $agence = 0, $mode = 'real', $format = 'ALL', $executiondate = '', $notrigger = 0, $type = 'direct-debit')
 	{
 		// phpcs:enable
 		global $conf, $langs, $user;
@@ -769,7 +786,12 @@ class BonPrelevement extends CommonObject
 		require_once DOL_DOCUMENT_ROOT."/compta/facture/class/facture.class.php";
 		require_once DOL_DOCUMENT_ROOT."/societe/class/societe.class.php";
 
-		if (empty($format)) return 'ErrorBadParametersForDirectDebitFileCreate';
+		if ($type != 'bank-transfer') {
+			if (empty($format)) {
+				$this->error = 'ErrorBadParametersForDirectDebitFileCreate';
+				return -1;
+			}
+		}
 
 		$error = 0;
 
@@ -796,17 +818,26 @@ class BonPrelevement extends CommonObject
 			$sql .= ", pfd.code_banque, pfd.code_guichet, pfd.number, pfd.cle_rib";
 			$sql .= ", pfd.amount";
 			$sql .= ", s.nom as name";
-			$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
+			if ($type != 'bank-transfer') {
+				$sql .= " FROM ".MAIN_DB_PREFIX."facture as f";
+			} else {
+				$sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f";
+			}
 			$sql .= ", ".MAIN_DB_PREFIX."societe as s";
 			$sql .= ", ".MAIN_DB_PREFIX."prelevement_facture_demande as pfd";
-			$sql .= " WHERE f.rowid = pfd.fk_facture";
-			$sql .= " AND f.entity IN (".getEntity('invoice').')';
+			$sql .= " WHERE f.entity IN (".getEntity('invoice').')';
+			if ($type != 'bank-transfer') {
+				$sql .= " AND f.rowid = pfd.fk_facture";
+			} else {
+				$sql .= " AND f.rowid = pfd.fk_facture_fourn";
+			}
 			$sql .= " AND s.rowid = f.fk_soc";
 			//if ($banque || $agence) $sql.= " AND s.rowid = sr.fk_soc";
 			$sql .= " AND f.fk_statut = 1";
 			$sql .= " AND f.paye = 0";
 			$sql .= " AND pfd.traite = 0";
 			$sql .= " AND f.total_ttc > 0";
+			$sql .= " AND pfd.ext_payment_id IS NULL";
 			//if ($banque) $sql.= " AND sr.code_banque = '".$conf->global->PRELEVEMENT_CODE_BANQUE."'";
 			//if ($agence) $sql.= " AND sr.code_guichet = '".$conf->global->PRELEVEMENT_CODE_GUICHET."'";
 
@@ -822,6 +853,12 @@ class BonPrelevement extends CommonObject
 				{
 					$row = $this->db->fetch_row($resql);
 					$factures[$i] = $row; // All fields
+					if ($row[7] == 0) {
+						$error++;
+						dol_syslog(__METHOD__."::Read invoices error Found a null invoice", LOG_ERR);
+						$this->invoice_in_error[$row[0]] = "Error for invoice id ".$row[0].", found a null amount";
+						break;
+					}
 					$i++;
 				}
 				$this->db->free($resql);
@@ -837,15 +874,19 @@ class BonPrelevement extends CommonObject
 			require_once DOL_DOCUMENT_ROOT.'/societe/class/companybankaccount.class.php';
 			$soc = new Societe($this->db);
 
-			// Check RIB
+			// Check BAN
 			$i = 0;
-			dol_syslog(__METHOD__."::Check RIB", LOG_DEBUG);
+			dol_syslog(__METHOD__."::Check BAN", LOG_DEBUG);
 
 			if (count($factures) > 0)
 			{
 				foreach ($factures as $key => $fac)
 				{
-					$fact = new Facture($this->db);
+					if ($type != 'bank-transfer') {
+						$fact = new Facture($this->db);
+					} else {
+						$fact = new FactureFournisseur($this->db);
+					}
 					$resfetch = $fact->fetch($fac[0]);
 					if ($resfetch >= 0)		// Field 0 of $fac is rowid of invoice
 					{
@@ -854,13 +895,15 @@ class BonPrelevement extends CommonObject
 							$bac = new CompanyBankAccount($this->db);
 							$bac->fetch(0, $soc->id);
 
-							if ($format == 'FRST' && $bac->frstrecur != 'FRST')
-							{
-								continue;
-							}
-							if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR'))
-							{
-								continue;
+							if ($type != 'bank-transfer') {
+								if ($format == 'FRST' && $bac->frstrecur != 'FRST')
+								{
+									continue;
+								}
+								if ($format == 'RCUR' && ($bac->frstrecur != 'RCUR' && $bac->frstrecur != 'RECUR'))
+								{
+									continue;
+								}
 							}
 
 							if ($bac->verif() >= 1)
@@ -871,26 +914,26 @@ class BonPrelevement extends CommonObject
 								$i++;
 								//dol_syslog(__METHOD__."::RIB is ok", LOG_DEBUG);
 							} else {
-								dol_syslog(__METHOD__."::Check RIB Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_WARNING);
+								dol_syslog(__METHOD__."::Check BAN Error on default bank number IBAN/BIC for thirdparty reported by verif() ".$fact->socid." ".$soc->name, LOG_WARNING);
 								$this->invoice_in_error[$fac[0]] = "Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
 								$this->thirdparty_in_error[$soc->id] = "Error on default bank number IBAN/BIC for invoice ".$fact->getNomUrl(0)." for thirdparty ".$soc->getNomUrl(0);
 							}
 						} else {
-							dol_syslog(__METHOD__."::Check RIB Failed to read company", LOG_WARNING);
+							dol_syslog(__METHOD__."::Check BAN Failed to read company", LOG_WARNING);
 						}
 					} else {
-						dol_syslog(__METHOD__."::Check RIB Failed to read invoice", LOG_WARNING);
+						dol_syslog(__METHOD__."::Check BAN Failed to read invoice", LOG_WARNING);
 					}
 				}
 			} else {
-				dol_syslog(__METHOD__."::Check RIB No invoice to process", LOG_WARNING);
+				dol_syslog(__METHOD__."::Check BAN No invoice to process", LOG_WARNING);
 			}
 		}
 
 		$ok = 0;
 
 		// Withdraw invoices in factures_prev array
-		$out = count($factures_prev)." invoices will be withdrawn.";
+		$out = count($factures_prev)." invoices will be included.";
 		//print $out."\n";
 		dol_syslog($out);
 
@@ -918,14 +961,14 @@ class BonPrelevement extends CommonObject
 		{
 			/*
 			 * We are in real mode.
-			 * We create withdraw receipt and build withdraw into disk
+			 * We create order and build file into disk
 			 */
 			$this->db->begin();
 
 			$now = dol_now();
 
 			/*
-			 * Traitements
+			 * Process order generation
 			 */
 			if (!$error)
 			{
@@ -937,7 +980,7 @@ class BonPrelevement extends CommonObject
 				$sql .= " AND entity = ".$conf->entity;
 				$sql .= " ORDER BY ref DESC LIMIT 1";
 
-				dol_syslog(get_class($this)."::Create sql=".$sql, LOG_DEBUG);
+				dol_syslog(get_class($this)."::create sql=".$sql, LOG_DEBUG);
 				$resql = $this->db->query($sql);
 
 				if ($resql)
@@ -945,18 +988,23 @@ class BonPrelevement extends CommonObject
 					$row = $this->db->fetch_row($resql);
 					$ref = "T".$ref.str_pad(dol_substr("00".intval($row[0]) + 1, 0, 2), 2, "0", STR_PAD_LEFT);
 
-					$dir = $conf->prelevement->dir_output.'/receipts';
+					if ($type != 'bank-transfer') {
+						$dir = $conf->prelevement->dir_output.'/receipts';
+					} else {
+						$dir = $conf->paymentbybanktransfer->dir_output.'/receipts';
+					}
 					if (!is_dir($dir)) dol_mkdir($dir);
 
 					$this->filename = $dir.'/'.$ref.'.xml';
 
 					// Create withdraw receipt in database
 					$sql = "INSERT INTO ".MAIN_DB_PREFIX."prelevement_bons (";
-					$sql .= " ref, entity, datec";
+					$sql .= " ref, entity, datec, type";
 					$sql .= ") VALUES (";
 					$sql .= "'".$this->db->escape($ref)."'";
 					$sql .= ", ".$conf->entity;
 					$sql .= ", '".$this->db->idate($now)."'";
+					$sql .= ", '".($type == 'bank-transfer' ? 'bank-transfer' : 'debit-order')."'";
 					$sql .= ")";
 
 					$resql = $this->db->query($sql);
@@ -987,10 +1035,13 @@ class BonPrelevement extends CommonObject
 						// Fetch invoice
 						$fact = new Facture($this->db);
 						$fact->fetch($fac[0]);
+
 						/*
 						 * Add standing order
 						 *
-						 *
+						 * $fac[0] : invoice_id
+						 * $fac[1] : ???
+						 * $fac[2] : third party id
 						 * $fac[3] : banque
 						 * $fac[4] : guichet
 						 * $fac[5] : number
@@ -999,7 +1050,8 @@ class BonPrelevement extends CommonObject
 						 * $fac[8] : client nom
 						 * $fac[2] : client id
 						 */
-						$ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6]);
+
+						$ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6], $type);
 						if ($ri <> 0)
 						{
 							$error++;
@@ -1012,13 +1064,12 @@ class BonPrelevement extends CommonObject
 						$sql .= ", fk_prelevement_bons = ".$this->id;
 						$sql .= " WHERE rowid = ".$fac[1];
 
-						dol_syslog(__METHOD__."::Update Orders::Sql=".$sql, LOG_DEBUG);
 						$resql = $this->db->query($sql);
 
 						if (!$resql)
 						{
 							$error++;
-							dol_syslog(__METHOD__."::Update Orders::Error=".$this->db->error(), LOG_ERR);
+							dol_syslog(__METHOD__."::Update Error=".$this->db->error(), LOG_ERR);
 						}
 					}
 				}
@@ -1027,11 +1078,10 @@ class BonPrelevement extends CommonObject
 			if (!$error)
 			{
 				/*
-				 * Create direct debit order in a XML file
+				 * Create file of direct debit order or credit transfer into a XML file
 				 */
 
-				dol_syslog(__METHOD__."::Init withdraw receipt for ".count($factures_prev)." invoices", LOG_DEBUG);
-
+				dol_syslog(__METHOD__."::Init direct debit file for ".count($factures_prev)." invoices", LOG_DEBUG);
 
 				if (count($factures_prev) > 0)
 				{
@@ -1058,14 +1108,15 @@ class BonPrelevement extends CommonObject
 					$this->context['factures_prev'] = $factures_prev;
 
 					// Generation of SEPA file $this->filename
-					$this->generate($format, $executiondate);
+					// This also the the property $this->total that is included into file
+					$result = $this->generate($format, $executiondate, $type);
 				}
 				dol_syslog(__METHOD__."::End withdraw receipt, file ".$this->filename, LOG_DEBUG);
 			}
 			//var_dump($factures_prev);exit;
 
 			/*
-			 * Update total
+			 * Update total defined after generation of file
 			 */
 			$sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons";
 			$sql .= " SET amount = ".price2num($this->total);
@@ -1081,8 +1132,13 @@ class BonPrelevement extends CommonObject
 
 			if (!$error && !$notrigger)
 			{
+				$triggername = 'DIRECT_DEBIT_ORDER_CREATE';
+				if ($type != 'bank-transfer') {
+					$triggername = 'CREDIT_TRANSFER_ORDER_CREATE';
+				}
+
 				// Call trigger
-				$result = $this->call_trigger('DIRECT_DEBIT_ORDER_CREATE', $user);
+				$result = $this->call_trigger($triggername, $user);
 				if ($result < 0) $error++;
 				// End call triggers
 			}
@@ -1332,17 +1388,18 @@ class BonPrelevement extends CommonObject
 
 
 	/**
-	 * Generate a withdrawal file.
+	 * Generate a direct debit or credit transfer file.
 	 * Generation Formats:
 	 * - Europe: SEPA (France: CFONB no more supported, Spain: AEB19 if external module EsAEB is enabled)
 	 * - Others countries: Warning message
 	 * File is generated with name this->filename
 	 *
-	 *  @param		string	$format		FRST, RCUR or ALL
-	 * @param string $executiondate		Date to execute transfer
-	 *	@return		int					0 if OK, <0 if KO
+	 * @param	string	$format				FRST, RCUR or ALL
+	 * @param 	string 	$executiondate		Date to execute transfer
+	 * @param	string	$type				'direct-debit' or 'credit-transfer'
+	 * @return	int							>=0 if OK, <0 if KO
 	 */
-	public function generate($format = 'ALL', $executiondate = '')
+	public function generate($format = 'ALL', $executiondate = '', $type = 'direct-debit')
 	{
 		global $conf, $langs, $mysoc;
 
@@ -1350,7 +1407,7 @@ class BonPrelevement extends CommonObject
 
 		$result = 0;
 
-		dol_syslog(get_class($this)."::generate build file ".$this->filename);
+		dol_syslog(get_class($this)."::generate build file=".$this->filename." type=".$type);
 
 		$this->file = fopen($this->filename, "w");
 		if (empty($this->file))
@@ -1360,159 +1417,201 @@ class BonPrelevement extends CommonObject
 		}
 
 		$found = 0;
+		$this->total = 0;
 
 		// Build file for European countries
 		if ($mysoc->isInEEC())
 		{
 			$found++;
 
-			/**
-			 * SECTION CREATION FICHIER SEPA
-			 */
-			// SEPA Initialisation
-			$CrLf = "\n";
+			if ($type == 'bank-transfer') {
+				print 'TODO';
+				exit;
+			} else {
+				/**
+				 * SECTION CREATION FICHIER SEPA
+				 */
+				// SEPA Initialisation
+				$CrLf = "\n";
 
-			$now = dol_now();
+				$now = dol_now();
 
-			$dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
+				$dateTime_ECMA = dol_print_date($now, '%Y-%m-%dT%H:%M:%S');
 
-			$date_actu = $now;
-			if (!empty($executiondate)) $date_actu = $executiondate;
+				$date_actu = $now;
+				if (!empty($executiondate)) $date_actu = $executiondate;
 
-			$dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
-			$dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
-			$fileDebiteurSection = '';
-			$fileEmetteurSection = '';
-			$i = 0;
-			$this->total = 0;
+				$dateTime_YMD = dol_print_date($date_actu, '%Y%m%d');
+				$dateTime_YMDHMS = dol_print_date($date_actu, '%Y%m%d%H%M%S');
+				$fileDebiteurSection = '';
+				$fileEmetteurSection = '';
+				$i = 0;
 
-			/*
-			 * section Debiteur (sepa Debiteurs bloc lines)
-			 */
+				/*
+				 * Section Debitor (sepa Debiteurs bloc lines)
+				 */
 
-			$sql = "SELECT soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
-			$sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
-			$sql .= " f.ref as fac, pf.fk_facture as idfac, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
-			$sql .= " FROM";
-			$sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
-			$sql .= " ".MAIN_DB_PREFIX."facture as f,";
-			$sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
-			$sql .= " ".MAIN_DB_PREFIX."societe as soc,";
-			$sql .= " ".MAIN_DB_PREFIX."c_country as c,";
-			$sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
-			$sql .= " WHERE pl.fk_prelevement_bons = ".$this->id;
-			$sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
-			$sql .= " AND pf.fk_facture = f.rowid";
-			$sql .= " AND soc.fk_pays = c.rowid";
-			$sql .= " AND soc.rowid = f.fk_soc";
-			$sql .= " AND rib.fk_soc = f.fk_soc";
-			$sql .= " AND rib.default_rib = 1";
-			$sql .= " AND rib.type = 'ban'";
-			//print $sql;
-
-			// Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
-			$resql = $this->db->query($sql);
-			if ($resql)
-			{
-				$num = $this->db->num_rows($resql);
-				while ($i < $num)
+				$sql = "SELECT soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,";
+				$sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,";
+				$sql .= " f.ref as fac, pf.fk_facture as idfac, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, rib.rum, rib.date_rum";
+				$sql .= " FROM";
+				$sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
+				$sql .= " ".MAIN_DB_PREFIX."facture as f,";
+				$sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf,";
+				$sql .= " ".MAIN_DB_PREFIX."societe as soc,";
+				$sql .= " ".MAIN_DB_PREFIX."c_country as c,";
+				$sql .= " ".MAIN_DB_PREFIX."societe_rib as rib";
+				$sql .= " WHERE pl.fk_prelevement_bons = ".$this->id;
+				$sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
+				$sql .= " AND pf.fk_facture = f.rowid";
+				$sql .= " AND soc.fk_pays = c.rowid";
+				$sql .= " AND soc.rowid = f.fk_soc";
+				$sql .= " AND rib.fk_soc = f.fk_soc";
+				$sql .= " AND rib.default_rib = 1";
+				$sql .= " AND rib.type = 'ban'";
+				//print $sql;
+
+				// Define $fileDebiteurSection. One section DrctDbtTxInf per invoice.
+				$resql = $this->db->query($sql);
+				if ($resql)
 				{
-					$obj = $this->db->fetch_object($resql);
-					$daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
-					$fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->fac, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum);
-					$this->total = $this->total + $obj->somme;
-					$i++;
+					$num = $this->db->num_rows($resql);
+					while ($i < $num)
+					{
+						$obj = $this->db->fetch_object($resql);
+						$daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec);
+						$fileDebiteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->fac, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum);
+						$this->total = $this->total + $obj->somme;
+						$i++;
+					}
+					$nbtotalDrctDbtTxInf = $i;
+				} else {
+					fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf); // DEBITOR = Customers
+					$result = -2;
 				}
-				$nbtotalDrctDbtTxInf = $i;
-			} else {
-				fputs($this->file, 'ERROR DEBITOR '.$sql.$CrLf); // DEBITOR = Customers
-				$result = -2;
-			}
 
-			// Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all DrctDbtTxInf
-			if ($result != -2)
-			{
-				$fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format);
-			} else {
-				fputs($this->file, 'ERROR CREDITOR'.$CrLf); // CREDITOR = My company
-			}
+				// Define $fileEmetteurSection. Start of bloc PmtInf. Will contains all DrctDbtTxInf
+				if ($result != -2)
+				{
+					$fileEmetteurSection .= $this->EnregEmetteurSEPA($conf, $date_actu, $nbtotalDrctDbtTxInf, $this->total, $CrLf, $format);
+				} else {
+					fputs($this->file, 'ERROR CREDITOR'.$CrLf); // CREDITOR = My company
+				}
 
-			/**
-			 * SECTION CREATION SEPA FILE
-			 */
-			// SEPA File Header
-			fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
-			fputs($this->file, '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.$CrLf);
-			fputs($this->file, '	<CstmrDrctDbtInitn>'.$CrLf);
-			// SEPA Group header
-			fputs($this->file, '		<GrpHdr>'.$CrLf);
-			fputs($this->file, '			<MsgId>'.('PREL'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
-			fputs($this->file, '			<CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
-			fputs($this->file, '			<NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
-			fputs($this->file, '			<CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
-			fputs($this->file, '			<InitgPty>'.$CrLf);
-			fputs($this->file, '				<Nm>'.strtoupper(dol_string_unaccent($this->raison_sociale)).'</Nm>'.$CrLf);
-			fputs($this->file, '				<Id>'.$CrLf);
-			fputs($this->file, '				    <PrvtId>'.$CrLf);
-			fputs($this->file, '					<Othr>'.$CrLf);
-			fputs($this->file, '						<Id>'.$conf->global->PRELEVEMENT_ICS.'</Id>'.$CrLf);
-			fputs($this->file, '					</Othr>'.$CrLf);
-			fputs($this->file, '				    </PrvtId>'.$CrLf);
-			fputs($this->file, '				</Id>'.$CrLf);
-			fputs($this->file, '			</InitgPty>'.$CrLf);
-			fputs($this->file, '		</GrpHdr>'.$CrLf);
-			// SEPA File Emetteur
-			if ($result != -2)
-			{	fputs($this-> file, $fileEmetteurSection); }
-			// SEPA File Debiteurs
-			if ($result != -2)
-			{	fputs($this-> file, $fileDebiteurSection); }
-			// SEPA FILE FOOTER
-			fputs($this->file, '		</PmtInf>'.$CrLf);
-			fputs($this->file, '	</CstmrDrctDbtInitn>'.$CrLf);
-			fputs($this->file, '</Document>'.$CrLf);
+				/**
+				 * SECTION CREATION SEPA FILE
+				 */
+				// SEPA File Header
+				fputs($this->file, '<'.'?xml version="1.0" encoding="UTF-8" standalone="yes"?'.'>'.$CrLf);
+				fputs($this->file, '<Document xmlns="urn:iso:std:iso:20022:tech:xsd:pain.008.001.02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">'.$CrLf);
+				fputs($this->file, '	<CstmrDrctDbtInitn>'.$CrLf);
+				// SEPA Group header
+				fputs($this->file, '		<GrpHdr>'.$CrLf);
+				fputs($this->file, '			<MsgId>'.('PREL'.$dateTime_YMD.'/REF'.$this->id).'</MsgId>'.$CrLf);
+				fputs($this->file, '			<CreDtTm>'.$dateTime_ECMA.'</CreDtTm>'.$CrLf);
+				fputs($this->file, '			<NbOfTxs>'.$i.'</NbOfTxs>'.$CrLf);
+				fputs($this->file, '			<CtrlSum>'.$this->total.'</CtrlSum>'.$CrLf);
+				fputs($this->file, '			<InitgPty>'.$CrLf);
+				fputs($this->file, '				<Nm>'.strtoupper(dol_string_unaccent($this->raison_sociale)).'</Nm>'.$CrLf);
+				fputs($this->file, '				<Id>'.$CrLf);
+				fputs($this->file, '				    <PrvtId>'.$CrLf);
+				fputs($this->file, '					<Othr>'.$CrLf);
+				fputs($this->file, '						<Id>'.$conf->global->PRELEVEMENT_ICS.'</Id>'.$CrLf);
+				fputs($this->file, '					</Othr>'.$CrLf);
+				fputs($this->file, '				    </PrvtId>'.$CrLf);
+				fputs($this->file, '				</Id>'.$CrLf);
+				fputs($this->file, '			</InitgPty>'.$CrLf);
+				fputs($this->file, '		</GrpHdr>'.$CrLf);
+				// SEPA File Emetteur
+				if ($result != -2)
+				{	fputs($this-> file, $fileEmetteurSection); }
+				// SEPA File Debiteurs
+				if ($result != -2)
+				{	fputs($this-> file, $fileDebiteurSection); }
+				// SEPA FILE FOOTER
+				fputs($this->file, '		</PmtInf>'.$CrLf);
+				fputs($this->file, '	</CstmrDrctDbtInitn>'.$CrLf);
+				fputs($this->file, '</Document>'.$CrLf);
+			}
 		}
 
 		// Build file for Other Countries with unknow format
 		if (!$found)
 		{
-			$this->total = 0;
-			$sql = "SELECT pl.amount";
-			$sql .= " FROM";
-			$sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
-			$sql .= " ".MAIN_DB_PREFIX."facture as f,";
-			$sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
-			$sql .= " WHERE pl.fk_prelevement_bons = ".$this->id;
-			$sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
-			$sql .= " AND pf.fk_facture = f.rowid";
-
-			//Lines
-			$i = 0;
-			$resql = $this->db->query($sql);
-			if ($resql)
-			{
-				$num = $this->db->num_rows($resql);
+			if ($type == 'bank-transfer') {
+				$sql = "SELECT pl.amount";
+				$sql .= " FROM";
+				$sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
+				$sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,";
+				$sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
+				$sql .= " WHERE pl.fk_prelevement_bons = ".$this->id;
+				$sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
+				$sql .= " AND pf.fk_facture_fourn = f.rowid";
+
+				// Lines
+				$i = 0;
+				$resql = $this->db->query($sql);
+				if ($resql)
+				{
+					$num = $this->db->num_rows($resql);
 
-				while ($i < $num)
+					while ($i < $num)
+					{
+						$obj = $this->db->fetch_object($resql);
+						$this->total = $this->total + $obj->amount;
+
+						// TODO Write record into file
+						$i++;
+					}
+				}
+				else
 				{
-					$obj = $this->db->fetch_object($resql);
-					$this->total = $this->total + $obj->amount;
-					$i++;
+					$result = -2;
 				}
 			} else {
-				$result = -2;
+				$sql = "SELECT pl.amount";
+				$sql .= " FROM";
+				$sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,";
+				$sql .= " ".MAIN_DB_PREFIX."facture as f,";
+				$sql .= " ".MAIN_DB_PREFIX."prelevement_facture as pf";
+				$sql .= " WHERE pl.fk_prelevement_bons = ".$this->id;
+				$sql .= " AND pl.rowid = pf.fk_prelevement_lignes";
+				$sql .= " AND pf.fk_facture = f.rowid";
+
+				// Lines
+				$i = 0;
+				$resql = $this->db->query($sql);
+				if ($resql)
+				{
+					$num = $this->db->num_rows($resql);
+
+					while ($i < $num)
+					{
+						$obj = $this->db->fetch_object($resql);
+						$this->total = $this->total + $obj->amount;
+
+						// TODO Write record into file
+						$i++;
+					}
+				}
+				else
+				{
+					$result = -2;
+				}
 			}
 
 			$langs->load('withdrawals');
 
 			// TODO Add here code to generate a generic file
-			fputs($this->file, $langs->trans('WithdrawalFileNotCapable', $mysoc->country_code));
+			fputs($this->file, $langs->transnoentitiesnoconv('WithdrawalFileNotCapable', $mysoc->country_code));
 		}
 
 		fclose($this->file);
-		if (!empty($conf->global->MAIN_UMASK))
+		if (!empty($conf->global->MAIN_UMASK)) {
 			@chmod($this->file, octdec($conf->global->MAIN_UMASK));
-			return $result;
+		}
+
+		return $result;
 	}
 
 

+ 41 - 12
htdocs/compta/prelevement/create.php

@@ -1,11 +1,11 @@
 <?php
 /* Copyright (C) 2005       Rodolphe Quiedeville    <rodolphe@quiedeville.org>
- * Copyright (C) 2010-2015  Laurent Destailleur     <eldy@users.sourceforge.net>
+ * Copyright (C) 2010-2020  Laurent Destailleur     <eldy@users.sourceforge.net>
  * Copyright (C) 2005-2009  Regis Houssin           <regis.houssin@inodbox.com>
  * Copyright (C) 2010-2012  Juanjo Menent           <jmenent@2byte.es>
  * Copyright (C) 2018       Nicolas ZABOURI         <info@inovea-conseil.com>
  * Copyright (C) 2018       Frédéric France         <frederic.france@netlogic.fr>
- * Copyright (C) 2019      Markus Welters       <markus@welters.de>
+ * Copyright (C) 2019       Markus Welters          <markus@welters.de>
  *
  * This program is free software; you can redistribute it and/or modify
  * it under the terms of the GNU General Public License as published by
@@ -24,7 +24,7 @@
 /**
  *	\file       htdocs/compta/prelevement/create.php
  *  \ingroup    prelevement
- *	\brief      Prelevement creation page
+ *	\brief      Page to create a direct debit order or a credit transfer order
  */
 
 require '../../main.inc.php';
@@ -77,11 +77,17 @@ if (empty($reshook))
 	}
 	if ($action == 'create')
 	{
-		// $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty
+		$delayindays = 0;
+		if ($type != 'bank-transfer') {
+			$conf->global->PRELEVEMENT_ADDDAYS;
+		} else {
+			$conf->global->PAYMENTBYBANKTRANSFER_ADDDAYS;
+		}
 		$bprev = new BonPrelevement($db);
-	    $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth'), (GETPOST('reday') + $conf->global->PRELEVEMENT_ADDDAYS), GETPOST('reyear'));
+	    $executiondate = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), (GETPOST('reday', 'int') + $delayindays), GETPOST('reyear', 'int'));
 
-	    $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format, $executiondate);
+	    // $conf->global->PRELEVEMENT_CODE_BANQUE and $conf->global->PRELEVEMENT_CODE_GUICHET should be empty (we don't use them anymore)
+	    $result = $bprev->create($conf->global->PRELEVEMENT_CODE_BANQUE, $conf->global->PRELEVEMENT_CODE_GUICHET, $mode, $format, $executiondate, 0, $type);
 		if ($result < 0)
 		{
 			setEventMessages($bprev->error, $bprev->errors, 'errors');
@@ -111,7 +117,11 @@ if (empty($reshook))
 $form = new Form($db);
 
 $thirdpartystatic = new Societe($db);
-$invoicestatic = new Facture($db);
+if ($type != 'bank-transfer') {
+	$invoicestatic = new Facture($db);
+} else {
+	$invoicestatic = new FactureFournisseur($db);
+}
 $bprev = new BonPrelevement($db);
 
 llxHeader('', $langs->trans("NewStandingOrder"));
@@ -174,15 +184,25 @@ print '<div class="tabsAction">'."\n";
 
 print '<form action="'.$_SERVER['PHP_SELF'].'?action=create" method="POST">';
 print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
+print '<input type="hidden" name="type" value="'.$type.'">';
 if ($nb) {
     if ($pricetowithdraw) {
         print $langs->trans('ExecutionDate').' ';
-        print $form->selectDate();
+        $datere = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
+        print $form->selectDate($datere, 're');
 
         if ($mysoc->isInEEC()) {
         	$title = $langs->trans("CreateForSepa");
+        	if ($type == 'bank-transfer') {
+        		$title = $langs->trans("CreateSepaFileForPaymentByBankTransfer");
+        	}
 
-            print '<select name="format"><option value="FRST">'.$langs->trans('SEPAFRST').'</option><option value="RCUR">'.$langs->trans('SEPARCUR').'</option></select>';
+        	if ($type != 'bank-transfer') {
+            	print '<select name="format">';
+            	print '<option value="FRST"'.(GETPOST('format', 'aZ09') == 'FRST' ? ' selected="selected"' : '').'>'.$langs->trans('SEPAFRST').'</option>';
+            	print '<option value="RCUR"'.(GETPOST('format', 'aZ09') == 'RCUR' ? ' selected="selected"' : '').'>'.$langs->trans('SEPARCUR').'</option>';
+            	print '</select>';
+        	}
             print '<input class="butAction" type="submit" value="'.$title.'"/>';
         } else {
         	$title = $langs->trans("CreateAll");
@@ -248,8 +268,10 @@ if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS))
 {
 	$sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
 }
-$sql .= " AND f.total_ttc > 0";
+//$sql .= " AND pfd.amount > 0";
+$sql .= " AND f.total_ttc > 0";		// Avoid credit notes
 $sql .= " AND pfd.traite = 0";
+$sql .= " AND pfd.ext_payment_id IS NULL";
 if ($type == 'bank-transfer') {
 	$sql .= " AND pfd.fk_facture_fourn = f.rowid";
 } else {
@@ -295,9 +317,14 @@ if ($resql)
 	}
     print_barre_liste($title, $page, $_SERVER['PHP_SELF'], $param, '', '', '', $num, $nbtotalofrecords, 'bill', 0, '', '', $limit);
 
+    $tradinvoice = "Invoice";
+    if ($type == 'bank-transfer') {
+    	$tradinvoice = "SupplierInvoice";
+    }
+
 	print '<table class="noborder centpercent">';
 	print '<tr class="liste_titre">';
-	print '<td>'.$langs->trans("Invoice").'</td>';
+	print '<td>'.$langs->trans($tradinvoice).'</td>';
 	print '<td>'.$langs->trans("ThirdParty").'</td>';
 	print '<td>'.$langs->trans("RIB").'</td>';
 	print '<td>'.$langs->trans("RUM").'</td>';
@@ -341,7 +368,9 @@ if ($resql)
 			print '<td>';
 			print $thirdpartystatic->display_rib('rum');
 			$format = $thirdpartystatic->display_rib('format');
-			if ($format) print ' ('.$format.')';
+			if ($type != 'bank-transfer') {
+				if ($format) print ' ('.$format.')';
+			}
 			print '</td>';
 			// Amount
 			print '<td class="right">';

+ 13 - 8
htdocs/compta/prelevement/index.php

@@ -22,7 +22,7 @@
 /**
  *	\file       htdocs/compta/prelevement/index.php
  *  \ingroup    prelevement
- *	\brief      Prelevement index page
+ *	\brief      Home page for direct debit orders
  */
 
 
@@ -94,7 +94,7 @@ print '</td></tr></table></div><br>';
  */
 $sql = "SELECT f.ref, f.rowid, f.total_ttc, f.fk_statut, f.paye, f.type,";
 $sql .= " pfd.date_demande, pfd.amount,";
-$sql .= " s.nom as name, s.rowid as socid";
+$sql .= " s.nom as name, s.email, s.rowid as socid";
 $sql .= " FROM ".MAIN_DB_PREFIX."facture as f,";
 $sql .= " ".MAIN_DB_PREFIX."societe as s";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc";
@@ -106,7 +106,9 @@ if (empty($conf->global->WITHDRAWAL_ALLOW_ANY_INVOICE_STATUS))
 {
 	$sql .= " AND f.fk_statut = ".Facture::STATUS_VALIDATED;
 }
-$sql .= " AND pfd.traite = 0 AND pfd.fk_facture = f.rowid";
+$sql .= " AND pfd.traite = 0";
+$sql .= " AND pfd.ext_payment_id IS NULL";
+$sql .= " AND pfd.fk_facture = f.rowid";
 if (!$user->rights->societe->client->voir && !$socid) $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".$user->id;
 if ($socid) $sql .= " AND f.fk_soc = ".$socid;
 
@@ -133,14 +135,15 @@ if ($resql)
             $invoicestatic->type = $obj->type;
             $alreadypayed = $invoicestatic->getSommePaiement();
 
+            $thirdpartystatic->id = $obj->socid;
+            $thirdpartystatic->name = $obj->name;
+            $thirdpartystatic->email = $obj->email;
 
             print '<tr class="oddeven"><td>';
             print $invoicestatic->getNomUrl(1, 'withdraw');
             print '</td>';
 
             print '<td>';
-            $thirdpartystatic->id = $obj->socid;
-            $thirdpartystatic->name = $obj->name;
             print $thirdpartystatic->getNomUrl(1, 'customer');
             print '</td>';
 
@@ -171,8 +174,9 @@ print '</div><div class="fichetwothirdright"><div class="ficheaddleft">';
 
 
 /*
- * Withdraw receipts
+ * Direct debit orders
  */
+
 $limit = 5;
 $sql = "SELECT p.rowid, p.ref, p.amount, p.datec, p.statut";
 $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p";
@@ -189,7 +193,8 @@ if ($result)
     print"\n<!-- debut table -->\n";
     print '<div class="div-table-responsive-no-min">';
     print '<table class="noborder centpercent">';
-    print '<tr class="liste_titre"><th>'.$langs->trans("LastWithdrawalReceipt", $limit).'</th>';
+    print '<tr class="liste_titre">';
+    print '<th>'.$langs->trans("LastWithdrawalReceipt", $limit).'</th>';
     print '<th>'.$langs->trans("Date").'</th>';
     print '<th class="right">'.$langs->trans("Amount").'</th>';
     print '<th class="right">'.$langs->trans("Status").'</th>';
@@ -217,7 +222,7 @@ if ($result)
 	        $i++;
 	    }
     } else {
-    	print '<tr><td class="opacitymedium">'.$langs->trans("None").'</td></tr>';
+    	print '<tr><td class="opacitymedium" colspan="4">'.$langs->trans("None").'</td></tr>';
     }
 
     print "</table></div><br>";

+ 8 - 4
htdocs/core/class/evalmath.class.php

@@ -270,9 +270,11 @@ class EvalMath
 				// ===============
 			} elseif ($op == ')' and $expecting_op) { // ready to close a parenthesis?
 				while (($o2 = $stack->pop()) != '(') { // pop off the stack back to the last (
-					if (is_null($o2))
+					if (is_null($o2)) {
 						return $this->trigger(5, "unexpected ')'", ")");
-					else $output[] = $o2;
+					} else {
+						$output[] = $o2;
+					}
 				}
 				if (preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches)) { // did we just close a function?
 					$fnn = $matches[1]; // get the function name
@@ -292,9 +294,11 @@ class EvalMath
 				// ===============
 			} elseif ($op == ',' and $expecting_op) { // did we just finish a function argument?
 				while (($o2 = $stack->pop()) != '(') {
-					if (is_null($o2))
+					if (is_null($o2)) {
 						return $this->trigger(5, "unexpected ','", ","); // oops, never had a (
-					else $output[] = $o2; // pop the argument expression stuff and push onto the output
+					} else {
+						$output[] = $o2; // pop the argument expression stuff and push onto the output
+					}
 				}
 				// make sure there was a function
 				if (!preg_match("/^([a-z]\w*)\($/", $stack->last(2), $matches))

+ 6 - 8
htdocs/core/class/extrafields.class.php

@@ -1960,28 +1960,26 @@ class ExtraFields
 					}
 				}
 
-				if (in_array($key_type, array('date')))
-				{
+				if (in_array($key_type, array('date'))) {
 					// Clean parameters
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
 					$value_key = dol_mktime(0, 0, 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
-				} elseif (in_array($key_type, array('datetime')))
-				{
+				} elseif (in_array($key_type, array('datetime'))) {
 					// Clean parameters
 					// TODO GMT date in memory must be GMT so we should add gm=true in parameters
 					$value_key = dol_mktime($_POST["options_".$key."hour"], $_POST["options_".$key."min"], 0, $_POST["options_".$key."month"], $_POST["options_".$key."day"], $_POST["options_".$key."year"]);
-				} elseif (in_array($key_type, array('checkbox', 'chkbxlst')))
-				{
+				} elseif (in_array($key_type, array('checkbox', 'chkbxlst'))) {
 					$value_arr = GETPOST("options_".$key, 'array'); // check if an array
 					if (!empty($value_arr)) {
 						$value_key = implode($value_arr, ',');
 					} else {
 						$value_key = '';
 					}
-				} elseif (in_array($key_type, array('price', 'double')))
-				{
+				} elseif (in_array($key_type, array('price', 'double'))) {
 					$value_arr = GETPOST("options_".$key, 'alpha');
 					$value_key = price2num($value_arr);
+				} elseif (in_array($key_type, array('html'))) {
+					$value_key = GETPOST("options_".$key, 'alpha');
 				} else {
 					$value_key = GETPOST("options_".$key);
 					if (in_array($key_type, array('link')) && $value_key == '-1') $value_key = '';

+ 1 - 3
htdocs/core/lib/fourn.lib.php

@@ -68,7 +68,7 @@ function facturefourn_prepare_head($object)
 			if ($obj) $nbStandingOrders = $obj->nb;
 		}
 		else dol_print_error($db);
-		$head[$h][0] = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id.'&mode=bank-transfer';
+		$head[$h][0] = DOL_URL_ROOT.'/compta/facture/prelevement.php?facid='.$object->id.'&type=bank-transfer';
 		$head[$h][1] = $langs->trans('BankTransfer');
 		if ($nbStandingOrders > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbStandingOrders.'</span>';
 		$head[$h][2] = 'standingorders';
@@ -233,8 +233,6 @@ function supplierorder_admin_prepare_head()
 	$head[$h][2] = 'supplierorderdet';
 	$h++;
 
-
-
 	$head[$h][0] = DOL_URL_ROOT.'/admin/supplierinvoice_extrafields.php';
 	$head[$h][1] = $langs->trans("ExtraFieldsSupplierInvoices");
 	$head[$h][2] = 'supplierinvoice';

+ 1 - 1
htdocs/core/lib/holiday.lib.php

@@ -35,7 +35,7 @@ function holiday_prepare_head($object)
 	$head = array();
 
     $head[$h][0] = DOL_URL_ROOT.'/holiday/card.php?id='.$object->id;
-    $head[$h][1] = $langs->trans("Holiday");
+    $head[$h][1] = $langs->trans("Leave");
     $head[$h][2] = 'card';
     $h++;
 

+ 1 - 1
htdocs/core/menus/standard/eldy.lib.php

@@ -1484,7 +1484,7 @@ function print_left_eldy_menu($db, $menu_array_before, $menu_array_after, &$tabM
 			// Direct debit order
 			if (!empty($conf->prelevement->enabled))
 			{
-				$newmenu->add("/compta/prelevement/index.php?leftmenu=withdraw&amp;mainmenu=bank", $langs->trans("StandingOrders"), 0, $user->rights->prelevement->bons->lire, '', $mainmenu, 'withdraw');
+				$newmenu->add("/compta/prelevement/index.php?leftmenu=withdraw&amp;mainmenu=bank", $langs->trans("PaymentByDirectDebit"), 0, $user->rights->prelevement->bons->lire, '', $mainmenu, 'withdraw');
 
 				if ($usemenuhider || empty($leftmenu) || $leftmenu == "withdraw") {
 				    $newmenu->add("/compta/prelevement/create.php?mainmenu=bank", $langs->trans("NewStandingOrder"), 1, $user->rights->prelevement->bons->creer);

+ 4 - 0
htdocs/install/mysql/data/llx_c_tva.sql

@@ -86,6 +86,10 @@ insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 9
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 93,  9,    '3','0','VAT super reduced rate 0',1);
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values ( 94,  9,   '17','0','VAT standard rate',1);
 
+-- CONGO = REPUBLIQUE DU CONGO (id country=72)
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (721, 72,    '0','0','VAT Rate 0',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,localtax1,localtax1_type,note,active) values (722, 72,   '18','0', '0.9', '1', 'VAT Rate 18+0.9', 1);
+
 -- CYPRUS (id country=78)
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (781, 78,    '0','0','VAT Rate 0',1);
 insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (782, 78,    '9','0','VAT Rate 9',1);

+ 3 - 0
htdocs/install/mysql/migration/11.0.0-12.0.0.sql

@@ -322,3 +322,6 @@ UPDATE llx_prelevement_facture_demande SET entity = 1 WHERE entity IS NULL;
 
 ALTER TABLE llx_prelevement_facture_demande ADD INDEX idx_prelevement_facture_demande_fk_facture (fk_facture);
 ALTER TABLE llx_prelevement_facture_demande ADD INDEX idx_prelevement_facture_demande_fk_facture_fourn (fk_facture_fourn);
+
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,note,active) values (721, 72,    '0','0','VAT Rate 0',1);
+insert into llx_c_tva(rowid,fk_pays,taux,recuperableonly,localtax1,localtax1_type,note,active) values (722, 72,   '18','0', '0.9', '1', 'VAT Rate 18+0.9', 1);

+ 1 - 0
htdocs/langs/en_US/banks.lang

@@ -37,6 +37,7 @@ IbanValid=BAN valid
 IbanNotValid=BAN not valid
 StandingOrders=Direct debit orders
 StandingOrder=Direct debit order
+PaymentByDirectDebit=Payment by direct debit
 PaymentByBankTransfers=Payments by credit transfer
 PaymentByBankTransfer=Payment by credit transfer
 AccountStatement=Account statement

+ 2 - 1
htdocs/langs/en_US/cashdesk.lang

@@ -115,4 +115,5 @@ ScanToOrder=Scan QR code to order
 Appearance=Appearance
 HideCategoryImages=Hide Category Images
 HideProductImages=Hide Product Images
-NumberOfLinesToShow=Number of lines to show in image box
+NumberOfLinesToShow=Number of lines to show in image box
+DefineTablePlan=Define table plan

+ 1 - 0
htdocs/langs/en_US/holiday.lang

@@ -15,6 +15,7 @@ CancelCP=Canceled
 RefuseCP=Refused
 ValidatorCP=Approbator
 ListeCP=List of leave
+Leave=Leave request
 LeaveId=Leave ID
 ReviewedByCP=Will be approved by
 UserID=User ID

+ 2 - 2
htdocs/langs/en_US/withdrawals.lang

@@ -10,8 +10,8 @@ PaymentByBankTransferReceipts=Credit transfer orders
 PaymentByBankTransferLines=Credit transfer order lines
 WithdrawalsReceipts=Direct debit orders
 WithdrawalReceipt=Direct debit order
-BankTransferReceipts=Credit transfer receipts
-BankTransferReceipt=Credit transfer receipt
+BankTransferReceipts=Credit transfer order
+BankTransferReceipt=Credit transfer order
 LatestBankTransferReceipts=Latest %s credit transfer orders
 LastWithdrawalReceipts=Latest %s direct debit files
 WithdrawalsLine=Direct debit order line

+ 1 - 1
htdocs/master.inc.php

@@ -49,7 +49,7 @@ $conf->db->host							= $dolibarr_main_db_host;
 $conf->db->port							= $dolibarr_main_db_port;
 $conf->db->name							= $dolibarr_main_db_name;
 $conf->db->user							= $dolibarr_main_db_user;
-$conf->db->pass							= $dolibarr_main_db_pass;
+$conf->db->pass							= empty($dolibarr_main_db_pass)?'':$dolibarr_main_db_pass;
 $conf->db->type							= $dolibarr_main_db_type;
 $conf->db->prefix = $dolibarr_main_db_prefix;
 $conf->db->character_set = $dolibarr_main_db_character_set;

+ 5 - 0
htdocs/societe/card.php

@@ -849,6 +849,11 @@ if (empty($reshook))
     $id = $socid;
     $object->fetch($socid);
 
+	// Selection of new fields
+	if (!empty($conf->global->MAIN_DUPLICATE_CONTACTS_TAB_ON_MAIN_CARD) && (empty($conf->global->SOCIETE_DISABLE_CONTACTS) || !empty($conf->global->SOCIETE_ADDRESSES_MANAGEMENT))) {
+		include DOL_DOCUMENT_ROOT . '/core/actions_changeselectedfields.inc.php';
+	}
+
     // Actions to send emails
     $triggersendname = 'COMPANY_SENTBYMAIL';
     $paramname = 'socid';

+ 10 - 10
htdocs/societe/class/societe.class.php

@@ -2339,37 +2339,37 @@ class Societe extends CommonObject
 
 		$label .= '<div class="centpercent">';
 
-		if ($option == 'customer' || $option == 'compta' || $option == 'category' || $option == 'category_supplier')
+		if ($option == 'customer' || $option == 'compta' || $option == 'category')
 		{
-		    $label .= '<u>'.$langs->trans("ShowCustomer").'</u>';
+		    $label .= '<u>'.$langs->trans("Customer").'</u>';
 		    $linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
 		} elseif ($option == 'prospect' && empty($conf->global->SOCIETE_DISABLE_PROSPECTS))
 		{
-			$label .= '<u>'.$langs->trans("ShowProspect").'</u>';
+			$label .= '<u>'.$langs->trans("Prospect").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/comm/card.php?socid='.$this->id;
-		} elseif ($option == 'supplier')
+		} elseif ($option == 'supplier' || $option == 'category_supplier')
 		{
-			$label .= '<u>'.$langs->trans("ShowSupplier").'</u>';
+			$label .= '<u>'.$langs->trans("Supplier").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$this->id;
 		} elseif ($option == 'agenda')
 		{
-			$label .= '<u>'.$langs->trans("ShowAgenda").'</u>';
+			$label .= '<u>'.$langs->trans("ThirdParty").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/agenda.php?socid='.$this->id;
 		} elseif ($option == 'project')
 		{
-			$label .= '<u>'.$langs->trans("ShowProject").'</u>';
+			$label .= '<u>'.$langs->trans("ThirdParty").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/project.php?socid='.$this->id;
 		} elseif ($option == 'margin')
 		{
-			$label .= '<u>'.$langs->trans("ShowMargin").'</u>';
+			$label .= '<u>'.$langs->trans("ThirdParty").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/margin/tabs/thirdpartyMargins.php?socid='.$this->id.'&type=1';
 		} elseif ($option == 'contact')
 		{
-			$label .= '<u>'.$langs->trans("ShowContacts").'</u>';
+			$label .= '<u>'.$langs->trans("ThirdParty").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/contact.php?socid='.$this->id;
 		} elseif ($option == 'ban')
 		{
-			$label .= '<u>'.$langs->trans("ShowBan").'</u>';
+			$label .= '<u>'.$langs->trans("ThirdParty").'</u>';
 			$linkstart = '<a href="'.DOL_URL_ROOT.'/societe/paymentmodes.php?socid='.$this->id;
 		}
 

+ 16 - 1
htdocs/societe/paymentmodes.php

@@ -1766,29 +1766,44 @@ if ($socid && $action == 'create' && $user->rights->societe->creer)
 	// Show fields of bank account
 	foreach ($companybankaccount->getFieldsToShow(1) as $val) {
 		$require = false;
+		$tooltip = '';
 		if ($val == 'BankCode') {
 			$name = 'code_banque';
 			$size = 8;
+			$content = $companybankaccount->code_banque;
 		} elseif ($val == 'DeskCode') {
 			$name = 'code_guichet';
 			$size = 8;
+			$content = $companybankaccount->code_guichet;
 		} elseif ($val == 'BankAccountNumber') {
 			$name = 'number';
 			$size = 18;
+			$content = $companybankaccount->number;
 		} elseif ($val == 'BankAccountNumberKey') {
 			$name = 'cle_rib';
 			$size = 3;
+			$content = $companybankaccount->cle_rib;
 		} elseif ($val == 'IBAN') {
 			$name = 'iban';
 			$size = 30;
+			$content = $companybankaccount->iban;
 			if ($companybankaccount->needIBAN()) $require = true;
+			$tooltip = $langs->trans("Example").':<br>LT12 1000 0111 0100 1000<br>FR14 2004 1010 0505 0001 3M02 606<br>LU28 0019 4006 4475 0000<br>DE89 3704 0044 0532 0130 00';
 		} elseif ($val == 'BIC') {
 			$name = 'bic';
 			$size = 12;
+			$content = $companybankaccount->bic;
 			if ($companybankaccount->needIBAN()) $require = true;
+			$tooltip = $langs->trans("Example").': LIABLT2XXXX';
 		}
 
-		print '<tr><td'.($require ? ' class="fieldrequired" ' : '').'>'.$langs->trans($val).'</td>';
+		print '<tr><td'.($require ? ' class="fieldrequired" ' : '').'>';
+		if ($tooltip) {
+			print $form->textwithpicto($langs->trans($val), $tooltip, 4, 'help', '', 0, 3, $name);
+		} else {
+			print $langs->trans($val);
+		}
+		print '</td>';
 		print '<td><input size="'.$size.'" type="text" class="flat" name="'.$name.'" value="'.GETPOST($name).'"></td>';
 		print '</tr>';
 	}

+ 20 - 3
htdocs/takepos/admin/bar.php

@@ -66,12 +66,14 @@ if (GETPOST('action', 'alpha') == 'set')
 $form = new Form($db);
 $formproduct = new FormProduct($db);
 
-llxHeader('', $langs->trans("CashDeskSetup"));
+$arrayofcss = array("/takepos/css/colorbox.css");
+
+llxHeader('', $langs->trans("CashDeskSetup"), '', '', 0, 0, $arrayofjs, $arrayofcss);
 
 $linkback = '<a href="'.DOL_URL_ROOT.'/admin/modules.php">'.$langs->trans("BackToModuleList").'</a>';
 print load_fiche_titre($langs->trans("CashDeskSetup").' (TakePOS)', $linkback, 'title_setup');
 $head = takepos_prepare_head();
-dol_fiche_head($head, 'bar', 'TakePOS', -1);
+dol_fiche_head($head, 'bar', 'TakePOS', -1, 'cash-register');
 print '<br>';
 
 
@@ -80,6 +82,20 @@ print '<form action="'.$_SERVER["PHP_SELF"].'" method="post">';
 print '<input type="hidden" name="token" value="'.newToken().'">';
 print '<input type="hidden" name="action" value="set">';
 
+?>
+<script type="text/javascript" src="<?php echo DOL_URL_ROOT ?>/takepos/js/jquery.colorbox-min.js"></script>	<!-- TODO It seems we don't need this -->
+<script type="text/javascript">
+function Floors() {
+	console.log("Open box to select floor");
+	$.colorbox({href:"<?php echo DOL_URL_ROOT ?>/takepos/floors.php?mode=edit&place=0", width:"90%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("Floors"); ?>"});
+}
+</script>
+
+<?php
+
+print '<a href="" onclick="Floors(); return false;"><span class="fa fa-glass-cheers"></span> '.$langs->trans("DefineTablePlan").'</a><br>';
+print '<br><br>';
+
 print '<div class="div-table-responsive">';
 print '<table class="noborder centpercent">';
 print '<tr class="liste_titre">';
@@ -138,9 +154,9 @@ print '<td colspan="2">';
 print ajax_constantonoff("TAKEPOS_QR_MENU", array(), $conf->entity, 0, 0, 1, 0);
 print '</td></tr>';
 
-
 print '</table>';
 
+
 if ($conf->global->TAKEPOS_AUTO_ORDER)
 {
 	print '<br>';
@@ -168,6 +184,7 @@ if ($conf->global->TAKEPOS_AUTO_ORDER)
 	print '</table>';
 }
 
+
 if ($conf->global->TAKEPOS_QR_MENU)
 {
 	$urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));

+ 1 - 0
htdocs/takepos/admin/setup.php

@@ -118,6 +118,7 @@ if ($action != '') {
 	}
 }
 
+
 /*
  * View
  */

+ 8 - 2
htdocs/takepos/index.php

@@ -431,7 +431,7 @@ function CloseBill() {
 }
 
 function Floors() {
-	console.log("Open box to select floor");
+	console.log("Open box to select floor place="+place);
 	$.colorbox({href:"floors.php?place="+place, width:"90%", height:"90%", transition:"none", iframe:"true", title:"<?php echo $langs->trans("Floors"); ?>"});
 }
 
@@ -928,7 +928,13 @@ if ($resql)
 $hookmanager->initHooks(array('takeposfrontend'));
 $reshook = $hookmanager->executeHooks('ActionButtons');
 if (!empty($reshook)) {
-    $menus[$r++] = $reshook;
+	if (is_array($reshook) && !isset($reshook['title'])) {
+		foreach ($reshook as $reshook) {
+			$menus[$r++] = $reshook;
+		}
+	} else {
+		$menus[$r++] = $reshook;
+	}
 }
 
 if ($r % 3 == 2) $menus[$r++] = array('title'=>'', 'style'=>'visibility: hidden;');