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