dolibarr 25.0.0-alpha
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-2026 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';
36require_once DOL_DOCUMENT_ROOT.'/expensereport/class/expensereport.class.php';
37require_once DOL_DOCUMENT_ROOT.'/expensereport/class/paymentexpensereport.class.php';
38require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
39
40// Load translation files required by the page
41$langs->loadLangs(array('bills', 'banks', 'trips'));
42
43$id = GETPOSTINT('id');
44$ref = GETPOST('ref', 'alpha');
45$action = GETPOST('action', 'aZ09');
46$amounts = array();
47$accountid = GETPOSTINT('accountid');
48$cancel = GETPOST('cancel');
49
50// $id is the id of the expense report to pay (see link on expensereport/card.php)
51$object = new ExpenseReport($db);
52if ($id > 0 || !empty($ref)) {
53 $result = $object->fetch($id, $ref);
54 if ($result <= 0) {
56 }
57}
58
59// Security check
60$socid = 0;
61if ($user->isExternalUser()) {
62 $socid = $user->isExternalUser();
63}
64
65// Check the user can read this expense report: entity, and author in his hierarchy unless readall.
66// Not restrictedArea(), that would also ask for 'creer' with action=create, the link of expensereport/card.php.
67if (!$user->hasRight('expensereport', 'lire') || !checkUserAccessToObject($user, array('expensereport'), $object, 'expensereport')) {
69}
70
71$permissiontoadd = $user->hasRight('expensereport', 'to_paid');
72
73
74/*
75 * Actions
76 */
77
78if ($action == 'add_payment' && $permissiontoadd) {
79 $error = 0;
80
81 if ($cancel) {
82 $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id;
83 header("Location: ".$loc);
84 exit;
85 }
86
87 $expensereport = new ExpenseReport($db);
88 $result = $expensereport->fetch($id, $ref);
89 if (!$result) {
90 $error++;
91 setEventMessages($expensereport->error, $expensereport->errors, 'errors');
92 }
93 if (!$error && $expensereport->status != ExpenseReport::STATUS_APPROVED) {
94 $error++;
95 setEventMessages($langs->trans('StatusOfRefMustBe', $expensereport->ref, $langs->transnoentitiesnoconv('Approved')), null, 'errors');
96 }
97
98 $datepaid = dol_mktime(12, 0, 0, GETPOSTINT("remonth"), GETPOSTINT("reday"), GETPOSTINT("reyear"));
99
100 if (!(GETPOSTINT("fk_typepayment") > 0)) {
101 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors');
102 $error++;
103 }
104 if ($datepaid == '') {
105 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors');
106 $error++;
107 }
108
109 if (isModEnabled("bank") && !($accountid > 0)) {
110 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToDebit")), null, 'errors');
111 $error++;
112 }
113
114 if (!$error) {
115 $paymentid = 0;
116 // $total = 0;
117
118 // Read possible payments
119 foreach ($_POST as $key => $value) {
120 if (substr($key, 0, 7) == 'amount_') {
121 if (GETPOST($key)) {
122 $amounts[$expensereport->fk_user_author] = (float) price2num(GETPOST($key));
123 // $total += price2num(GETPOST($key));
124 }
125 }
126 }
127
128 if (count($amounts) <= 0) {
129 $error++;
130 setEventMessages('ErrorNoPaymentDefined', null, 'errors');
131 }
132 // A payment can't be higher than the remainder to pay
133 $remaintopay = (float) price2num($expensereport->total_ttc - $expensereport->getSumPayments(), 'MT');
134 if (!$error && (float) price2num(array_sum($amounts), 'MT') > $remaintopay) {
135 $error++;
136 setEventMessages($langs->trans('PaymentHigherThanReminderToPay'), null, 'errors');
137 }
138
139 if (!$error) {
140 $db->begin();
141
142 // Create a line of payments
143 $payment = new PaymentExpenseReport($db);
144 $payment->fk_expensereport = $expensereport->id;
145 $payment->datep = $datepaid;
146 $payment->amounts = $amounts; // array of amounts
147 // total is calculated in class
148 // $payment->total = $total;
149 $payment->fk_typepayment = GETPOSTINT("fk_typepayment");
150 $payment->num_payment = GETPOST("num_payment", 'alphanohtml');
151 $payment->note_public = GETPOST("note_public", 'restricthtml');
152 $payment->fk_bank = $accountid;
153
154 if (!$error) {
155 $paymentid = $payment->create($user);
156 if ($paymentid < 0) {
157 setEventMessages($payment->error, $payment->errors, 'errors');
158 $error++;
159 }
160 }
161
162 if (!$error) {
163 $result = $payment->addPaymentToBank($user, 'payment_expensereport', '(ExpenseReportPayment)', $accountid, '', '');
164 if ($result <= 0) {
165 setEventMessages($payment->error, $payment->errors, 'errors');
166 $error++;
167 }
168 }
169
170 if (!$error) {
171 $payment->fetch($paymentid);
172 // Set the expense report as paid when the sum of all its payments (not only this one) reaches its total
173 $remaintopay = price2num($expensereport->total_ttc - $expensereport->getSumPayments(), 'MT');
174 if ($remaintopay <= 0) {
175 $result = $expensereport->setPaid($expensereport->id, $user);
176 if (!($result > 0)) {
177 setEventMessages($payment->error, $payment->errors, 'errors');
178 $error++;
179 }
180 }
181 }
182
183 if (!$error) {
184 $db->commit();
185 $loc = DOL_URL_ROOT.'/expensereport/card.php?id='.$id;
186 header('Location: '.$loc);
187 exit;
188 } else {
189 $db->rollback();
190 }
191 }
192 }
193
194 $action = 'create';
195}
196
197
198/*
199 * View
200 */
201
202llxHeader();
203
204$form = new Form($db);
205
206
207// Form to create expense report payment
208if ($action == 'create' || empty($action)) {
209 $expensereport = new ExpenseReport($db);
210 $expensereport->fetch($id, $ref);
211
212 $total = $expensereport->total_ttc;
213
214 // autofill remainder amount
215 if (!empty($conf->use_javascript_ajax)) {
216 print "\n".'<script type="text/javascript">';
217 //Add js for AutoFill
218 print ' $(document).ready(function () {';
219 print ' $(".AutoFillAmount").on(\'click touchstart\', function(){
220 var amount = $(this).data("value");
221 document.getElementById($(this).data(\'rowid\')).value = amount ;
222 });';
223 print "\t});\n";
224 print "</script>\n";
225 }
226
227 print load_fiche_titre($langs->trans("DoPayment"));
228
229 print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">';
230 print '<input type="hidden" name="token" value="'.newToken().'">';
231 print '<input type="hidden" name="id" value="'.$expensereport->id.'">';
232 print '<input type="hidden" name="chid" value="'.$expensereport->id.'">';
233 print '<input type="hidden" name="action" value="add_payment">';
234
235 print dol_get_fiche_head([], '0', '', -1);
236
237 $linkback = '';
238 // $linkback = '<a href="' . DOL_URL_ROOT . '/expensereport/payment/list.php">' . $langs->trans("BackToList") . '</a>';
239
240 dol_banner_tab($expensereport, 'ref', $linkback, 1, 'ref', 'ref', '');
241
242 print '<div class="fichecenter">';
243 print '<div class="underbanner clearboth"></div>';
244
245 print '<table class="border centpercent">'."\n";
246
247 print '<tr><td class="titlefield">'.$langs->trans("Period").'</td><td>'.get_date_range($expensereport->date_debut, $expensereport->date_fin, "", $langs, 0).'</td></tr>';
248 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>';
249
250 $sql = "SELECT sum(p.amount) as total";
251 $sql .= " FROM ".MAIN_DB_PREFIX."payment_expensereport as p, ".MAIN_DB_PREFIX."expensereport as e";
252 $sql .= " WHERE p.fk_expensereport = e.rowid AND p.fk_expensereport = ".((int) $id);
253 $sql .= ' AND e.entity IN ('.getEntity('expensereport').')';
254 $sumpaid = 0;
255 $resql = $db->query($sql);
256 if ($resql) {
257 $obj = $db->fetch_object($resql);
258 $sumpaid = $obj->total;
259 $db->free($resql);
260 }
261 print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td><span class="amount">'.price($sumpaid, 0, $langs, 1, -1, -1, $conf->currency).'</span></td></tr>';
262 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>';
263
264 print '</table>';
265
266 print '</div>';
267
268 print dol_get_fiche_end();
269
270 print '<br>';
271
272 print dol_get_fiche_head();
273
274 print '<table class="border centpercent">'."\n";
275
276 print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Date").'</td><td colspan="2">';
277 $datepaid = dol_mktime(12, 0, 0, GETPOSTINT("remonth"), GETPOSTINT("reday"), GETPOSTINT("reyear"));
278 $datepayment = ($datepaid == '' ? (getDolGlobalString('MAIN_AUTOFILL_DATE') ? '' : -1) : $datepaid);
279 print $form->selectDate($datepayment, '', 0, 0, 0, "add_payment", 1, 1);
280 print "</td>";
281 print '</tr>';
282
283 print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td colspan="2">';
284 $form->select_types_paiements(GETPOSTISSET("fk_typepayment") ? GETPOST("fk_typepayment", 'alpha') : $expensereport->fk_c_paiement, "fk_typepayment");
285 print "</td>\n";
286 print '</tr>';
287
288 if (isModEnabled("bank")) {
289 print '<tr>';
290 print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>';
291 print '<td colspan="2">';
292 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
293 $form->select_comptes(GETPOSTISSET("accountid") ? GETPOSTINT("accountid") : 0, "accountid", 0, '', 2); // Show open bank account list
294 print '</td></tr>';
295 }
296
297 // Number
298 print '<tr><td>'.$langs->trans('Numero');
299 print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
300 print '</td>';
301 print '<td colspan="2"><input name="num_payment" type="text" value="'.GETPOST('num_payment').'"></td></tr>'."\n";
302
303 print '<tr>';
304 print '<td class="tdtop">'.$langs->trans("Comments").'</td>';
305 print '<td valign="top" colspan="2"><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
306 print '</tr>';
307
308 print '</table>';
309
310 print dol_get_fiche_end();
311
312 print '<br>';
313
314 // List of expenses ereport not already paid completely
315 $num = 1;
316 $i = 0;
317
318 print '<table class="noborder centpercent">';
319 print '<tr class="liste_titre">';
320 print '<td>'.$langs->trans("ExpenseReport").'</td>';
321 print '<td class="right">'.$langs->trans("Amount").'</td>';
322 print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>';
323 print '<td class="right">'.$langs->trans("RemainderToPay").'</td>';
324 print '<td class="center">'.$langs->trans("Amount").'</td>';
325 print "</tr>\n";
326
327 $total_ttc = 0;
328 $totalrecu = 0;
329
330 while ($i < $num) {
331 $objp = $expensereport;
332
333 print '<tr class="oddeven">';
334
335 print '<td>'.$expensereport->getNomUrl(1)."</td>";
336 print '<td class="right">'.price($objp->total_ttc)."</td>";
337 print '<td class="right">'.price($sumpaid)."</td>";
338 print '<td class="right">'.price($objp->total_ttc - $sumpaid)."</td>";
339 print '<td class="center">';
340 if ($sumpaid < $objp->total_ttc) {
341 $namef = "amount_".$objp->id;
342 $nameRemain = "remain_".$objp->id; // autofill remainder amount
343 if (!empty($conf->use_javascript_ajax)) { // autofill remainder amount
344 print img_picto("Auto fill", 'rightarrow.png', "class='AutoFillAmount' data-rowid='".$namef."' data-value='".($objp->total_ttc - $sumpaid)."'"); // autofill remainder amount
345 }
346 $remaintopay = $objp->total_ttc - $sumpaid; // autofill remainder amount
347 print '<input type=hidden class="sum_remain" name="'.$nameRemain.'" value="'.$remaintopay.'">'; // autofill remainder amount
348 print '<input type="text" class="width75" name="'.$namef.'" id="'.$namef.'" value="'.GETPOST($namef).'">';
349 } else {
350 print '-';
351 }
352 print "</td>";
353
354 print "</tr>\n";
355
356 $total_ttc += $objp->total_ttc;
357 $totalrecu += $sumpaid;
358 $i++;
359 }
360 if ($i > 1) {
361 // Print total
362 print '<tr class="oddeven">';
363 print '<td colspan="2" class="left">'.$langs->trans("Total").':</td>';
364 print '<td class="right"><b>'.price($total_ttc).'</b></td>';
365 print '<td class="right"><b>'.price($totalrecu).'</b></td>';
366 print '<td class="right"><b>'.price($total_ttc - $totalrecu).'</b></td>';
367 print '<td class="center">&nbsp;</td>';
368 print "</tr>\n";
369 }
370
371 print "</table>";
372
373 print $form->buttonsSaveCancel();
374
375 print "</form>\n";
376}
377
378// End of page
379llxFooter();
380$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
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
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
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.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
get_date_range($date_start, $date_end, $format='', $outputlangs=null, $withparenthesis=1)
Format output for start and end date.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
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.
Definition html.lib.php:542
dol_get_fiche_end($notab=0)
Return tab footer of a card.
Definition html.lib.php:740
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
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.