dolibarr  13.0.2
payment.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2014-2018 Alexandre Spangaro <aspangaro@open-dsi.fr>
3  * Copyright (C) 2015-2018 Frédéric France <frederic.france@netlogic.fr>
4  * Copyright (C) 2020 Maxime DEMAREST <maxime@indelog.fr>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <https://www.gnu.org/licenses/>.
18  */
19 
26 require '../../main.inc.php';
27 require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/loan/class/loanschedule.class.php';
29 require_once DOL_DOCUMENT_ROOT.'/loan/class/paymentloan.class.php';
30 require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/lib/loan.lib.php';
32 
33 $langs->loadLangs(array("bills", "loan"));
34 
35 $chid = GETPOST('id', 'int');
36 $action = GETPOST('action', 'aZ09');
37 $cancel = GETPOST('cancel', 'alpha');
38 $datepaid = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int'));
39 
40 // Security check
41 $socid = 0;
42 if ($user->socid > 0)
43  $socid = $user->socid;
44 elseif (GETPOSTISSET('socid')) $socid = GETPOST('socid', 'int');
45 if (empty($user->rights->loan->write)) accessforbidden();
46 
47 $loan = new Loan($db);
48 $loan->fetch($chid);
49 
50 $echance = 0;
51 $ls = new LoanSchedule($db);
52 // grab all loanschedule
53 $res = $ls->fetchAll($chid);
54 if ($res > 0)
55 {
56  foreach ($ls->lines as $l)
57  {
58  $echance++; // Count term pos
59  // last unpaid term
60  if (empty($l->fk_bank))
61  {
62  $line_id = $l->id;
63  break;
64  }
65  // If line_id provided, only count temp pos
66  elseif ($line_id == $l->id)
67  {
68  break;
69  }
70  }
71 }
72 
73 // Set current line with last unpaid line (only if shedule is used)
74 if (!empty($line_id))
75 {
76  $line = new LoanSchedule($db);
77  $res = $line->fetch($line_id);
78  if ($res > 0) {
79  $amount_capital = price($line->amount_capital);
80  $amount_insurance = price($line->amount_insurance);
81  $amount_interest = price($line->amount_interest);
82  if (empty($datepaid)) $ts_temppaid = $line->datep;
83  }
84 }
85 
86 
87 /*
88  * Actions
89  */
90 
91 if ($action == 'add_payment')
92 {
93  $error = 0;
94 
95  if ($cancel)
96  {
97  $loc = DOL_URL_ROOT.'/loan/card.php?id='.$chid;
98  header("Location: ".$loc);
99  exit;
100  }
101 
102  if (!GETPOST('paymenttype', 'int') > 0)
103  {
104  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("PaymentMode")), null, 'errors');
105  $error++;
106  }
107  if ($datepaid == '')
108  {
109  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("Date")), null, 'errors');
110  $error++;
111  }
112  if (!empty($conf->banque->enabled) && !GETPOST('accountid', 'int') > 0)
113  {
114  setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentities("AccountToCredit")), null, 'errors');
115  $error++;
116  }
117 
118  if (!$error)
119  {
120  $paymentid = 0;
121 
122  $pay_amount_capital = price2num(GETPOST('amount_capital'));
123  $pay_amount_insurance = price2num(GETPOST('amount_insurance'));
124  // User can't set interest him self if schedule is set (else value in schedule can be incoherent)
125  if (!empty($line)) $pay_amount_interest = $line->amount_interest;
126  else $pay_amount_interest = price2num(GETPOST('amount_interest'));
127  $remaindertopay = price2num(GETPOST('remaindertopay'));
128  $amount = $pay_amount_capital + $pay_amount_insurance + $pay_amount_interest;
129 
130  // This term is allready paid
131  if (!empty($line) && !empty($line->fk_bank))
132  {
133  setEventMessages($langs->trans('TermPaidAllreadyPaid'), null, 'errors');
134  $error++;
135  }
136 
137  if (empty($remaindertopay))
138  {
139  setEventMessages('Empty sumpaid', null, 'errors');
140  $error++;
141  }
142 
143  if ($amount == 0)
144  {
145  setEventMessages($langs->trans('ErrorNoPaymentDefined'), null, 'errors');
146  $error++;
147  }
148 
149  if (!$error)
150  {
151  $db->begin();
152 
153  // Create a line of payments
154  $payment = new PaymentLoan($db);
155  $payment->chid = $chid;
156  $payment->datep = $datepaid;
157  $payment->label = $loan->label;
158  $payment->amount_capital = $pay_amount_capital;
159  $payment->amount_insurance = $pay_amount_insurance;
160  $payment->amount_interest = $pay_amount_interest;
161  $payment->fk_bank = GETPOST('accountid', 'int');
162  $payment->paymenttype = GETPOST('paymenttype', 'int');
163  $payment->num_payment = GETPOST('num_payment');
164  $payment->note_private = GETPOST('note_private', 'restricthtml');
165  $payment->note_public = GETPOST('note_public', 'restricthtml');
166 
167  if (!$error)
168  {
169  $paymentid = $payment->create($user);
170  if ($paymentid < 0)
171  {
172  setEventMessages($payment->error, $payment->errors, 'errors');
173  $error++;
174  }
175  }
176 
177  if (!$error)
178  {
179  $result = $payment->addPaymentToBank($user, $chid, 'payment_loan', '(LoanPayment)', $payment->fk_bank, '', '');
180  if (!$result > 0)
181  {
182  setEventMessages($payment->error, $payment->errors, 'errors');
183  $error++;
184  }
185  }
186 
187  // Update loan schedule with payment value
188  if (!$error && !empty($line))
189  {
190  // If payment values are modified, recalculate schedule
191  if (($line->amount_capital <> $pay_amount_capital) || ($line->amount_insurance <> $pay_amount_insurance) || ($line->amount_interest <> $pay_amount_interest))
192  {
193  $arr_term = loanCalcMonthlyPayment(($pay_amount_capital + $pay_amount_interest), $remaindertopay, ($loan->rate / 100), $echance, $loan->nbterm);
194  foreach ($arr_term as $k=>$v)
195  {
196  // Update fk_bank for current line
197  if ($k == $echance)
198  {
199  $ls->lines[$k - 1]->fk_bank = $payment->fk_bank;
200  $ls->lines[$k - 1]->fk_payment_loan = $payment->id;
201  }
202  $ls->lines[$k - 1]->amount_capital = $v['mens'] - $v['interet'];
203  $ls->lines[$k - 1]->amount_interest = $v['interet'];
204  $ls->lines[$k - 1]->tms = dol_now();
205  $ls->lines[$k - 1]->fk_user_modif = $user->id;
206  $result = $ls->lines[$k - 1]->update($user, 0);
207  if ($result < 1)
208  {
209  setEventMessages(null, $ls->errors, 'errors');
210  $error++;
211  break;
212  }
213  }
214  }
215  else // Only add fk_bank bank to schedule line (mark as paid)
216  {
217  $line->fk_bank = $payment->fk_bank;
218  $line->fk_payment_loan = $payment->id;
219  $result = $line->update($user, 0);
220  if ($result < 1)
221  {
222  setEventMessages(null, $line->errors, 'errors');
223  $error++;
224  }
225  }
226  }
227 
228  if (!$error)
229  {
230  $db->commit();
231  $loc = DOL_URL_ROOT.'/loan/card.php?id='.$chid;
232  header('Location: '.$loc);
233  exit;
234  } else {
235  $db->rollback();
236  }
237  }
238  }
239 
240  $action = 'create';
241 }
242 
243 
244 /*
245  * View
246  */
247 
248 llxHeader();
249 
250 $form = new Form($db);
251 
252 
253 // Form to create loan's payment
254 if ($action == 'create')
255 {
256  $total = $loan->capital;
257 
258  print load_fiche_titre($langs->trans("DoPayment"));
259 
260  $sql = "SELECT SUM(amount_capital) as total";
261  $sql .= " FROM ".MAIN_DB_PREFIX."payment_loan";
262  $sql .= " WHERE fk_loan = ".$chid;
263  $resql = $db->query($sql);
264  if ($resql)
265  {
266  $obj = $db->fetch_object($resql);
267  $sumpaid = $obj->total;
268  $db->free();
269  }
270 
271  print '<form name="add_payment" action="'.$_SERVER['PHP_SELF'].'" method="post">';
272  print '<input type="hidden" name="token" value="'.newToken().'">';
273  print '<input type="hidden" name="id" value="'.$chid.'">';
274  print '<input type="hidden" name="chid" value="'.$chid.'">';
275  print '<input type="hidden" name="line_id" value="'.$line_id.'">';
276  print '<input type="hidden" name="remaindertopay" value="'.($total - $sumpaid).'">';
277  print '<input type="hidden" name="action" value="add_payment">';
278 
279  print dol_get_fiche_head();
280 
281  /*
282  print '<table class="border centpercent">';
283 
284  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>';
285  if ($echance > 0)
286  {
287  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";
288  }
289  print '<tr><td>'.$langs->trans("DateStart").'</td><td colspan="2">'.dol_print_date($loan->datestart, 'day')."</td></tr>\n";
290  print '<tr><td>'.$langs->trans("Label").'</td><td colspan="2">'.$loan->label."</td></tr>\n";
291  print '<tr><td>'.$langs->trans("Amount").'</td><td colspan="2">'.price($loan->capital, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
292 
293  print '<tr><td>'.$langs->trans("AlreadyPaid").'</td><td colspan="2">'.price($sumpaid, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
294  print '<tr><td class="tdtop">'.$langs->trans("RemainderToPay").'</td><td colspan="2">'.price($total - $sumpaid, 0, $outputlangs, 1, -1, -1, $conf->currency).'</td></tr>';
295  print '</tr>';
296 
297  print '</table>';
298  */
299 
300  print '<table class="border centpercent">';
301 
302  print '<tr><td class="titlefield fieldrequired">'.$langs->trans("Date").'</td><td colspan="2">';
303  if (empty($datepaid))
304  if (empty($ts_temppaid)) $datepayment = empty($conf->global->MAIN_AUTOFILL_DATE) ?-1 : dol_now();
305  else $datepayment = $ts_temppaid;
306  else $datepayment = $datepaid;
307  print $form->selectDate($datepayment, '', '', '', '', "add_payment", 1, 1);
308  print "</td>";
309  print '</tr>';
310 
311  print '<tr><td class="fieldrequired">'.$langs->trans("PaymentMode").'</td><td colspan="2">';
312  $form->select_types_paiements(GETPOSTISSET("paymenttype") ? GETPOST("paymenttype", 'alphanohtml') : $loan->fk_typepayment, "paymenttype");
313  print "</td>\n";
314  print '</tr>';
315 
316  print '<tr>';
317  print '<td class="fieldrequired">'.$langs->trans('AccountToDebit').'</td>';
318  print '<td colspan="2">';
319  $form->select_comptes(GETPOSTISSET("accountid") ? GETPOST("accountid", 'int') : $loan->accountid, "accountid", 0, 'courant = '.Account::TYPE_CURRENT, 1); // Show opend bank account list
320  print '</td></tr>';
321 
322  // Number
323  print '<tr><td>'.$langs->trans('Numero');
324  print ' <em>('.$langs->trans("ChequeOrTransferNumber").')</em>';
325  print '</td>';
326  print '<td colspan="2"><input name="num_payment" type="text" value="'.GETPOST('num_payment', 'alphanohtml').'"></td>'."\n";
327  print "</tr>";
328 
329  print '<tr>';
330  print '<td class="tdtop">'.$langs->trans("NotePrivate").'</td>';
331  print '<td valign="top" colspan="2"><textarea name="note_private" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
332  print '</tr>';
333 
334  print '<tr>';
335  print '<td class="tdtop">'.$langs->trans("NotePublic").'</td>';
336  print '<td valign="top" colspan="2"><textarea name="note_public" wrap="soft" cols="60" rows="'.ROWS_3.'"></textarea></td>';
337  print '</tr>';
338 
339  print '</table>';
340 
341  print dol_get_fiche_end();
342 
343 
344  print '<table class="noborder centpercent">';
345  print '<tr class="liste_titre">';
346  print '<td class="left">'.$langs->trans("DateDue").'</td>';
347  print '<td class="right">'.$langs->trans("LoanCapital").'</td>';
348  print '<td class="right">'.$langs->trans("AlreadyPaid").'</td>';
349  print '<td class="right">'.$langs->trans("RemainderToPay").'</td>';
350  print '<td class="right">'.$langs->trans("Amount").'</td>';
351  print "</tr>\n";
352 
353  print '<tr class="oddeven">';
354 
355  if ($loan->datestart > 0)
356  {
357  print '<td class="left" valign="center">'.dol_print_date($loan->datestart, 'day').'</td>';
358  } else {
359  print '<td class="center" valign="center"><b>!!!</b></td>';
360  }
361 
362  print '<td class="right" valign="center">'.price($loan->capital)."</td>";
363 
364  print '<td class="right" valign="center">'.price($sumpaid)."</td>";
365 
366  print '<td class="right" valign="center">'.price($loan->capital - $sumpaid)."</td>";
367 
368  print '<td class="right">';
369  if ($sumpaid < $loan->capital)
370  {
371  print $langs->trans("LoanCapital").': <input type="text" size="8" name="amount_capital" value="'.(GETPOSTISSET('amount_capital') ?GETPOST('amount_capital') : $amount_capital).'">';
372  }
373  else {
374  print '-';
375  }
376  print '<br>';
377  if ($sumpaid < $loan->capital)
378  {
379  print $langs->trans("Insurance").': <input type="text" size="8" name="amount_insurance" value="'.(GETPOSTISSET('amount_insurance') ?GETPOST('amount_insurance') : $amount_insurance).'">';
380  }
381  else {
382  print '-';
383  }
384  print '<br>';
385  if ($sumpaid < $loan->capital)
386  {
387  print $langs->trans("Interest").': <input type="text" size="8" name="amount_interest" value="'.(GETPOSTISSET('amount_interest') ?GETPOST('amount_interest') : $amount_interest).'" '.(!empty($line) ? 'disabled title="'.$langs->trans('CantModifyInterestIfScheduleIsUsed').'"' : '').'>';
388  }
389  else {
390  print '-';
391  }
392  print "</td>";
393 
394  print "</tr>\n";
395 
396  print '</table>';
397 
398  print '<br><div class="center">';
399  print '<input type="submit" class="button button-save" name="save" value="'.$langs->trans("Save").'">';
400  print '&nbsp; &nbsp;';
401  print '<input type="submit" class="button button-cancel" name="cancel" value="'.$langs->trans("Cancel").'">';
402  print '</div>';
403 
404  print "</form>\n";
405 }
406 
407 llxFooter();
408 $db->close();
GETPOST($paramname, $check= 'alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
loanCalcMonthlyPayment($mens, $capital, $rate, $echance, $nbterm)
Calculate remaining loan mensuality and interests.
Definition: loan.lib.php:96
Loan.
Definition: loan.class.php:30
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm= 'auto', $check=1)
Return a timestamp date built from detailed informations (by default a local PHP server timestamp) Re...
dol_now($mode= 'auto')
Return date for now.
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...
llxHeader()
Empty header.
Definition: wrapper.php:45
Class to manage Schedule of loans.
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname.
load_fiche_titre($titre, $morehtmlright= '', $picto= 'generic', $pictoisfullpath=0, $id= '', $morecssontable= '', $morehtmlcenter= '')
Load a title with picto.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
Class to manage payments of loans.
accessforbidden($message= '', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
dol_get_fiche_head($links=array(), $active= '', $title= '', $notab=0, $picto= '', $pictoisfullpath=0, $morehtmlright= '', $morecss= '', $limittoshow=0, $moretabssuffix= '')
Show tabs of a record.
print
Draft customers invoices.
Definition: index.php:89
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_get_fiche_end($notab=0)
Return tab footer of a card.
llxFooter()
Empty footer.
Definition: wrapper.php:59
if(!defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN'
Draft customers invoices.