Passed
Branch develop (c36c8e)
by
unknown
39:14
created

PaymentLoan::update()   F

Complexity

Conditions 30
Paths > 20000

Size

Total Lines 59
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 30
eloc 42
nc 268435456
nop 2
dl 0
loc 59
rs 0
c 0
b 0
f 0

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2014-2018  Alexandre Spangaro   <[email protected]>
3
 * Copyright (C) 2015-2018  Frederic France      <[email protected]>
4
 * Copyright (C) 2020       Maxime DEMAREST      <[email protected]>
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
20
/**
21
 *  \file       htdocs/loan/class/paymentloan.class.php
22
 *  \ingroup    loan
23
 *  \brief      File of class to manage payment of loans
24
 */
25
26
require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
27
28
29
/**
30
 * Class to manage payments of loans
31
 */
32
class PaymentLoan extends CommonObject
33
{
34
	/**
35
	 * @var string ID to identify managed object
36
	 */
37
	public $element = 'payment_loan';
38
39
	/**
40
	 * @var string Name of table without prefix where object is stored
41
	 */
42
	public $table_element = 'payment_loan';
43
44
    /**
45
     * @var string String with name of icon for PaymentLoan
46
     */
47
    public $picto = 'money-bill-alt';
48
49
    /**
50
     * @var int Loan ID
51
     */
52
    public $fk_loan;
53
54
    /**
55
     * @var string Create date
56
     */
57
    public $datec = '';
58
59
    public $tms = '';
60
61
    /**
62
     * @var string Payment date
63
     */
64
    public $datep = '';
65
66
    public $amounts = array(); // Array of amounts
67
68
    public $amount_capital; // Total amount of payment
69
70
    public $amount_insurance;
71
72
    public $amount_interest;
73
74
    /**
75
     * @var int Payment type ID
76
     */
77
    public $fk_typepayment;
78
79
    /**
80
     * @var int Payment ID
81
     */
82
    public $num_payment;
83
84
    /**
85
     * @var int Bank ID
86
     */
87
    public $fk_bank;
88
89
    /**
90
     * @var int User ID
91
     */
92
    public $fk_user_creat;
93
94
    /**
95
     * @var int user ID
96
     */
97
    public $fk_user_modif;
98
99
    public $type_code;
100
    public $type_label;
101
102
103
	/**
104
	 *	Constructor
105
	 *
106
	 *  @param		DoliDB		$db      Database handler
107
	 */
108
	public function __construct($db)
109
	{
110
		$this->db = $db;
111
	}
112
113
	/**
114
	 *  Create payment of loan into database.
115
	 *  Use this->amounts to have list of lines for the payment
116
	 *
117
	 *  @param      User		$user   User making payment
118
	 *  @return     int     			<0 if KO, id of payment if OK
119
	 */
120
	public function create($user)
121
	{
122
		global $conf, $langs;
123
124
		$error = 0;
125
126
		$now = dol_now();
127
128
		// Validate parameters
129
		if (!$this->datep)
130
		{
131
			$this->error = 'ErrorBadValueForParameter';
132
			return -1;
133
		}
134
135
		// Clean parameters
136
		if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan;
137
		if (isset($this->amount_capital))	$this->amount_capital = price2num($this->amount_capital ? $this->amount_capital : 0);
138
		if (isset($this->amount_insurance)) $this->amount_insurance = price2num($this->amount_insurance ? $this->amount_insurance : 0);
139
		if (isset($this->amount_interest))	$this->amount_interest = price2num($this->amount_interest ? $this->amount_interest : 0);
140
		if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment;
141
		if (isset($this->num_payment)) $this->num_payment = (int) $this->num_payment;
142
		if (isset($this->note_private))     $this->note_private = trim($this->note_private);
143
		if (isset($this->note_public))      $this->note_public = trim($this->note_public);
144
		if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank;
145
		if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat;
146
		if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif;
147
148
		$totalamount = $this->amount_capital + $this->amount_insurance + $this->amount_interest;
149
		$totalamount = price2num($totalamount);
150
151
		// Check parameters
152
		if ($totalamount == 0) return -1; // Negative amounts are accepted for reject prelevement but not null
153
154
155
		$this->db->begin();
156
157
		if ($totalamount != 0)
158
		{
159
			$sql = "INSERT INTO ".MAIN_DB_PREFIX."payment_loan (fk_loan, datec, datep, amount_capital, amount_insurance, amount_interest,";
160
			$sql .= " fk_typepayment, num_payment, note_private, note_public, fk_user_creat, fk_bank)";
161
			$sql .= " VALUES (".$this->chid.", '".$this->db->idate($now)."',";
162
			$sql .= " '".$this->db->idate($this->datep)."',";
163
			$sql .= " ".$this->amount_capital.",";
164
			$sql .= " ".$this->amount_insurance.",";
165
			$sql .= " ".$this->amount_interest.",";
166
			$sql .= " ".$this->paymenttype.", '".$this->db->escape($this->num_payment)."', '".$this->db->escape($this->note_private)."', '".$this->db->escape($this->note_public)."', ".$user->id.",";
167
			$sql .= " 0)";
168
169
			dol_syslog(get_class($this)."::create", LOG_DEBUG);
170
			$resql = $this->db->query($sql);
171
			if ($resql)
172
			{
173
				$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."payment_loan");
174
			} else {
175
				$this->error = $this->db->lasterror();
176
				$error++;
177
			}
178
		}
179
180
		if ($totalamount != 0 && !$error)
181
		{
182
			$this->amount_capital = $totalamount;
183
			$this->db->commit();
184
			return $this->id;
185
		} else {
186
			$this->error = $this->db->lasterror();
187
			$this->db->rollback();
188
			return -1;
189
		}
190
	}
191
192
	/**
193
	 *  Load object in memory from database
194
	 *
195
	 *  @param	int		$id         Id object
196
	 *  @return int         		<0 if KO, >0 if OK
197
	 */
198
	public function fetch($id)
199
	{
200
		global $langs;
201
		$sql = "SELECT";
202
		$sql .= " t.rowid,";
203
		$sql .= " t.fk_loan,";
204
		$sql .= " t.datec,";
205
		$sql .= " t.tms,";
206
		$sql .= " t.datep,";
207
		$sql .= " t.amount_capital,";
208
		$sql .= " t.amount_insurance,";
209
		$sql .= " t.amount_interest,";
210
		$sql .= " t.fk_typepayment,";
211
		$sql .= " t.num_payment,";
212
		$sql .= " t.note_private,";
213
		$sql .= " t.note_public,";
214
		$sql .= " t.fk_bank,";
215
		$sql .= " t.fk_user_creat,";
216
		$sql .= " t.fk_user_modif,";
217
		$sql .= " pt.code as type_code, pt.libelle as type_label,";
218
		$sql .= ' b.fk_account';
219
		$sql .= " FROM ".MAIN_DB_PREFIX."payment_loan as t";
220
		$sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pt ON t.fk_typepayment = pt.id";
221
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'bank as b ON t.fk_bank = b.rowid';
222
		$sql .= " WHERE t.rowid = ".$id;
223
224
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
225
		$resql = $this->db->query($sql);
226
		if ($resql)
227
		{
228
			if ($this->db->num_rows($resql))
229
			{
230
				$obj = $this->db->fetch_object($resql);
231
232
				$this->id = $obj->rowid;
233
				$this->ref = $obj->rowid;
234
235
				$this->fk_loan = $obj->fk_loan;
236
				$this->datec = $this->db->jdate($obj->datec);
237
				$this->tms = $this->db->jdate($obj->tms);
238
				$this->datep = $this->db->jdate($obj->datep);
239
				$this->amount_capital = $obj->amount_capital;
240
				$this->amount_insurance = $obj->amount_insurance;
241
				$this->amount_interest = $obj->amount_interest;
242
				$this->fk_typepayment = $obj->fk_typepayment;
243
				$this->num_payment = $obj->num_payment;
244
				$this->note_private = $obj->note_private;
245
				$this->note_public = $obj->note_public;
246
				$this->fk_bank = $obj->fk_bank;
247
				$this->fk_user_creat = $obj->fk_user_creat;
248
				$this->fk_user_modif = $obj->fk_user_modif;
249
250
				$this->type_code = $obj->type_code;
251
				$this->type_label = $obj->type_label;
252
253
				$this->bank_account = $obj->fk_account;
254
				$this->bank_line = $obj->fk_bank;
255
			}
256
			$this->db->free($resql);
257
258
			return 1;
259
		} else {
260
			$this->error = "Error ".$this->db->lasterror();
261
			return -1;
262
		}
263
	}
264
265
266
	/**
267
	 *  Update database
268
	 *
269
	 *  @param	User	$user        	User that modify
270
	 *  @param  int		$notrigger	    0=launch triggers after, 1=disable triggers
271
	 *  @return int         			<0 if KO, >0 if OK
272
	 */
273
	public function update($user = 0, $notrigger = 0)
274
	{
275
		global $conf, $langs;
276
		$error = 0;
277
278
		// Clean parameters
279
		if (isset($this->fk_loan)) $this->fk_loan = (int) $this->fk_loan;
280
		if (isset($this->amount_capital)) $this->amount_capital = trim($this->amount_capital);
281
		if (isset($this->amount_insurance)) $this->amount_insurance = trim($this->amount_insurance);
282
		if (isset($this->amount_interest)) $this->amount_interest = trim($this->amount_interest);
283
		if (isset($this->fk_typepayment)) $this->fk_typepayment = (int) $this->fk_typepayment;
284
		if (isset($this->num_payment)) $this->num_payment = (int) $this->num_payment;
285
		if (isset($this->note_private)) $this->note = trim($this->note_private);
286
		if (isset($this->note_public)) $this->note = trim($this->note_public);
287
		if (isset($this->fk_bank)) $this->fk_bank = (int) $this->fk_bank;
288
		if (isset($this->fk_user_creat)) $this->fk_user_creat = (int) $this->fk_user_creat;
289
		if (isset($this->fk_user_modif)) $this->fk_user_modif = (int) $this->fk_user_modif;
290
291
		// Check parameters
292
293
		// Update request
294
		$sql = "UPDATE ".MAIN_DB_PREFIX."payment_loan SET";
295
296
		$sql .= " fk_loan=".(isset($this->fk_loan) ? $this->fk_loan : "null").",";
297
		$sql .= " datec=".(dol_strlen($this->datec) != 0 ? "'".$this->db->idate($this->datec)."'" : 'null').",";
298
		$sql .= " tms=".(dol_strlen($this->tms) != 0 ? "'".$this->db->idate($this->tms)."'" : 'null').",";
299
		$sql .= " datep=".(dol_strlen($this->datep) != 0 ? "'".$this->db->idate($this->datep)."'" : 'null').",";
300
		$sql .= " amount_capital=".(isset($this->amount_capital) ? $this->amount_capital : "null").",";
301
		$sql .= " amount_insurance=".(isset($this->amount_insurance) ? $this->amount_insurance : "null").",";
302
		$sql .= " amount_interest=".(isset($this->amount_interest) ? $this->amount_interest : "null").",";
303
		$sql .= " fk_typepayment=".(isset($this->fk_typepayment) ? $this->fk_typepayment : "null").",";
304
		$sql .= " num_payment=".(isset($this->num_payment) ? "'".$this->db->escape($this->num_payment)."'" : "null").",";
305
		$sql .= " note_private=".(isset($this->note_private) ? "'".$this->db->escape($this->note_private)."'" : "null").",";
306
		$sql .= " note_public=".(isset($this->note_public) ? "'".$this->db->escape($this->note_public)."'" : "null").",";
307
		$sql .= " fk_bank=".(isset($this->fk_bank) ? $this->fk_bank : "null").",";
308
		$sql .= " fk_user_creat=".(isset($this->fk_user_creat) ? $this->fk_user_creat : "null").",";
309
		$sql .= " fk_user_modif=".(isset($this->fk_user_modif) ? $this->fk_user_modif : "null")."";
310
311
		$sql .= " WHERE rowid=".$this->id;
312
313
		$this->db->begin();
314
315
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
316
		$resql = $this->db->query($sql);
317
		if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
318
319
		// Commit or rollback
320
		if ($error)
321
		{
322
			foreach ($this->errors as $errmsg)
323
			{
324
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
325
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
326
			}
327
			$this->db->rollback();
328
			return -1 * $error;
329
		} else {
330
			$this->db->commit();
331
			return 1;
332
		}
333
	}
334
335
336
	/**
337
	 *  Delete object in database
338
	 *
339
	 *  @param	User	$user        	User that delete
340
	 *  @param  int		$notrigger		0=launch triggers after, 1=disable triggers
341
	 *  @return int						<0 if KO, >0 if OK
342
	 */
343
	public function delete($user, $notrigger = 0)
344
	{
345
		global $conf, $langs;
346
		$error = 0;
347
348
		$this->db->begin();
349
350
		if (!$error)
351
		{
352
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url";
353
			$sql .= " WHERE type='payment_loan' AND url_id=".$this->id;
354
355
			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
356
			$resql = $this->db->query($sql);
357
			if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
358
		}
359
360
		if (!$error)
361
		{
362
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."payment_loan";
363
			$sql .= " WHERE rowid=".$this->id;
364
365
			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
366
			$resql = $this->db->query($sql);
367
			if (!$resql) { $error++; $this->errors[] = "Error ".$this->db->lasterror(); }
368
		}
369
370
        // Set loan unpaid if loan has no other payment
371
        if (!$error)
372
        {
373
            require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
374
            $loan = new Loan($this->db);
375
            $loan->fetch($this->fk_loan);
376
            $sum_payment = $loan->getSumPayment();
377
            if ($sum_payment == 0)
378
            {
379
                dol_syslog(get_class($this)."::delete : set loan to unpaid", LOG_DEBUG);
380
                if ($loan->set_unpaid($user) < 1)
381
                {
382
                    $error++;
383
                    dol_print_error($this->db);
384
                }
385
            }
386
        }
387
388
		//if (! $error)
389
		//{
390
		//	if (! $notrigger)
391
		//	{
392
				// Uncomment this and change MYOBJECT to your own tag if you
393
				// want this action call a trigger.
394
395
				//// Call triggers
396
				//include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
397
				//$interface=new Interfaces($this->db);
398
				//$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
399
				//if ($result < 0) { $error++; $this->errors=$interface->errors; }
400
				//// End call triggers
401
		//	}
402
		//}
403
404
		// Commit or rollback
405
		if ($error)
406
		{
407
			foreach ($this->errors as $errmsg)
408
			{
409
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
410
				$this->error .= ($this->error ? ', '.$errmsg : $errmsg);
411
			}
412
			$this->db->rollback();
413
			return -1 * $error;
414
		} else {
415
			$this->db->commit();
416
			return 1;
417
		}
418
	}
419
420
	/**
421
	 *      Add record into bank for payment with links between this bank record and invoices of payment.
422
	 *      All payment properties must have been set first like after a call to create().
423
	 *
424
	 *      @param	User	$user               Object of user making payment
425
	 *      @param  int		$fk_loan            Id of fk_loan to do link with this payment
426
	 *      @param  string	$mode               'payment_loan'
427
	 *      @param  string	$label              Label to use in bank record
428
	 *      @param  int		$accountid          Id of bank account to do link with
429
	 *      @param  string	$emetteur_nom       Name of transmitter
430
	 *      @param  string	$emetteur_banque    Name of bank
431
	 *      @return int                 		<0 if KO, >0 if OK
432
	 */
433
	public function addPaymentToBank($user, $fk_loan, $mode, $label, $accountid, $emetteur_nom, $emetteur_banque)
434
	{
435
		global $conf;
436
437
		$error = 0;
438
        $this->db->begin();
439
440
		if (!empty($conf->banque->enabled))
441
		{
442
			require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php';
443
444
			$acc = new Account($this->db);
445
			$acc->fetch($accountid);
446
447
			$total = $this->amount_capital;
448
			if ($mode == 'payment_loan') $total = -$total;
449
450
			// Insert payment into llx_bank
451
            $bank_line_id = $acc->addline(
452
				$this->datep,
453
				$this->paymenttype, // Payment mode id or code ("CHQ or VIR for example")
0 ignored issues
show
Bug Best Practice introduced by
The property paymenttype does not exist on PaymentLoan. Did you maybe forget to declare it?
Loading history...
454
				$label,
455
				$total,
456
				$this->num_payment,
457
				'',
458
				$user,
459
				$emetteur_nom,
460
				$emetteur_banque
461
			);
462
463
			// Update fk_bank into llx_paiement.
464
			// We know the payment who generated the account write
465
			if ($bank_line_id > 0)
466
			{
467
				$result = $this->update_fk_bank($bank_line_id);
468
				if ($result <= 0)
469
				{
470
					$error++;
471
					dol_print_error($this->db);
472
				}
473
474
				// Add link 'payment_loan' in bank_url between payment and bank transaction
475
				$url = '';
476
				if ($mode == 'payment_loan') $url = DOL_URL_ROOT.'/loan/payment/card.php?id=';
477
				if ($url)
478
				{
479
					$result = $acc->add_url_line($bank_line_id, $this->id, $url, '(payment)', $mode);
480
					if ($result <= 0)
481
					{
482
						$error++;
483
						dol_print_error($this->db);
484
					}
485
				}
486
487
488
				// Add link 'loan' in bank_url between invoice and bank transaction (for each invoice concerned by payment)
489
				if ($mode == 'payment_loan')
490
				{
491
					$result = $acc->add_url_line($bank_line_id, $fk_loan, DOL_URL_ROOT.'/loan/card.php?id=', ($this->label ? $this->label : ''), 'loan');
492
					if ($result <= 0) dol_print_error($this->db);
493
				}
494
			} else {
495
				$this->error = $acc->error;
496
				$error++;
497
			}
498
		}
499
500
501
        // Set loan payment started if no set
502
        if (!$error)
503
        {
504
            require_once DOL_DOCUMENT_ROOT.'/loan/class/loan.class.php';
505
            $loan = new Loan($this->db);
506
            $loan->fetch($fk_loan);
507
            if ($loan->paid == $loan::STATUS_UNPAID)
508
            {
509
                dol_syslog(get_class($this)."::addPaymentToBank : set loan payment to started", LOG_DEBUG);
510
                if ($loan->set_started($user) < 1)
511
                {
512
                    $error++;
513
                    dol_print_error($this->db);
514
                }
515
            }
516
        }
517
518
		if (!$error)
519
		{
520
            $this->db->commit();
521
			return 1;
522
		}
523
		else {
524
            $this->db->rollback();
525
			return -1;
526
		}
527
	}
528
529
530
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
531
	/**
532
	 *  Update link between loan's payment and the line generate in llx_bank
533
	 *
534
	 *  @param	int		$id_bank         Id if bank
535
	 *  @return	int			             >0 if OK, <=0 if KO
536
	 */
537
	public function update_fk_bank($id_bank)
538
	{
539
        // phpcs:enable
540
		$sql = "UPDATE ".MAIN_DB_PREFIX."payment_loan SET fk_bank = ".$id_bank." WHERE rowid = ".$this->id;
541
542
		dol_syslog(get_class($this)."::update_fk_bank", LOG_DEBUG);
543
		$result = $this->db->query($sql);
544
		if ($result)
545
		{
546
		    $this->fk_bank = $id_bank;
547
			return 1;
548
		} else {
549
			$this->error = $this->db->error();
550
			return 0;
551
		}
552
	}
553
554
	/**
555
	 *  Return clicable name (with eventually a picto)
556
	 *
557
	 *	@param	int		$withpicto					0=No picto, 1=Include picto into link, 2=No picto
558
	 * 	@param	int		$maxlen						Max length label
559
     *	@param	int  	$notooltip					1=Disable tooltip
560
     *	@param	string	$moretitle					Add more text to title tooltip
561
     *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
562
	 *	@return	string								String with URL
563
	 */
564
	public function getNomUrl($withpicto = 0, $maxlen = 0, $notooltip = 0, $moretitle = '', $save_lastsearch_value = -1)
565
	{
566
		global $langs, $conf;
567
568
		if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
569
570
		$result = '';
571
		$label = '<u>'.$langs->trans("Loan").'</u>';
572
		if (!empty($this->id)) {
573
			$label .= '<br><b>'.$langs->trans('Ref').':</b> '.$this->id;
574
		}
575
		if ($moretitle) $label .= ' - '.$moretitle;
576
577
		$url = DOL_URL_ROOT.'/loan/payment/card.php?id='.$this->id;
578
579
		$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
580
		if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
581
		if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
582
583
		$linkstart = '<a href="'.$url.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
584
		$linkend = '</a>';
585
586
		$result .= $linkstart;
587
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
588
		if ($withpicto != 2) $result .= $this->ref;
589
		$result .= $linkend;
590
591
		return $result;
592
	}
593
}
594