1<?php
2/* Copyright (C) 2005      Rodolphe Quiedeville  <rodolphe@quiedeville.org>
3 * Copyright (C) 2005      Marc Barilley / Ocebo <marc@ocebo.com>
4 * Copyright (C) 2006-2010 Laurent Destailleur   <eldy@users.sourceforge.net>
5 * Copyright (C) 2014      Marcos García         <marcosgdf@gmail.com>
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/fourn/paiement/card.php
23 *	\ingroup    facture, fournisseur
24 *	\brief      Tab to show a payment of a supplier invoice
25 *	\remarks	Fichier presque identique a compta/paiement/card.php
26 */
27
28require '../../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
30require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php';
31require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.class.php';
32require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
34
35$langs->loadLangs(array('bills', 'banks', 'companies', 'suppliers'));
36
37$id = GETPOST('id', 'int');
38$action		= GETPOST('action', 'alpha');
39$confirm	= GETPOST('confirm', 'alpha');
40
41$object = new PaiementFourn($db);
42// Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
43$hookmanager->initHooks(array('supplierpaymentcard', 'globalcard'));
44
45// Load object
46include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be include, not include_once.
47
48$result = restrictedArea($user, $object->element, $object->id, 'paiementfourn', '');
49
50// Security check
51if ($user->socid) {
52	$socid = $user->socid;
53}
54// Now check also permission on thirdparty of invoices of payments. Thirdparty were loaded by the fetch_object before based on first invoice.
55// It should be enough because all payments are done on invoices of the same thirdparty.
56if ($socid && $socid != $object->thirdparty->id) {
57	accessforbidden();
58}
59
60
61/*
62 * Actions
63 */
64
65if ($action == 'setnote' && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)) {
66	$db->begin();
67
68	$object->fetch($id);
69	$result = $object->update_note(GETPOST('note', 'restricthtml'));
70	if ($result > 0) {
71		$db->commit();
72		$action = '';
73	} else {
74		setEventMessages($object->error, $object->errors, 'errors');
75		$db->rollback();
76	}
77}
78
79if ($action == 'confirm_delete' && $confirm == 'yes' && $user->rights->fournisseur->facture->supprimer) {
80	$db->begin();
81
82	$object->fetch($id);
83	$result = $object->delete();
84	if ($result > 0) {
85		$db->commit();
86		header('Location: '.DOL_URL_ROOT.'/fourn/paiement/list.php');
87		exit;
88	} else {
89		setEventMessages($object->error, $object->errors, 'errors');
90		$db->rollback();
91	}
92}
93
94if ($action == 'confirm_validate' && $confirm == 'yes' &&
95	((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && (!empty($user->rights->fournisseur->facture->creer) || !empty($user->rights->supplier_invoice->creer)))
96	|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate)))
97) {
98	$db->begin();
99
100	$object->fetch($id);
101	if ($object->validate() >= 0) {
102		$db->commit();
103		header('Location: '.$_SERVER['PHP_SELF'].'?id='.$object->id);
104		exit;
105	} else {
106		setEventMessages($object->error, $object->errors, 'errors');
107		$db->rollback();
108	}
109}
110
111if ($action == 'setnum_paiement' && !empty($_POST['num_paiement'])) {
112	$object->fetch($id);
113	$res = $object->update_num($_POST['num_paiement']);
114	if ($res === 0) {
115		setEventMessages($langs->trans('PaymentNumberUpdateSucceeded'), null, 'mesgs');
116	} else {
117		setEventMessages($langs->trans('PaymentNumberUpdateFailed'), null, 'errors');
118	}
119}
120
121if ($action == 'setdatep' && !empty($_POST['datepday'])) {
122	$object->fetch($id);
123	$datepaye = dol_mktime(GETPOST('datephour', 'int'), GETPOST('datepmin', 'int'), GETPOST('datepsec', 'int'), GETPOST('datepmonth', 'int'), GETPOST('datepday', 'int'), GETPOST('datepyear', 'int'));
124	$res = $object->update_date($datepaye);
125	if ($res === 0) {
126		setEventMessages($langs->trans('PaymentDateUpdateSucceeded'), null, 'mesgs');
127	} else {
128		setEventMessages($langs->trans('PaymentDateUpdateFailed'), null, 'errors');
129	}
130}
131
132// Build document
133$upload_dir = $conf->fournisseur->payment->dir_output;
134// TODO: get the appropriate permission
135$permissiontoadd = true;
136include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php';
137
138
139/*
140 * View
141 */
142
143llxHeader();
144
145$result = $object->fetch($id);
146
147$form = new Form($db);
148$formfile = new FormFile($db);
149
150$head = payment_supplier_prepare_head($object);
151
152print dol_get_fiche_head($head, 'payment', $langs->trans('SupplierPayment'), -1, 'payment');
153
154if ($result > 0) {
155	/*
156	 * Confirmation of payment's delete
157	 */
158	if ($action == 'delete') {
159		print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("DeletePayment"), $langs->trans("ConfirmDeletePayment"), 'confirm_delete');
160	}
161
162	/*
163	 * Confirmation of payment's validation
164	 */
165	if ($action == 'validate') {
166		print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans("ValidatePayment"), $langs->trans("ConfirmValidatePayment"), 'confirm_validate');
167	}
168
169	$linkback = '<a href="'.DOL_URL_ROOT.'/fourn/paiement/list.php'.(!empty($socid) ? '?socid='.$socid : '').'">'.$langs->trans("BackToList").'</a>';
170
171
172	dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref');
173
174	print '<div class="fichecenter">';
175	print '<div class="underbanner clearboth"></div>';
176
177	print '<table class="border centpercent">';
178
179	/*print '<tr>';
180	print '<td width="20%">'.$langs->trans('Ref').'</td><td>';
181	print $form->showrefnav($object,'id','',1,'rowid','ref');
182	print '</td></tr>';*/
183
184	// Date of payment
185	print '<tr><td class="titlefield">'.$form->editfieldkey("Date", 'datep', $object->date, $object, $object->statut == 0 && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)).'</td>';
186	print '<td>';
187	print $form->editfieldval("Date", 'datep', $object->date, $object, $object->statut == 0 && ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer), 'datehourpicker', '', null, $langs->trans('PaymentDateUpdateSucceeded'));
188	print '</td></tr>';
189
190	// Payment mode
191	$labeltype = $langs->trans("PaymentType".$object->type_code) != ("PaymentType".$object->type_code) ? $langs->trans("PaymentType".$object->type_code) : $object->type_label;
192	print '<tr><td>'.$langs->trans('PaymentMode').'</td>';
193	print '<td>'.$labeltype;
194	print $object->num_payment ? ' - '.$object->num_payment : '';
195	print '</td></tr>';
196
197	// Payment numero
198	/* TODO Add field num_payment into payment table and save it
199	print '<tr><td>'.$form->editfieldkey("Numero",'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer).'</td>';
200	print '<td>';
201	print $form->editfieldval("Numero",'num_paiement',$object->num_paiement,$object,$object->statut == 0 && $user->rights->fournisseur->facture->creer,'string','',null,$langs->trans('PaymentNumberUpdateSucceeded'));
202	print '</td></tr>';
203	*/
204
205	// Amount
206	print '<tr><td>'.$langs->trans('Amount').'</td>';
207	print '<td>'.price($object->amount, '', $langs, 0, 0, -1, $conf->currency).'</td></tr>';
208
209	if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) {
210		print '<tr><td>'.$langs->trans('Status').'</td>';
211		print '<td>'.$object->getLibStatut(4).'</td></tr>';
212	}
213
214	$allow_delete = 1;
215	// Bank account
216	if (!empty($conf->banque->enabled)) {
217		if ($object->fk_account) {
218			$bankline = new AccountLine($db);
219			$bankline->fetch($object->bank_line);
220			if ($bankline->rappro) {
221				$allow_delete = 0;
222				$title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemoveConciliatedPayment"));
223			}
224
225			print '<tr>';
226			print '<td>'.$langs->trans('BankAccount').'</td>';
227			print '<td>';
228			$accountstatic = new Account($db);
229			$accountstatic->fetch($bankline->fk_account);
230			print $accountstatic->getNomUrl(1);
231			print '</td>';
232			print '</tr>';
233
234			print '<tr>';
235			print '<td>'.$langs->trans('BankTransactionLine').'</td>';
236			print '<td>';
237			print $bankline->getNomUrl(1, 0, 'showconciliated');
238			print '</td>';
239			print '</tr>';
240		}
241	}
242
243	// Note
244	print '<tr><td>'.$form->editfieldkey("Comments", 'note', $object->note, $object, ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer)).'</td>';
245	print '<td>';
246	print $form->editfieldval("Note", 'note', $object->note, $object, ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer), 'textarea');
247	print '</td></tr>';
248
249	print '</table>';
250
251	print '</div>';
252
253	print '<br>';
254
255	/**
256	 *	List of seller's invoices
257	 */
258	$sql = 'SELECT f.rowid, f.rowid as facid, f.ref, f.ref_supplier, f.type, f.paye, f.total_ht, f.total_tva, f.total_ttc, f.datef as date, f.fk_statut as status,';
259	$sql .= ' pf.amount, s.nom as name, s.rowid as socid';
260	$sql .= ' FROM '.MAIN_DB_PREFIX.'paiementfourn_facturefourn as pf,'.MAIN_DB_PREFIX.'facture_fourn as f,'.MAIN_DB_PREFIX.'societe as s';
261	$sql .= ' WHERE pf.fk_facturefourn = f.rowid AND f.fk_soc = s.rowid';
262	$sql .= ' AND pf.fk_paiementfourn = '.$object->id;
263	$resql = $db->query($sql);
264	if ($resql) {
265		$num = $db->num_rows($resql);
266
267		$i = 0;
268		$total = 0;
269
270		print '<table class="noborder centpercent">';
271		print '<tr class="liste_titre">';
272		print '<td>'.$langs->trans('Invoice').'</td>';
273		print '<td>'.$langs->trans('RefSupplier').'</td>';
274		print '<td>'.$langs->trans('Company').'</td>';
275		print '<td class="right">'.$langs->trans('ExpectedToPay').'</td>';
276		print '<td class="right">'.$langs->trans('PayedByThisPayment').'</td>';
277		print '<td class="right">'.$langs->trans('Status').'</td>';
278		print "</tr>\n";
279
280		if ($num > 0) {
281			$facturestatic = new FactureFournisseur($db);
282
283			while ($i < $num) {
284				$objp = $db->fetch_object($resql);
285
286				$facturestatic->id = $objp->facid;
287				$facturestatic->ref = ($objp->ref ? $objp->ref : $objp->rowid);
288				$facturestatic->date = $db->jdate($objp->date);
289				$facturestatic->type = $objp->type;
290				$facturestatic->total_ht = $objp->total_ht;
291				$facturestatic->total_tva = $objp->total_tva;
292				$facturestatic->total_ttc = $objp->total_ttc;
293				$facturestatic->statut = $objp->status;
294				$facturestatic->alreadypaid = -1; // unknown
295
296				print '<tr class="oddeven">';
297				// Ref
298				print '<td>';
299				print $facturestatic->getNomUrl(1);
300				print "</td>\n";
301				// Ref supplier
302				print '<td>'.$objp->ref_supplier."</td>\n";
303				// Third party
304				print '<td><a href="'.DOL_URL_ROOT.'/fourn/card.php?socid='.$objp->socid.'">'.img_object($langs->trans('ShowCompany'), 'company').' '.$objp->name.'</a></td>';
305				// Expected to pay
306				print '<td class="right">'.price($objp->total_ttc).'</td>';
307				// Paid
308				print '<td class="right">'.price($objp->amount).'</td>';
309				// Status
310				print '<td class="right">'.$facturestatic->LibStatut($objp->paye, $objp->status, 6, 1).'</td>';
311				print "</tr>\n";
312
313				if ($objp->paye == 1) {
314					$allow_delete = 0;
315					$title_button = dol_escape_htmltag($langs->transnoentitiesnoconv("CantRemovePaymentWithOneInvoicePaid"));
316				}
317				$total = $total + $objp->amount;
318				$i++;
319			}
320		}
321
322
323		print "</table>\n";
324		$db->free($resql);
325	} else {
326		dol_print_error($db);
327	}
328
329	print '</div>';
330
331
332	/*
333	 * Actions Buttons
334	 */
335
336	print '<div class="tabsAction">';
337	if (!empty($conf->global->BILL_ADD_PAYMENT_VALIDATION)) {
338		if ($user->socid == 0 && $object->statut == 0 && $action == '') {
339			if ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && (!empty($user->rights->fournisseur->facture->creer) || !empty($user->rights->supplier_invoice->creer)))
340			|| (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->fournisseur->supplier_invoice_advance->validate))) {
341				print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=validate">'.$langs->trans('Valid').'</a>';
342			}
343		}
344	}
345	if ($user->socid == 0 && $action == '') {
346		if ($user->rights->fournisseur->facture->supprimer) {
347			if ($allow_delete) {
348				print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&amp;action=delete&amp;token='.newToken().'">'.$langs->trans('Delete').'</a>';
349			} else {
350				print '<a class="butActionRefused classfortooltip" href="#" title="'.$title_button.'">'.$langs->trans('Delete').'</a>';
351			}
352		}
353	}
354	print '</div>';
355
356
357	print '<div class="fichecenter"><div class="fichehalfleft">';
358
359	// Generated documents
360	include_once DOL_DOCUMENT_ROOT.'/core/modules/supplier_payment/modules_supplier_payment.php';
361	$modellist = ModelePDFSuppliersPayments::liste_modeles($db);
362	if (is_array($modellist)) {
363		$ref = dol_sanitizeFileName($object->ref);
364		$filedir = $conf->fournisseur->payment->dir_output.'/'.dol_sanitizeFileName($object->ref);
365		$urlsource = $_SERVER['PHP_SELF'].'?id='.$object->id;
366		$genallowed = ($user->rights->fournisseur->facture->lire || $user->rights->supplier_invoice->lire);
367		$delallowed = ($user->rights->fournisseur->facture->creer || $user->rights->supplier_invoice->creer);
368		$modelpdf = (!empty($object->model_pdf) ? $object->model_pdf : (empty($conf->global->SUPPLIER_PAYMENT_ADDON_PDF) ? '' : $conf->global->SUPPLIER_PAYMENT_ADDON_PDF));
369
370		print $formfile->showdocuments('supplier_payment', $ref, $filedir, $urlsource, $genallowed, $delallowed, $modelpdf, 1, 0, 0, 40, 0, '', '', '', $societe->default_lang);
371		$somethingshown = $formfile->numoffiles;
372	}
373
374	print '</div><div class="fichehalfright"><div class="ficheaddleft">';
375	//print '<br>';
376
377	// List of actions on element
378	/*include_once DOL_DOCUMENT_ROOT.'/core/class/html.formactions.class.php';
379	$formactions=new FormActions($db);
380	$somethingshown = $formactions->showactions($object,'supplier_payment',$socid,1,'listaction'.($genallowed?'largetitle':''));
381	*/
382
383	print '</div></div></div>';
384} else {
385	$langs->load("errors");
386	print $langs->trans("ErrorRecordNotFound");
387}
388
389print dol_get_fiche_end();
390
391// End of page
392llxFooter();
393$db->close();
394