dolibarr 25.0.0-alpha
payment.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2014-2024 Alexandre Spangaro <alexandre@inovea-conseil.com>
3 * Copyright (C) 2015-2026 Frédéric France <frederic.france@free.fr>
4 * Copyright (C) 2020 Maxime DEMAREST <maxime@indelog.fr>
5 * Copyright (C) 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.'/loan/class/loan.class.php';
37require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php';
38require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
39require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
40require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php';
41
42$langs->loadLangs(array("bills", "loan"));
43
44$action = GETPOST('action', 'aZ09');
45$confirm = GETPOST('confirm', 'alpha');
46$cancel = GETPOST('cancel', 'alpha');
47
48$chid = GETPOSTINT('id');
49$datepaid = dol_mktime(12, 0, 0, GETPOSTINT('remonth'), GETPOSTINT('reday'), GETPOSTINT('reyear'));
50
51// Security check
52$socid = 0;
53if ($user->socid > 0) {
54 $socid = $user->socid;
55} elseif (GETPOSTISSET('socid')) {
56 $socid = GETPOSTINT('socid');
57}
58if (!$user->hasRight('loan', 'write')) {
60}
61
62$loan = new Loan($db);
63$loan->fetch($chid);
64
65$line_id = 0;
66$echance = 0;
67$amount_capital = 0;
68$amount_insurance = 0;
69$amount_interest = 0;
70
71$ls = new LoanSchedule($db);
72// grab all loanschedule
73$res = $ls->fetchAll($chid);
74if ($res > 0) {
75 foreach ($ls->lines as $l) {
76 $echance++; // Count term pos
77 // last unpaid term
78 if (empty($l->fk_bank)) {
79 $line_id = $l->id;
80 break;
81 } elseif ($line_id == $l->id) {
82 // If line_id provided, only count temp pos
83 break;
84 }
85 }
86}
87
88// Set current line with last unpaid line (only if schedule is used)
89if (!empty($line_id)) {
90 $line = new LoanSchedule($db);
91 $res = $line->fetch($line_id);
92 if ($res > 0) {
93 $amount_capital = price($line->amount_capital);
94 $amount_insurance = price($line->amount_insurance);
95 $amount_interest = price($line->amount_interest);
96 if (empty($datepaid)) {
97 $ts_temppaid = $line->datep;
98 }
99 }
100}
101
102// Without a schedule: the next payment worked out from the loan and the payments already made
103$nextpayment = null;
104if (empty($line) && $loan->paid != Loan::STATUS_PAID) {
105 $nextpayment = loanNextPayment($db, $loan);
106 if ($nextpayment) {
107 $amount_capital = price($nextpayment['capital']);
108 $amount_insurance = price($nextpayment['charge']);
109 $amount_interest = price($nextpayment['interest']);
110 if (empty($datepaid)) {
111 $ts_temppaid = $nextpayment['date'];
112 }
113 }
114}
115
116$permissiontoadd = $user->hasRight('loan', 'write');
117
118
119/*
120 * Actions
121 */
122
123if ($action == 'add_payment' && $permissiontoadd) {
124 $error = 0;
125
126 if ($cancel) {
127 $loc = DOL_URL_ROOT.'/loan/card.php?id='.$chid;
128 header("Location: ".$loc);
129 exit;
130 }
131
132 if (!GETPOSTINT('paymenttype') > 0) {
133 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors');
134 $error++;
135 }
136 if ($datepaid == '') {
137 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors');
138 $error++;
139 }
140 if (isModEnabled("bank") && !GETPOSTINT('accountid') > 0) {
141 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToCredit")), null, 'errors');
142 $error++;
143 }
144
145 if (!$error) {
146 $paymentid = 0;
147
148 $pay_amount_capital = (float) price2num(GETPOST('amount_capital'));
149 $pay_amount_insurance = (float) price2num(GETPOST('amount_insurance'));
150 // Interest as entered (pre-filled with the schedule's); if it differs from the schedule, the following payments are recalculated
151 if (!empty($line) && !GETPOSTISSET('amount_interest')) {
152 $pay_amount_interest = $line->amount_interest;
153 } else {
154 $pay_amount_interest = (float) price2num(GETPOST('amount_interest'));
155 }
156 $remaindertopay = (float) price2num(GETPOST('remaindertopay'));
157 $amount = (float) price2num($pay_amount_capital + $pay_amount_insurance + $pay_amount_interest, 'MT');
158
159 // This term is already paid
160 if (!empty($line) && !empty($line->fk_bank)) {
161 setEventMessages($langs->trans('TermPaidAllreadyPaid'), null, 'errors');
162 $error++;
163 }
164
165 if (empty($remaindertopay)) {
166 setEventMessages('Empty sumpaid', null, 'errors');
167 $error++;
168 }
169
170 if ($amount == 0) {
171 setEventMessages($langs->trans('ErrorNoPaymentDefined'), null, 'errors');
172 $error++;
173 }
174
175 if (!$error) {
176 $db->begin();
177
178 // Create a line of payments
179 $payment = new PaymentLoan($db);
180 $payment->chid = $chid;
181 $payment->datep = $datepaid;
182 $payment->label = $loan->label;
183 $payment->amount_capital = $pay_amount_capital;
184 $payment->amount_insurance = $pay_amount_insurance;
185 $payment->amount_interest = $pay_amount_interest;
186 $payment->fk_bank = GETPOSTINT('accountid');
187 $payment->paymenttype = GETPOSTINT('paymenttype');
188 $payment->num_payment = GETPOST('num_payment', 'alphanohtml');
189 $payment->note_private = GETPOST('note_private', 'restricthtml');
190 $payment->note_public = GETPOST('note_public', 'restricthtml');
191
192 if (!$error) {
193 $paymentid = $payment->create($user);
194 if ($paymentid < 0) {
195 setEventMessages($payment->error, $payment->errors, 'errors');
196 $error++;
197 }
198 }
199
200 if (!$error) {
201 // @phan-suppress-next-line PhanPluginSuspiciousParamOrder
202 $result = $payment->addPaymentToBank($user, $chid, 'payment_loan', '(LoanPayment)', $payment->fk_bank, '', '');
203 if (!($result > 0)) {
204 setEventMessages($payment->error, $payment->errors, 'errors');
205 $error++;
206 }
207 }
208
209 // Update loan schedule with payment value
210 if (!$error && !empty($line)) {
211 if (($line->amount_capital != $pay_amount_capital) || ($line->amount_insurance != $pay_amount_insurance) || ($line->amount_interest != $pay_amount_interest)) {
212 // This payment as entered, then the following unpaid payments recalculated (each with the rate in force on
213 // its date), keeping either the number of payments or the repayment
214 $keep = (GETPOST('recalc_keep', 'aZ09') === 'payment' ? 'payment' : 'term');
215 $nbtermold = (float) $loan->nbterm;
216 $line->fk_bank = $payment->fk_bank;
217 $line->fk_payment_loan = $payment->id;
218 $line->amount_capital = $pay_amount_capital;
219 $line->amount_insurance = $pay_amount_insurance;
220 $line->amount_interest = $pay_amount_interest;
221 $line->fk_user_modif = $user->id;
222 if ($line->update($user, 0) < 1) {
223 setEventMessages(null, $line->errors, 'errors');
224 $error++;
225 }
226 if (!$error && isset($ls->lines[$echance])) {
227 $lines = $ls->lines;
228 $lines[$echance - 1] = $line;
229 $res = loanRecalculateSchedule($db, $user, $loan, $lines, $echance, (float) $remaindertopay - (float) $pay_amount_capital, null, $keep);
230 if ($res['error']) {
231 setEventMessages($langs->trans($res['error']), null, 'errors');
232 $error++;
233 } elseif (loanRecordChange($db, $user, $loan->id, 'payment', $datepaid, (float) $loan->rate, (float) $loan->rate, $keep, $res['payment_old'], $res['payment_new'], $nbtermold, $res['nbterm_new'], $payment->id) < 0) {
234 setEventMessages($db->lasterror(), null, 'errors');
235 $error++;
236 }
237 }
238 } else { // Only add fk_bank bank to schedule line (mark as paid)
239 $line->fk_bank = $payment->fk_bank;
240 $line->fk_payment_loan = $payment->id;
241 $result = $line->update($user, 0);
242 if ($result < 1) {
243 setEventMessages(null, $line->errors, 'errors');
244 $error++;
245 }
246 }
247 }
248
249 if (!$error) {
250 $db->commit();
251 $loc = DOL_URL_ROOT.'/loan/card.php?id='.$chid;
252 header('Location: '.$loc);
253 exit;
254 } else {
255 $db->rollback();
256 }
257 }
258 }
259
260 $action = 'create';
261}
262
263
264/*
265 * View
266 */
267$form = new Form($db);
268
269$title = $langs->trans('Loans');
270$help_url = "EN:Module_Loan|FR:Module_Emprunt";
271
272llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'bodyforlist mod-loan page-payment-list');
273
274
275// Form to create loan's payment
276if ($action == 'create') {
277 $total = $loan->capital;
278 $sumpaid = 0;
279
280 print load_fiche_titre($langs->trans("DoPayment"));
281
282 $sql = "SELECT SUM(amount_capital) as total";
283 $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan";
284 $sql .= " WHERE fk_loan = ".((int) $chid);
285 $resql = $db->query($sql);
286 if ($resql) {
287 $obj = $db->fetch_object($resql);
288 $sumpaid = $obj->total;
289 $db->free($resql);
290 }
291
292 print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">';
293 print '<input type="hidden" name="token" value="'.newToken().'">';
294 print '<input type="hidden" name="id" value="'.$chid.'">';
295 print '<input type="hidden" name="chid" value="'.$chid.'">';
296 print '<input type="hidden" name="line_id" value="'.$line_id.'">';
297 print '<input type="hidden" name="remaindertopay" value="'.($total - $sumpaid).'">';
298 print '<input type="hidden" name="action" value="add_payment">';
299
300 print dol_get_fiche_head();
301
302 /*
303 print '<table class="border centpercent">';
304
305 print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td><td colspan="2"><a href="'.DOL_URL_ROOT.'/loan/card.php?id='.$chid.'">'.$chid.'</a></td></tr>';
306 if ($echance > 0)
307 {
308 print '<tr><td>'.$langs->trans("Term").'</td><td colspan="2"><a href="'.DOL_URL_ROOT.'/loan/schedule.php?loanid='.$chid.'#n'.$echance.'">'.$echance.'</a></td></tr>'."\n";
309 }
310 print '<tr><td>'.$langs->trans("DateStart").'</td><td colspan="2">'.dol_print_date($loan->datestart, 'day')."</td></tr>\n";
311 print '<tr><td>'.$langs->trans("Label").'</td><td colspan="2">'.$loan->label."</td></tr>\n";
312 print '<tr><td>'.$langs->trans("Amount").'</td><td colspan="2">'.price($loan->capital, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
313
314 print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td colspan="2">'.price($sumpaid, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
315 print '<tr><td class="tdtop">'.$langs->trans("RemainderToPay").'</td><td colspan="2">'.price($total - $sumpaid, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
316 print '</tr>';
317
318 print '</table>';
319 */
320
321 print '<table class="border centpercent">';
322
323 print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Date").'</td><td colspan="2">';
324 if (empty($datepaid)) {
325 if (empty($ts_temppaid)) {
326 $datepayment = (getDolGlobalString('MAIN_AUTOFILL_DATE') ? dol_now() : -1);
327 } else {
328 $datepayment = $ts_temppaid;
329 }
330 } else {
331 $datepayment = $datepaid;
332 }
333 print $form->selectDate($datepayment, '', 0, 0, 0, "add_payment", 1, 1);
334 print "</td>";
335 print '</tr>';
336
337 print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td colspan="2">';
338 print img_picto('', 'money-bill-alt', 'class="pictofixedwidth"');
339 $form->select_types_paiements(GETPOSTISSET("paymenttype") ? GETPOST("paymenttype", 'alphanohtml') : '', "paymenttype");
340 print "</td>\n";
341 print '</tr>';
342
343 print '<tr>';
344 print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>';
345 print '<td colspan="2">';
346 print img_picto('', 'bank_account', 'class="pictofixedwidth"');
347 print $form->select_comptes(GETPOSTISSET("accountid") ? GETPOSTINT("accountid") : $loan->fk_bank, "accountid", 0, '(courant:=:'.Account::TYPE_CURRENT.')', 1, '', 0, '', 1); // Show open bank account list
348 print '</td></tr>';
349
350 // Number
351 print '<tr><td>'.$langs->trans('Numero');
352 print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
353 print '</td>';
354 print '<td colspan="2"><input name="num_payment" type="text" value="'.GETPOST('num_payment', 'alphanohtml').'"></td>'."\n";
355 print "</tr>";
356
357 print '<tr>';
358 print '<td class="tdtop">'.$langs->trans("NotePrivate").'</td>';
359 print '<td valign="top" colspan="2"><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
360 print '</tr>';
361
362 print '<tr>';
363 print '<td class="tdtop">'.$langs->trans("NotePublic").'</td>';
364 print '<td valign="top" colspan="2"><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
365 print '</tr>';
366
367 print '</table>';
368
369 print dol_get_fiche_end();
370
371
372 print '<table class="noborder centpercent">';
373 print '<tr class="liste_titre">';
374 print '<td class="left">'.$langs->trans("DateDue").'</td>';
375 print '<td class="right">'.$langs->trans("LoanCapital").'</td>';
376 print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>';
377 print '<td class="right">'.$langs->trans("RemainderToPay").'</td>';
378 print '<td class="right">'.$langs->trans("Amount").'</td>';
379 print "</tr>\n";
380
381 print '<tr class="oddeven">';
382
383 if ($loan->datestart > 0) {
384 print '<td class="left" valign="center">'.dol_print_date($loan->datestart, 'day').'</td>';
385 } else {
386 print '<td class="center" valign="center"><b>!!!</b></td>';
387 }
388
389 print '<td class="right" valign="center">'.price($loan->capital)."</td>";
390
391 print '<td class="right" valign="center">'.price($sumpaid)."</td>";
392
393 print '<td class="right" valign="center">'.price($loan->capital - $sumpaid)."</td>";
394
395 print '<td class="right">';
396 if ($sumpaid < $loan->capital) {
397 print $langs->trans("LoanCapital").': <input type="text" size="8" name="amount_capital" value="'.(GETPOSTISSET('amount_capital') ? GETPOST('amount_capital') : $amount_capital).'">';
398 } else {
399 print '-';
400 }
401 print '<br>';
402 if ($sumpaid < $loan->capital) {
403 print loanChargeLabel($loan->charge_type, $langs).': <input type="text" size="8" name="amount_insurance" value="'.(GETPOSTISSET('amount_insurance') ? GETPOST('amount_insurance') : $amount_insurance).'">';
404 } else {
405 print '-';
406 }
407 print '<br>';
408 if ($sumpaid < $loan->capital) {
409 print $langs->trans("Interest").': <input type="text" size="8" name="amount_interest" value="'.(GETPOSTISSET('amount_interest') ? GETPOST('amount_interest') : $amount_interest).'">';
410 } else {
411 print '-';
412 }
413 print "</td>";
414
415 print "</tr>\n";
416
417 print '</table>';
418
419 if (!empty($nextpayment)) {
420 print '<div class="opacitymedium margintoponly">'.$langs->trans("LoanNextPaymentPrefilled", $nextpayment['term'], (int) $loan->nbterm).'</div>';
421 }
422
423 // With a schedule, how to recalculate the following payments if this payment differs from it
424 if (!empty($line)) {
425 print '<div class="margintoponly">'.$langs->trans("LoanRecalcIfDifferent").' ';
426 print $form->selectarray('recalc_keep', array('term' => $langs->trans("LoanRecalcKeepTerm"), 'payment' => $langs->trans("LoanRecalcKeepPayment")), GETPOST('recalc_keep', 'aZ09') ? GETPOST('recalc_keep', 'aZ09') : 'term');
427 print '</div>';
428 }
429
430 print $form->buttonsSaveCancel();
431
432 print "</form>\n";
433}
434
435llxFooter();
436$db->close();
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 bank accounts.
Class to manage generation of HTML components Only common components must be here.
Loan.
Class to manage Schedule of loans.
Class to manage payments of loans.
dol_now($mode='gmt')
Return date for now.
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.
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.
loanNextPayment($db, $loan)
Next payment of a loan that has no schedule, worked out from the loan and the payments already made: ...
Definition loan.lib.php:606
loanChargeLabel($charge_type, $outputlangs)
Label of the charge of a loan (Insurance, Account-keeping fee, Other fee).
Definition loan.lib.php:328
loanRecordChange($db, $user, $loanid, $reason, $datechange, $rate_old, $rate_new, $keep, $payment_old, $payment_new, $nbterm_old, $nbterm_new, $fk_payment=0)
Record a change of a loan (rate change, or a payment that differs from the schedule) in its history.
Definition loan.lib.php:531
loanRecalculateSchedule($db, $user, $loan, $lines, $from, $capital, $rate, $keep, $payment=0.0)
Recalculate the unpaid payments of a loan schedule, from one payment to the end, after a rate change ...
Definition loan.lib.php:370
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.