1<?php
2/* Copyright (C) 2004      Rodolphe Quiedeville  <rodolphe@quiedeville.org>
3 * Copyright (C) 2004-2011 Laurent Destailleur   <eldy@users.sourceforge.net>
4 * Copyright (C) 2005      Marc Barilley / Ocebo <marc@ocebo.com>
5 * Copyright (C) 2005-2012 Regis Houssin         <regis.houssin@inodbox.com>
6 * Copyright (C) 2013	   Marcos García		 <marcosgdf@gmail.com>
7 * Copyright (C) 2015	   Juanjo Menent		 <jmenent@2byte.es>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23/**
24 *	    \file       htdocs/compta/paiement/card.php
25 *		\ingroup    facture
26 *		\brief      Page of a customer payment
27 *		\remarks	Nearly same file than fournisseur/paiement/card.php
28 */
29
30require '../../main.inc.php';
31require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php';
32require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
33require_once DOL_DOCUMENT_ROOT.'/core/modules/facture/modules_facture.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
35if (!empty($conf->banque->enabled)) {
36	require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
37}
38
39// Load translation files required by the page
40$langs->loadLangs(array('bills', 'banks', 'companies'));
41
42$id = GETPOST('id', 'int');
43$ref = GETPOST('ref', 'alpha');
44$action = GETPOST('action', 'aZ09');
45$confirm = GETPOST('confirm', 'alpha');
46$backtopage = GETPOST('backtopage', 'alpha');
47
48$object = new Paiement($db);
49// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
50$hookmanager->initHooks(array('paymentcard', 'globalcard'));
51
52// Load object
53include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
54
55$result = restrictedArea($user, $object->element, $object->id, 'paiement', '');
56
57// Security check
58if ($user->socid) {
59	$socid = $user->socid;
60}
61// Now check also permission on thirdparty of invoices of payments. Thirdparty were loaded by the fetch_object before based on first invoice.
62// It should be enough because all payments are done on invoices of the same thirdparty.
63if ($socid && $socid != $object->thirdparty->id) {
64	accessforbidden();
65}
66
67
68/*
69 * Actions
70 */
71
72if ($action == 'setnote' && $user->rights->facture->paiement) {
73	$db->begin();
74
75	$result = $object->update_note(GETPOST('note', 'restricthtml'));
76	if ($result > 0) {
77		$db->commit();
78		$action = '';
79	} else {
80		setEventMessages($object->error, $object->errors, 'errors');
81		$db->rollback();
82	}
83}
84
85if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->facture->paiement) {
86	$db->begin();
87
88	$result = $object->delete();
89	if ($result > 0) {
90		$db->commit();
91
92		if ($backtopage) {
93			header("Location: ".$backtopage);
94			exit;
95		} else {
96			header("Location: list.php");
97			exit;
98		}
99	} else {
100		$langs->load("errors");
101		setEventMessages($object->error, $object->errors, 'errors');
102		$db->rollback();
103	}
104}
105
106if ($action == 'confirm_validate' && $confirm == 'yes' && $user->rights->facture->paiement) {
107	$db->begin();
108
109	if ($object->validate($user) > 0) {
110		$db->commit();
111
112		// Loop on each invoice linked to this payment to rebuild PDF
113		if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
114			$outputlangs = $langs;
115			if (GETPOST('lang_id', 'aZ09')) {
116				$outputlangs = new Translate("", $conf);
117				$outputlangs->setDefaultLang(GETPOST('lang_id', 'aZ09'));
118			}
119
120			$hidedetails = ! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0;
121			$hidedesc = ! empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0;
122			$hideref = !empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0;
123
124			$sql = 'SELECT f.rowid as facid';
125			$sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf,'.MAIN_DB_PREFIX.'facture as f,'.MAIN_DB_PREFIX.'societe as s';
126			$sql .= ' WHERE pf.fk_facture = f.rowid';
127			$sql .= ' AND f.fk_soc = s.rowid';
128			$sql .= ' AND f.entity IN ('.getEntity('invoice').')';
129			$sql .= ' AND pf.fk_paiement = '.$object->id;
130			$resql = $db->query($sql);
131			if ($resql) {
132				$i = 0;
133				$num = $db->num_rows($resql);
134
135				if ($num > 0) {
136					while ($i < $num) {
137						$objp = $db->fetch_object($resql);
138
139						$invoice = new Facture($db);
140
141						if ($invoice->fetch($objp->facid) <= 0) {
142							$errors++;
143							setEventMessages($invoice->error, $invoice->errors, 'errors');
144							break;
145						}
146
147						if ($invoice->generateDocument($invoice->model_pdf, $outputlangs, $hidedetails, $hidedesc, $hideref) < 0) {
148							$errors++;
149							setEventMessages($invoice->error, $invoice->errors, 'errors');
150							break;
151						}
152
153						$i++;
154					}
155				}
156
157				$db->free($resql);
158			} else {
159				$errors++;
160				setEventMessages($db->error, $db->errors, 'errors');
161			}
162		}
163
164		if (! $errors) {
165			header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id);
166			exit;
167		}
168	} else {
169		$db->rollback();
170
171		$langs->load("errors");
172		setEventMessages($object->error, $object->errors, 'errors');
173	}
174}
175
176if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) {
177	$res = $object->update_num($_POST['num_paiement']);
178	if ($res === 0) {
179		setEventMessages($langs->trans('PaymentNumberUpdateSucceeded'), null, 'mesgs');
180	} else {
181		setEventMessages($langs->trans('PaymentNumberUpdateFailed'), null, 'errors');
182	}
183}
184
185if ($action == 'setdatep' && !empty($_POST['datepday'])) {
186	$datepaye = dol_mktime(GETPOST('datephour', 'int'), GETPOST('datepmin', 'int'), GETPOST('datepsec', 'int'), GETPOST('datepmonth', 'int'), GETPOST('datepday', 'int'), GETPOST('datepyear', 'int'));
187	$res = $object->update_date($datepaye);
188	if ($res === 0) {
189		setEventMessages($langs->trans('PaymentDateUpdateSucceeded'), null, 'mesgs');
190	} else {
191		setEventMessages($langs->trans('PaymentDateUpdateFailed'), null, 'errors');
192	}
193}
194
195
196/*
197 * View
198 */
199
200llxHeader('', $langs->trans("Payment"));
201
202$thirdpartystatic = new Societe($db);
203
204$result = $object->fetch($id, $ref);
205if ($result <= 0) {
206	dol_print_error($db, 'Payement '.$id.' not found in database');
207	exit;
208}
209
210$form = new Form($db);
211
212$head = payment_prepare_head($object);
213
214print dol_get_fiche_head($head, 'payment', $langs->trans("PaymentCustomerInvoice"), -1, 'payment');
215
216// Confirmation of payment delete
217if ($action == 'delete') {
218	print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete', '', 0, 2);
219}
220
221// Confirmation of payment validation
222if ($action == 'valide') {
223	$facid = $_GET['facid'];
224	print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;facid='.$facid, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_validate', '', 0, 2);
225}
226
227$linkback = '<a href="'.DOL_URL_ROOT.'/compta/paiement/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
228
229dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', '');
230
231
232print '<div class="fichecenter">';
233print '<div class="underbanner clearboth"></div>';
234
235print '<table class="border centpercent">'."\n";
236
237// Date payment
238print '<tr><td class="titlefield">'.$form->editfieldkey("Date", 'datep', $object->date, $object, $user->rights->facture->paiement).'</td><td>';
239print $form->editfieldval("Date", 'datep', $object->date, $object, $user->rights->facture->paiement, 'datehourpicker', '', null, $langs->trans('PaymentDateUpdateSucceeded'));
240print '</td></tr>';
241
242// Payment type (VIR, LIQ, ...)
243$labeltype = $langs->trans("PaymentType".$object->type_code) != ("PaymentType".$object->type_code) ? $langs->trans("PaymentType".$object->type_code) : $object->type_label;
244print '<tr><td>'.$langs->trans('PaymentMode').'</td><td>'.$labeltype;
245print $object->num_payment ? ' - '.$object->num_payment : '';
246print '</td></tr>';
247
248// Amount
249print '<tr><td>'.$langs->trans('Amount').'</td><td>'.price($object->amount, '', $langs, 0, -1, -1, $conf->currency).'</td></tr>';
250
251$disable_delete = 0;
252// Bank account
253if (!empty($conf->banque->enabled)) {
254	$bankline = new AccountLine($db);
255
256	if ($object->fk_account > 0) {
257		$bankline->fetch($object->bank_line);
258		if ($bankline->rappro) {
259			$disable_delete = 1;
260			$title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment"));
261		}
262
263		print '<tr>';
264		print '<td>'.$langs->trans('BankAccount').'</td>';
265		print '<td>';
266		$accountstatic = new Account($db);
267		$accountstatic->fetch($bankline->fk_account);
268		print $accountstatic->getNomUrl(1);
269		print '</td>';
270		print '</tr>';
271	}
272}
273
274// Payment numero
275/*
276$titlefield=$langs->trans('Numero').' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
277print '<tr><td>'.$form->editfieldkey($titlefield,'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td><td>';
278print $form->editfieldval($titlefield,'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded'));
279print '</td></tr>';
280
281// Check transmitter
282$titlefield=$langs->trans('CheckTransmitter').' <em>('.$langs->trans("ChequeMaker").')</em>';
283print '<tr><td>'.$form->editfieldkey($titlefield,'chqemetteur',$object->,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td><td>';
284print $form->editfieldval($titlefield,'chqemetteur',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('ChequeMakeUpdateSucceeded'));
285print '</td></tr>';
286
287// Bank name
288$titlefield=$langs->trans('Bank').' <em>('.$langs->trans("ChequeBank").')</em>';
289print '<tr><td>'.$form->editfieldkey($titlefield,'chqbank',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td><td>';
290print $form->editfieldval($titlefield,'chqbank',$object->aaa,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('ChequeBankUpdateSucceeded'));
291print '</td></tr>';
292*/
293
294// Bank account
295if (!empty($conf->banque->enabled)) {
296	if ($object->fk_account > 0) {
297		if ($object->type_code == 'CHQ' && $bankline->fk_bordereau > 0) {
298			dol_include_once('/compta/paiement/cheque/class/remisecheque.class.php');
299			$bordereau = new RemiseCheque($db);
300			$bordereau->fetch($bankline->fk_bordereau);
301
302			print '<tr>';
303			print '<td>'.$langs->trans('CheckReceipt').'</td>';
304			print '<td>';
305			print $bordereau->getNomUrl(1);
306			print '</td>';
307			print '</tr>';
308		}
309	}
310
311	print '<tr>';
312	print '<td>'.$langs->trans('BankTransactionLine').'</td>';
313	print '<td>';
314	if ($object->fk_account > 0) {
315		print $bankline->getNomUrl(1, 0, 'showconciliatedandaccounted');
316	} else {
317		$langs->load("admin");
318		print '<span class="opacitymedium">'.$langs->trans("NoRecordFoundIBankcAccount", $langs->transnoentitiesnoconv("Module85Name")).'</span>';
319	}
320	print '</td>';
321	print '</tr>';
322}
323
324// Comments
325print '<tr><td class="tdtop">'.$form->editfieldkey("Comments", 'note', $object->note, $object, $user->rights->facture->paiement).'</td><td>';
326print $form->editfieldval("Note", 'note', $object->note, $object, $user->rights->facture->paiement, 'textarea:'.ROWS_3.':90%');
327print '</td></tr>';
328
329print '</table>';
330
331print '</div>';
332
333print dol_get_fiche_end();
334
335
336/*
337 * List of invoices
338 */
339
340$sql = 'SELECT f.rowid as facid, f.ref, f.type, f.total_ttc, f.paye, f.entity, f.fk_statut, pf.amount, s.nom as name, s.rowid as socid';
341$sql .= ' FROM '.MAIN_DB_PREFIX.'paiement_facture as pf,'.MAIN_DB_PREFIX.'facture as f,'.MAIN_DB_PREFIX.'societe as s';
342$sql .= ' WHERE pf.fk_facture = f.rowid';
343$sql .= ' AND f.fk_soc = s.rowid';
344$sql .= ' AND f.entity IN ('.getEntity('invoice').')';
345$sql .= ' AND pf.fk_paiement = '.$object->id;
346$resql = $db->query($sql);
347if ($resql) {
348	$num = $db->num_rows($resql);
349
350	$i = 0;
351	$total = 0;
352
353	$moreforfilter = '';
354
355	print '<br>';
356
357	print '<div class="div-table-responsive">';
358	print '<table class="noborder centpercent">';
359
360	print '<tr class="liste_titre">';
361	print '<td>'.$langs->trans('Bill').'</td>';
362	print '<td>'.$langs->trans('Company').'</td>';
363	if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED)) {
364		print '<td>'.$langs->trans('Entity').'</td>';
365	}
366	print '<td class="right">'.$langs->trans('ExpectedToPay').'</td>';
367	print '<td class="right">'.$langs->trans('PayedByThisPayment').'</td>';
368	print '<td class="right">'.$langs->trans('RemainderToPay').'</td>';
369	print '<td class="right">'.$langs->trans('Status').'</td>';
370	print "</tr>\n";
371
372	if ($num > 0) {
373		while ($i < $num) {
374			$objp = $db->fetch_object($resql);
375
376			$thirdpartystatic->fetch($objp->socid);
377
378			$invoice = new Facture($db);
379			$invoice->fetch($objp->facid);
380
381			$paiement = $invoice->getSommePaiement();
382			$creditnotes = $invoice->getSumCreditNotesUsed();
383			$deposits = $invoice->getSumDepositsUsed();
384			$alreadypayed = price2num($paiement + $creditnotes + $deposits, 'MT');
385			$remaintopay = price2num($invoice->total_ttc - $paiement - $creditnotes - $deposits, 'MT');
386
387			print '<tr class="oddeven">';
388
389			// Invoice
390			print '<td>';
391			print $invoice->getNomUrl(1);
392			print "</td>\n";
393
394			// Third party
395			print '<td class="tdoverflowmax150">';
396			print $thirdpartystatic->getNomUrl(1);
397			print '</td>';
398
399			// Expected to pay
400			if (!empty($conf->multicompany->enabled) && !empty($conf->global->MULTICOMPANY_INVOICE_SHARING_ENABLED)) {
401				print '<td>';
402				$mc->getInfo($objp->entity);
403				print $mc->label;
404				print '</td>';
405			}
406			// Expected to pay
407			print '<td class="right"><span class="amount">'.price($objp->total_ttc).'</span></td>';
408
409			// Amount payed
410			print '<td class="right"><span class="amount">'.price($objp->amount).'</span></td>';
411
412			// Remain to pay
413			print '<td class="right"><span class="amount">'.price($remaintopay).'</span></td>';
414
415			// Status
416			print '<td class="right">'.$invoice->getLibStatut(5, $alreadypayed).'</td>';
417
418			print "</tr>\n";
419
420			// If at least one invoice is paid, disable delete. INVOICE_CAN_DELETE_PAYMENT_EVEN_IF_INVOICE_CLOSED Can be use for maintenance purpose. Never use this in production
421			if ($objp->paye == 1 && empty($conf->global->INVOICE_CAN_DELETE_PAYMENT_EVEN_IF_INVOICE_CLOSED)) {
422				$disable_delete = 1;
423				$title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemovePaymentWithOneInvoicePaid"));
424			}
425
426			$total = $total + $objp->amount;
427			$i++;
428		}
429	}
430
431
432	print "</table>\n";
433	print '</div>';
434
435	$db->free($resql);
436} else {
437	dol_print_error($db);
438}
439
440
441
442/*
443 * Actions Buttons
444 */
445
446print '<div class="tabsAction">';
447
448if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) {
449	if ($user->socid == 0 && $object->statut == 0 && $_GET['action'] == '') {
450		if ($user->rights->facture->paiement) {
451			print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&amp;facid='.$objp->facid.'&amp;action=valide">'.$langs->trans('Valid').'</a>';
452		}
453	}
454}
455
456if ($user->socid == 0 && $action == '') {
457	if ($user->rights->facture->paiement) {
458		if (!$disable_delete) {
459			print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$id.'&amp;action=delete">'.$langs->trans('Delete').'</a>';
460		} else {
461			print '<a class="butActionRefused classfortooltip" href="#" title="'.$title_button.'">'.$langs->trans('Delete').'</a>';
462		}
463	}
464}
465
466print '</div>';
467
468// End of page
469llxFooter();
470$db->close();
471