dolibarr 22.0.5
payment.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2015 Alexandre Spangaro <aspangaro@open-dsi.fr>
3 * Copyright (C) 2015 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.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
27// Load Dolibarr environment
28require '../../main.inc.php';
29require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
30require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
31require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
32
41// Load translation files required by the page
42$langs->loadLangs(array('bills', 'banks', 'trips'));
43
44$id = GETPOSTINT('id');
45$ref = GETPOST('ref', 'alpha');
46$action = GETPOST('action', 'aZ09');
47$amounts = array();
48$accountid = GETPOSTINT('accountid');
49$cancel = GETPOST('cancel');
50
51// $id is the id of the expense report to pay (see link on expensereport/card.php)
52$object = new ExpenseReport($db);
53if ($id > 0 || !empty($ref)) {
54 $result = $object->fetch($id, $ref);
55 if ($result <= 0) {
57 }
58}
59
60// Security check
61$socid = 0;
62if ($user->socid > 0) {
63 $socid = $user->socid;
64}
65
66// Check the user can read this expense report: entity, and author in his hierarchy unless readall.
67// Not restrictedArea(), that would also ask for 'creer' with action=create, the link of expensereport/card.php.
68if (!$user->hasRight('expensereport', 'lire') || !checkUserAccessToObject($user, array('expensereport'), $object, 'expensereport')) {
70}
71
72$permissiontoadd = $user->hasRight('expensereport', 'to_paid');
73
74
75
76/*
77 * Actions
78 */
79
80if ($action == 'add_payment' && $permissiontoadd) {
81 $error = 0;
82
83 if ($cancel) {
84 $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id;
85 header("Location: ".$loc);
86 exit;
87 }
88
89 $expensereport = new ExpenseReport($db);
90 $result = $expensereport->fetch($id, $ref);
91 if (!$result) {
92 $error++;
93 setEventMessages($expensereport->error, $expensereport->errors, 'errors');
94 }
95 if (!$error && $expensereport->status != ExpenseReport::STATUS_APPROVED) {
96 $error++;
97 setEventMessages($langs->trans('StatusOfRefMustBe', $expensereport->ref, $langs->transnoentitiesnoconv('Approved')), null, 'errors');
98 }
99
100 $datepaid = dol_mktime(12, 0, 0, GETPOSTINT("remonth"), GETPOSTINT("reday"), GETPOSTINT("reyear"));
101
102 if (!(GETPOSTINT("fk_typepayment") > 0)) {
103 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors');
104 $error++;
105 }
106 if ($datepaid == '') {
107 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors');
108 $error++;
109 }
110
111 if (isModEnabled("bank") && !($accountid > 0)) {
112 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToDebit")), null, 'errors');
113 $error++;
114 }
115
116 if (!$error) {
117 $paymentid = 0;
118 // $total = 0;
119
120 // Read possible payments
121 foreach ($_POST as $key => $value) {
122 if (substr($key, 0, 7) == 'amount_') {
123 if (GETPOST($key)) {
124 $amounts[$expensereport->fk_user_author] = (float) price2num(GETPOST($key));
125 // $total += price2num(GETPOST($key));
126 }
127 }
128 }
129
130 if (count($amounts) <= 0) {
131 $error++;
132 setEventMessages('ErrorNoPaymentDefined', null, 'errors');
133 }
134 // A payment can't be higher than the remainder to pay
135 $remaintopay = (float) price2num($expensereport->total_ttc - $expensereport->getSumPayments(), 'MT');
136 if (!$error && (float) price2num(array_sum($amounts), 'MT') > $remaintopay) {
137 $error++;
138 setEventMessages($langs->trans('PaymentHigherThanReminderToPay'), null, 'errors');
139 }
140
141 if (!$error) {
142 $db->begin();
143
144 // Create a line of payments
145 $payment = new PaymentExpenseReport($db);
146 $payment->fk_expensereport = $expensereport->id;
147 $payment->datep = $datepaid;
148 $payment->amounts = $amounts; // array of amounts
149 // total is calculated in class
150 // $payment->total = $total;
151 $payment->fk_typepayment = GETPOSTINT("fk_typepayment");
152 $payment->num_payment = GETPOST("num_payment", 'alphanohtml');
153 $payment->note_public = GETPOST("note_public", 'restricthtml');
154 $payment->fk_bank = $accountid;
155
156 if (!$error) {
157 $paymentid = $payment->create($user);
158 if ($paymentid < 0) {
159 setEventMessages($payment->error, $payment->errors, 'errors');
160 $error++;
161 }
162 }
163
164 if (!$error) {
165 $result = $payment->addPaymentToBank($user, 'payment_expensereport', '(ExpenseReportPayment)', $accountid, '', '');
166 if ($result <= 0) {
167 setEventMessages($payment->error, $payment->errors, 'errors');
168 $error++;
169 }
170 }
171
172 if (!$error) {
173 $payment->fetch($paymentid);
174 // Set the expense report as paid when the sum of all its payments (not only this one) reaches its total
175 $remaintopay = price2num($expensereport->total_ttc - $expensereport->getSumPayments(), 'MT');
176 if ($remaintopay <= 0) {
177 $result = $expensereport->setPaid($expensereport->id, $user);
178 if (!($result > 0)) {
179 setEventMessages($payment->error, $payment->errors, 'errors');
180 $error++;
181 }
182 }
183 }
184
185 if (!$error) {
186 $db->commit();
187 $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id;
188 header('Location: '.$loc);
189 exit;
190 } else {
191 $db->rollback();
192 }
193 }
194 }
195
196 $action = 'create';
197}
198
199
200/*
201 * View
202 */
203
204llxHeader();
205
206$form = new Form($db);
207
208
209// Form to create expense report payment
210if ($action == 'create' || empty($action)) {
211 $expensereport = new ExpenseReport($db);
212 $expensereport->fetch($id, $ref);
213
214 $total = $expensereport->total_ttc;
215
216 // autofill remainder amount
217 if (!empty($conf->use_javascript_ajax)) {
218 print "\n".'<script type="text/javascript">';
219 //Add js for AutoFill
220 print ' $(document).ready(function () {';
221 print ' $(".AutoFillAmount").on(\'click touchstart\', function(){
222 var amount = $(this).data("value");
223 document.getElementById($(this).data(\'rowid\')).value = amount ;
224 });';
225 print "\t});\n";
226 print "</script>\n";
227 }
228
229 print load_fiche_titre($langs->trans("DoPayment"));
230
231 print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">';
232 print '<input type="hidden" name="token" value="'.newToken().'">';
233 print '<input type="hidden" name="id" value="'.$expensereport->id.'">';
234 print '<input type="hidden" name="chid" value="'.$expensereport->id.'">';
235 print '<input type="hidden" name="action" value="add_payment">';
236
237 print dol_get_fiche_head([], '0', '', -1);
238
239 $linkback = '';
240 // $linkback = '<a href="' . DOL_URL_ROOT . '/expensereport/payment/list.php">' . $langs->trans("BackToList") . '</a>';
241
242 dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', '');
243
244 print '<div class="fichecenter">';
245 print '<div class="underbanner clearboth"></div>';
246
247 print '<table class="border centpercent">'."\n";
248
249 print '<tr><td class="titlefield">'.$langs->trans("Period").'</td><td>'.get_date_range($expensereport->date_debut, $expensereport->date_fin, "", $langs, 0).'</td></tr>';
250 print '<tr><td>'.$langs->trans("Amount").'</td><td><span class="amount">'.price($expensereport->total_ttc, 0, $langs, 1, -1, -1, $conf->currency).'</span></td></tr>';
251
252 $sql = "SELECT sum(p.amount) as total";
253 $sql .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as p, ".MAIN_DB_PREFIX."expensereport as e";
254 $sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".((int) $id);
255 $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
256 $sumpaid = 0;
257 $resql = $db->query($sql);
258 if ($resql) {
259 $obj = $db->fetch_object($resql);
260 $sumpaid = $obj->total;
261 $db->free($resql);
262 }
263 print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td><span class="amount">'.price($sumpaid, 0, $langs, 1, -1, -1, $conf->currency).'</span></td></tr>';
264 print '<tr><td class="tdtop">'.$langs->trans("RemainderToPay").'</td><td><span class="amount">'.price($total - $sumpaid, 0, $langs, 1, -1, -1, $conf->currency).'</span></td></tr>';
265
266 print '</table>';
267
268 print '</div>';
269
270 print dol_get_fiche_end();
271
272 print '<br>';
273
274 print dol_get_fiche_head();
275
276 print '<table class="border centpercent">'."\n";
277
278 print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Date").'</td><td colspan="2">';
279 $datepaid = dol_mktime(12, 0, 0, GETPOSTINT("remonth"), GETPOSTINT("reday"), GETPOSTINT("reyear"));
280 $datepayment = ($datepaid == '' ? (!getDolGlobalString('MAIN_AUTOFILL_DATE') ? -1 : '') : $datepaid);
281 print $form->selectDate($datepayment, '', 0, 0, 0, "add_payment", 1, 1);
282 print "</td>";
283 print '</tr>';
284
285 print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td colspan="2">';
286 $form->select_types_paiements(GETPOSTISSET("fk_typepayment") ? GETPOST("fk_typepayment", 'alpha') : $expensereport->fk_c_paiement, "fk_typepayment");
287 print "</td>\n";
288 print '</tr>';
289
290 if (isModEnabled("bank")) {
291 print '<tr>';
292 print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>';
293 print '<td colspan="2">';
294 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
295 $form->select_comptes(GETPOSTISSET("accountid") ? GETPOSTINT("accountid") : 0, "accountid", 0, '', 2); // Show open bank account list
296 print '</td></tr>';
297 }
298
299 // Number
300 print '<tr><td>'.$langs->trans('Numero');
301 print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
302 print '</td>';
303 print '<td colspan="2"><input name="num_payment" type="text" value="'.GETPOST('num_payment').'"></td></tr>'."\n";
304
305 print '<tr>';
306 print '<td class="tdtop">'.$langs->trans("Comments").'</td>';
307 print '<td valign="top" colspan="2"><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
308 print '</tr>';
309
310 print '</table>';
311
312 print dol_get_fiche_end();
313
314 print '<br>';
315
316 // List of expenses ereport not already paid completely
317 $num = 1;
318 $i = 0;
319
320 print '<table class="noborder centpercent">';
321 print '<tr class="liste_titre">';
322 print '<td>'.$langs->trans("ExpenseReport").'</td>';
323 print '<td class="right">'.$langs->trans("Amount").'</td>';
324 print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>';
325 print '<td class="right">'.$langs->trans("RemainderToPay").'</td>';
326 print '<td class="center">'.$langs->trans("Amount").'</td>';
327 print "</tr>\n";
328
329 $total_ttc = 0;
330 $totalrecu = 0;
331
332 while ($i < $num) {
333 $objp = $expensereport;
334
335 print '<tr class="oddeven">';
336
337 print '<td>'.$expensereport->getNomUrl(1)."</td>";
338 print '<td class="right">'.price($objp->total_ttc)."</td>";
339 print '<td class="right">'.price($sumpaid)."</td>";
340 print '<td class="right">'.price($objp->total_ttc - $sumpaid)."</td>";
341 print '<td class="center">';
342 if ($sumpaid < $objp->total_ttc) {
343 $namef = "amount_".$objp->id;
344 $nameRemain = "remain_".$objp->id; // autofill remainder amount
345 if (!empty($conf->use_javascript_ajax)) { // autofill remainder amount
346 print img_picto("Auto fill", 'rightarrow', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->total_ttc - $sumpaid)."'"); // autofill remainder amount
347 }
348 $remaintopay = $objp->total_ttc - $sumpaid; // autofill remainder amount
349 print '<input type=hidden class="sum_remain" name="'.$nameRemain.'" value="'.$remaintopay.'">'; // autofill remainder amount
350 print '<input type="text" class="width75" name="'.$namef.'" id="'.$namef.'" value="'.GETPOST($namef).'">';
351 } else {
352 print '-';
353 }
354 print "</td>";
355
356 print "</tr>\n";
357
358 $total_ttc += $objp->total_ttc;
359 $totalrecu += $sumpaid;
360 $i++;
361 }
362 if ($i > 1) {
363 // Print total
364 print '<tr class="oddeven">';
365 print '<td colspan="2" class="left">'.$langs->trans("Total").':</td>';
366 print '<td class="right"><b>'.price($total_ttc).'</b></td>';
367 print '<td class="right"><b>'.price($totalrecu).'</b></td>';
368 print '<td class="right"><b>'.price($total_ttc - $totalrecu).'</b></td>';
369 print '<td class="center">&nbsp;</td>';
370 print "</tr>\n";
371 }
372
373 print "</table>";
374
375 print $form->buttonsSaveCancel();
376
377 print "</form>\n";
378}
379
380// End of page
381llxFooter();
382$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage Trips and Expenses.
const STATUS_APPROVED
Classified approved.
Class to manage generation of HTML components Only common components must be here.
Class to manage payments of expense report.
recordNotFound($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Displays an error page when a record is not found.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0, $morecssdiv='')
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
checkUserAccessToObject($user, array $featuresarray, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='', $dbt_select='rowid', $parenttableforentity='')
Check that access by a given user to an object is ok.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.