1<?php
2/* Copyright (C) 2005       Rodolphe Quiedeville    <rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2010  Laurent Destailleur     <eldy@users.sourceforge.net>
4 * Copyright (C) 2010-2016  Juanjo Menent           <jmenent@2byte.es>
5 * Copyright (C) 2018-2021  Frédéric France         <frederic.france@netlogic.fr>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21/**
22 *	\file       htdocs/compta/prelevement/card.php
23 *	\ingroup    prelevement
24 *	\brief      Card of a direct debit
25 */
26
27require '../../main.inc.php';
28require_once DOL_DOCUMENT_ROOT.'/core/lib/prelevement.lib.php';
29require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php';
30require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php';
31require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
32
33// Load translation files required by the page
34$langs->loadLangs(array('banks', 'categories', 'bills', 'companies', 'withdrawals'));
35
36// Security check
37if ($user->socid > 0) {
38	accessforbidden();
39}
40
41// Get supervariables
42$action = GETPOST('action', 'aZ09');
43$id = GETPOST('id', 'int');
44$ref = GETPOST('ref', 'alpha');
45$socid = GETPOST('socid', 'int');
46$type = GETPOST('type', 'aZ09');
47
48// Load variable for pagination
49$limit = GETPOST('limit', 'int') ?GETPOST('limit', 'int') : $conf->liste_limit;
50$sortfield = GETPOST('sortfield', 'aZ09comma');
51$sortorder = GETPOST('sortorder', 'aZ09comma');
52$page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int');
53if (empty($page) || $page == -1) {
54	$page = 0;
55}     // If $page is not defined, or '' or -1
56$offset = $limit * $page;
57$pageprev = $page - 1;
58$pagenext = $page + 1;
59
60if (!$sortfield) {
61	$sortfield = 'pl.fk_soc';
62}
63if (!$sortorder) {
64	$sortorder = 'DESC';
65}
66
67$object = new BonPrelevement($db);
68
69// Load object
70include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once  // Must be include, not include_once. Include fetch and fetch_thirdparty but not fetch_optionals
71
72$hookmanager->initHooks(array('directdebitprevcard', 'globalcard', 'directdebitprevlist'));
73
74if (!$user->rights->prelevement->bons->lire && $object->type != 'bank-transfer') {
75	accessforbidden();
76}
77if (!$user->rights->paymentbybanktransfer->read && $object->type == 'bank-transfer') {
78	accessforbidden();
79}
80
81
82/*
83 * Actions
84 */
85
86$parameters = array('socid' => $socid);
87$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
88if ($reshook < 0) {
89	setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
90}
91
92if (empty($reshook)) {
93	if ($action == 'confirm_delete') {
94		$res = $object->delete($user);
95		if ($res > 0) {
96			if ($object->type == 'bank-transfer') {
97				header("Location: ".DOL_URL_ROOT.'/compta/paymentbybanktransfer/index.php');
98			} else {
99				header("Location: ".DOL_URL_ROOT.'/compta/prelevement/index.php');
100			}
101			exit;
102		}
103	}
104
105	// Seems to no be used and replaced with $action == 'infocredit'
106	if ($action == 'confirm_credite' && GETPOST('confirm', 'alpha') == 'yes') {
107		if ($object->statut == 2) {
108			$res = -1;
109			setEventMessages('WithdrawalCantBeCreditedTwice', array(), 'errors');
110		} else {
111			$res = $object->set_credite();
112		}
113
114		if ($res >= 0) {
115			header("Location: card.php?id=".$id);
116			exit;
117		}
118	}
119
120	if ($action == 'infotrans' && $user->rights->prelevement->bons->send) {
121		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
122
123		$dt = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
124
125		/*
126		if ($_FILES['userfile']['name'] && basename($_FILES['userfile']['name'],".ps") == $object->ref)
127		{
128			$dir = $conf->prelevement->dir_output.'/receipts';
129
130			if (dol_move_uploaded_file($_FILES['userfile']['tmp_name'], $dir . "/" . dol_unescapefile($_FILES['userfile']['name']),1) > 0)
131			{
132				$object->set_infotrans($user, $dt, GETPOST('methode','alpha'));
133			}
134
135			header("Location: card.php?id=".$id);
136			exit;
137		}
138		else
139		{
140			dol_syslog("Fichier invalide",LOG_WARNING);
141			$mesg='BadFile';
142		}*/
143
144		$error = $object->set_infotrans($user, $dt, GETPOST('methode', 'alpha'));
145
146		if ($error) {
147			header("Location: card.php?id=".$id."&error=$error");
148			exit;
149		}
150	}
151
152	// Set direct debit order to credited, create payment and close invoices
153	if ($action == 'infocredit' && $user->rights->prelevement->bons->credit) {
154		$dt = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
155
156		if ($object->statut == 2) {
157			$error = 1;
158			setEventMessages('WithdrawalCantBeCreditedTwice', array(), 'errors');
159		} else {
160			$error = $object->set_infocredit($user, $dt);
161		}
162
163		if ($error) {
164			setEventMessages($object->error, $object->errors, 'errors');
165		}
166	}
167}
168
169
170
171/*
172 * View
173 */
174
175$form = new Form($db);
176
177llxHeader('', $langs->trans("WithdrawalsReceipts"));
178
179if ($id > 0 || $ref) {
180	$head = prelevement_prepare_head($object);
181	print dol_get_fiche_head($head, 'prelevement', $langs->trans("WithdrawalsReceipts"), -1, 'payment');
182
183	if (GETPOST('error', 'alpha') != '') {
184		print '<div class="error">'.$object->getErrorString(GETPOST('error', 'alpha')).'</div>';
185	}
186
187	/*if ($action == 'credite')
188	{
189		print $form->formconfirm("card.php?id=".$object->id,$langs->trans("ClassCredited"),$langs->trans("ClassCreditedConfirm"),"confirm_credite",'',1,1);
190
191	}*/
192
193	$linkback = '<a href="'.DOL_URL_ROOT.'/compta/prelevement/orders_list.php?restore_lastsearch_values=1'.($object->type != 'bank-transfer' ? '' : '&type=bank-transfer').'">'.$langs->trans("BackToList").'</a>';
194
195	dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref');
196
197	print '<div class="fichecenter">';
198	print '<div class="underbanner clearboth"></div>';
199	print '<table class="border centpercent tableforfield">';
200
201	//print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td>'.$object->getNomUrl(1).'</td></tr>';
202	print '<tr><td class="titlefield">'.$langs->trans("Date").'</td><td>'.dol_print_date($object->datec, 'day').'</td></tr>';
203
204	print '<tr><td>'.$langs->trans("Amount").'</td><td><span class="amount">'.price($object->amount).'</span></td></tr>';
205
206	// Status
207	/*
208	print '<tr><td>'.$langs->trans('Status').'</td>';
209	print '<td>'.$object->getLibStatut(1).'</td>';
210	print '</tr>';
211	*/
212
213	if ($object->date_trans <> 0) {
214		$muser = new User($db);
215		$muser->fetch($object->user_trans);
216
217		print '<tr><td>'.$langs->trans("TransData").'</td><td>';
218		print dol_print_date($object->date_trans, 'day');
219		print ' <span class="opacitymedium">'.$langs->trans("By").'</span> '.$muser->getFullName($langs).'</td></tr>';
220		print '<tr><td>'.$langs->trans("TransMetod").'</td><td>';
221		print $object->methodes_trans[$object->method_trans];
222		print '</td></tr>';
223	}
224	if ($object->date_credit <> 0) {
225		print '<tr><td>'.$langs->trans('CreditDate').'</td><td>';
226		print dol_print_date($object->date_credit, 'day');
227		print '</td></tr>';
228	}
229
230	print '</table>';
231
232	print '<br>';
233
234	print '<div class="underbanner clearboth"></div>';
235	print '<table class="border centpercent tableforfield">';
236
237	$acc = new Account($db);
238	$result = $acc->fetch(($object->type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT));
239
240	print '<tr><td class="titlefield">';
241	$labelofbankfield = "BankToReceiveWithdraw";
242	if ($object->type == 'bank-transfer') {
243		$labelofbankfield = 'BankToPayCreditTransfer';
244	}
245	print $langs->trans($labelofbankfield);
246	print '</td>';
247	print '<td>';
248	if ($acc->id > 0) {
249		print $acc->getNomUrl(1);
250	}
251	print '</td>';
252	print '</tr>';
253
254	print '<tr><td class="titlefield">';
255	$labelfororderfield = 'WithdrawalFile';
256	if ($object->type == 'bank-transfer') {
257		$labelfororderfield = 'CreditTransferFile';
258	}
259	print $langs->trans($labelfororderfield).'</td><td>';
260	$relativepath = 'receipts/'.$object->ref.'.xml';
261	$modulepart = 'prelevement';
262	if ($object->type == 'bank-transfer') {
263		$modulepart = 'paymentbybanktransfer';
264	}
265	print '<a data-ajax="false" href="'.DOL_URL_ROOT.'/document.php?type=text/plain&amp;modulepart='.$modulepart.'&amp;file='.urlencode($relativepath).'">'.$relativepath.'</a>';
266	print '</td></tr></table>';
267
268	print '</div>';
269
270	print dol_get_fiche_end();
271
272
273	$formconfirm = '';
274
275	// Confirmation to delete
276	if ($action == 'delete') {
277		$formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('Delete'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 1);
278	}
279
280	// Call Hook formConfirm
281	/*$parameters = array('formConfirm' => $formconfirm);
282	$reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
283	if (empty($reshook)) $formconfirm.=$hookmanager->resPrint;
284	elseif ($reshook > 0) $formconfirm=$hookmanager->resPrint;*/
285
286	// Print form confirm
287	print $formconfirm;
288
289
290	if (empty($object->date_trans) && $user->rights->prelevement->bons->send && $action == 'settransmitted') {
291		print '<form method="post" name="userfile" action="card.php?id='.$object->id.'" enctype="multipart/form-data">';
292		print '<input type="hidden" name="token" value="'.newToken().'">';
293		print '<input type="hidden" name="action" value="infotrans">';
294		print '<table class="noborder centpercent">';
295		print '<tr class="liste_titre">';
296		print '<td colspan="3">'.$langs->trans("NotifyTransmision").'</td></tr>';
297		print '<tr class="oddeven"><td>'.$langs->trans("TransData").'</td><td>';
298		print $form->selectDate('', '', '', '', '', "userfile", 1, 1);
299		print '</td></tr>';
300		print '<tr class="oddeven"><td>'.$langs->trans("TransMetod").'</td><td>';
301		print $form->selectarray("methode", $object->methodes_trans);
302		print '</td></tr>';
303		print '</table><br>';
304		print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("SetToStatusSent")).'"></div>';
305		print '</form>';
306		print '<br>';
307	}
308
309	if (!empty($object->date_trans) && $object->date_credit == 0 && $user->rights->prelevement->bons->credit && $action == 'setcredited') {
310		print '<form name="infocredit" method="post" action="card.php?id='.$object->id.'">';
311		print '<input type="hidden" name="token" value="'.newToken().'">';
312		print '<input type="hidden" name="action" value="infocredit">';
313		print '<table class="noborder centpercent">';
314		print '<tr class="liste_titre">';
315		print '<td colspan="3">'.$langs->trans("NotifyCredit").'</td></tr>';
316		print '<tr class="oddeven"><td>'.$langs->trans('CreditDate').'</td><td>';
317		print $form->selectDate('', '', '', '', '', "infocredit", 1, 1);
318		print '</td></tr>';
319		print '</table>';
320		print '<br><div class="center"><span class="opacitymedium">'.$langs->trans("ThisWillAlsoAddPaymentOnInvoice").'</span></div>';
321		print '<div class="center"><input type="submit" class="button" value="'.dol_escape_htmltag($langs->trans("ClassCredited")).'"></div>';
322		print '</form>';
323		print '<br>';
324	}
325
326
327	// Actions
328	if ($action != 'settransmitted' && $action != 'setcredited') {
329		print "\n".'<div class="tabsAction">'."\n";
330
331		if (empty($object->date_trans) && $user->rights->prelevement->bons->send) {
332			print '<a class="butAction" href="card.php?action=settransmitted&token='.newToken().'&id='.$object->id.'">'.$langs->trans("SetToStatusSent").'</a>';
333		}
334
335		if (!empty($object->date_trans) && $object->date_credit == 0) {
336			print '<a class="butAction" href="card.php?action=setcredited&token='.newToken().'&id='.$object->id.'">'.$langs->trans("ClassCredited").'</a>';
337		}
338
339		print '<a class="butActionDelete" href="card.php?action=delete&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Delete").'</a>';
340
341		print '</div>';
342	}
343
344
345	$ligne = new LignePrelevement($db);
346
347	/*
348	 * Lines into withdraw request
349	 */
350	$sql = "SELECT pl.rowid, pl.statut, pl.amount,";
351	$sql .= " s.rowid as socid, s.nom as name";
352	$sql .= " FROM ".MAIN_DB_PREFIX."prelevement_lignes as pl";
353	$sql .= ", ".MAIN_DB_PREFIX."prelevement_bons as pb";
354	$sql .= ", ".MAIN_DB_PREFIX."societe as s";
355	$sql .= " WHERE pl.fk_prelevement_bons = ".((int) $id);
356	$sql .= " AND pl.fk_prelevement_bons = pb.rowid";
357	$sql .= " AND pb.entity = ".$conf->entity;
358	$sql .= " AND pl.fk_soc = s.rowid";
359	if ($socid) {
360		$sql .= " AND s.rowid = ".((int) $socid);
361	}
362	$sql .= $db->order($sortfield, $sortorder);
363
364	// Count total nb of records
365	$nbtotalofrecords = '';
366	if (empty($conf->global->MAIN_DISABLE_FULL_SCANLIST)) {
367		$result = $db->query($sql);
368		$nbtotalofrecords = $db->num_rows($result);
369		if (($page * $limit) > $nbtotalofrecords) {
370			// if total resultset is smaller then paging size (filtering), goto and load page 0
371			$page = 0;
372			$offset = 0;
373		}
374	}
375
376	$sql .= $db->plimit($limit + 1, $offset);
377
378	$result = $db->query($sql);
379
380	if ($result) {
381		$num = $db->num_rows($result);
382		$i = 0;
383
384		$urladd = "&id=".urlencode($id);
385
386		print '<form method="get" action="'.$_SERVER ['PHP_SELF'].'" name="search_form">'."\n";
387		print '<input type="hidden" name="id" value="'.$id.'"/>';
388		print '<input type="hidden" name="socid" value="'.$socid.'"/>';
389		if (!empty($page)) {
390			print '<input type="hidden" name="page" value="'.$page.'"/>';
391		}
392		if (!empty($limit)) {
393			print '<input type="hidden" name="limit" value="'.$limit.'"/>';
394		}
395		print_barre_liste($langs->trans("Lines"), $page, $_SERVER["PHP_SELF"], $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, '', 0, '', '', $limit);
396
397		print '<div class="div-table-responsive-no-min">'; // You can use div-table-responsive-no-min if you dont need reserved height for your table
398		print '<table class="noborder liste" width="100%" cellpadding="4">';
399		print '<tr class="liste_titre">';
400		print_liste_field_titre("Lines", $_SERVER["PHP_SELF"], "pl.rowid", '', $urladd);
401		print_liste_field_titre("ThirdParty", $_SERVER["PHP_SELF"], "s.nom", '', $urladd);
402		print_liste_field_titre("Amount", $_SERVER["PHP_SELF"], "pl.amount", "", $urladd, 'class="right"');
403		print_liste_field_titre('');
404		print "</tr>\n";
405
406		$total = 0;
407
408		while ($i < min($num, $limit)) {
409			$obj = $db->fetch_object($result);
410
411			print '<tr class="oddeven">';
412
413			// Status of line
414			print "<td>";
415			print $ligne->LibStatut($obj->statut, 2);
416			print "&nbsp;";
417			print '<a href="'.DOL_URL_ROOT.'/compta/prelevement/line.php?id='.$obj->rowid.'&type='.$object->type.'&token='.newtoken().'">';
418			print sprintf("%06s", $obj->rowid);
419			print '</a></td>';
420
421			$thirdparty = new Societe($db);
422			$thirdparty->fetch($obj->socid);
423			print '<td>';
424			print $thirdparty->getNomUrl(1);
425			print "</td>\n";
426
427			print '<td class="right"><span class="amount">'.price($obj->amount)."</span></td>\n";
428
429			print '<td class="right">';
430
431			if ($obj->statut == 3) {
432				print '<b>'.$langs->trans("StatusRefused").'</b>';
433			} else {
434				if ($object->statut == BonPrelevement::STATUS_CREDITED) {
435					if ($obj->statut == 2) {
436						if ($user->rights->prelevement->bons->credit) {
437							//print '<a class="butActionDelete" href="line.php?action=rejet&id='.$obj->rowid.'">'.$langs->trans("StandingOrderReject").'</a>';
438							print '<a href="line.php?action=rejet&type='.$object->type.'&id='.$obj->rowid.'&token='.newtoken().'">'.$langs->trans("StandingOrderReject").'</a>';
439						} else {
440							//print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotAllowed").'">'.$langs->trans("StandingOrderReject").'</a>';
441						}
442					}
443				} else {
444					//print '<a class="butActionRefused classfortooltip" href="#" title="'.$langs->trans("NotPossibleForThisStatusOfWithdrawReceiptORLine").'">'.$langs->trans("StandingOrderReject").'</a>';
445				}
446			}
447
448			print '</td></tr>';
449
450			$total += $obj->amount;
451
452			$i++;
453		}
454
455		if ($num > 0) {
456			print '<tr class="liste_total">';
457			print '<td>'.$langs->trans("Total").'</td>';
458			print '<td>&nbsp;</td>';
459			print '<td class="right">';
460			if (empty($offset) && $num <= $limit) {
461				// If we have all record on same page, then the following test/warning can be done
462				if ($total != $object->amount) {
463					print img_warning($langs->trans("TotalAmountOfdirectDebitOrderDiffersFromSumOfLines"));
464				}
465			}
466			print price($total);
467			print "</td>\n";
468			print '<td>&nbsp;</td>';
469			print "</tr>\n";
470		}
471
472		print "</table>";
473		print '</div>';
474		print '</form>';
475
476		$db->free($result);
477	} else {
478		dol_print_error($db);
479	}
480}
481
482// End of page
483llxFooter();
484$db->close();
485