Completed
Branch develop (e3d3d3)
by
unknown
23:59
created

AccountLine::LibStatut()   B

Complexity

Conditions 1
Paths 1

Size

Total Lines 36
Code Lines 2

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 2
nc 1
nop 2
dl 0
loc 36
rs 8.8571
c 0
b 0
f 0
1
<?php
2
/* Copyright (C) 2001-2007	Rodolphe Quiedeville	<[email protected]>
3
 * Copyright (C) 2003		Jean-Louis Bergamo		<[email protected]>
4
 * Copyright (C) 2004-2012	Laurent Destailleur		<[email protected]>
5
 * Copyright (C) 2004		Christophe Combelles	<[email protected]>
6
 * Copyright (C) 2005-2010	Regis Houssin			<[email protected]>
7
 * Copyright (C) 2013		Florian Henry			<[email protected]>
8
 * Copyright (C) 2015-2016	Marcos García			<[email protected]>
9
 * Copyright (C) 2015		Alexandre Spangaro		<[email protected]>
10
 * Copyright (C) 2016		Ferran Marcet   		<[email protected]>
11
 *
12
 * This program is free software; you can redistribute it and/or modify
13
 * it under the terms of the GNU General Public License as published by
14
 * the Free Software Foundation; either version 3 of the License, or
15
 * (at your option) any later version.
16
 *
17
 * This program is distributed in the hope that it will be useful,
18
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
19
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
20
 * GNU General Public License for more details.
21
 *
22
 * You should have received a copy of the GNU General Public License
23
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
24
 */
25
26
/**
27
 *	\file       htdocs/compta/bank/class/account.class.php
28
 *	\ingroup    bank
29
 *	\brief      File of class to manage bank accounts
30
 */
31
require_once DOL_DOCUMENT_ROOT .'/core/class/commonobject.class.php';
32
33
34
/**
35
 *	Class to manage bank accounts
36
 */
37
class Account extends CommonObject
38
{
39
    public $element = 'bank_account';
40
    public $table_element = 'bank_account';
41
    public $picto = 'account';
42
    
43
    /**
44
     * @var	int		Use id instead of rowid
45
     * @deprecated
46
     * @see id
47
     */
48
    public $rowid;
49
50
    /**
51
     * Label
52
     * @var string
53
     */
54
    public $label;
55
56
    /**
57
     * Bank account type. Check TYPE_ constants
58
     * @var int
59
     */
60
    public $courant;
61
62
    /**
63
     * Bank account type. Check TYPE_ constants
64
     * @var int
65
     */
66
    public $type;
67
68
    /**
69
     * Bank name
70
     * @var string
71
     */
72
    public $bank;
73
74
    /**
75
     * Status
76
     * @var int
77
     */
78
    public $clos = self::STATUS_OPEN;
79
80
    /**
81
     * Does it need to be conciliated?
82
     * @var int
83
     */
84
    public $rappro=1;
85
86
    /**
87
     * Webpage
88
     * @var string
89
     */
90
    public $url;
91
92
    /**
93
     * Bank number. If in SEPA area, you should move to IBAN field
94
     * @var string
95
     */
96
    public $code_banque;
97
98
    /**
99
     * Branch number. If in SEPA area, you should move to IBAN field
100
     * @var string
101
     */
102
    public $code_guichet;
103
104
    /**
105
     * Account number. If in SEPA area, you should move to IBAN field
106
     * @var string
107
     */
108
    public $number;
109
110
    /**
111
     * Bank account number control digit. If in SEPA area, you should move to IBAN field
112
     * @var string
113
     */
114
    public $cle_rib;
115
116
    /**
117
     * BIC/Swift code
118
     * @var string
119
     */
120
    public $bic;
121
122
    /**
123
     * IBAN number (International Bank Account Number). Stored into iban_prefix field into database
124
     * @var
125
     */
126
    public $iban;
127
128
    /**
129
     * Name of account holder
130
     * @var string
131
     */
132
    public $proprio;
133
134
    /**
135
     * Address of account holder
136
     * @var string
137
     */
138
    public $owner_address;
139
140
    public $state_id;
141
    public $state_code;
142
    public $state;
143
144
	/**
145
	 * Variable containing all account types with their respective translated label.
146
	 * Defined in __construct
147
	 * @var array
148
	 */
149
    public $type_lib = array();
150
151
	/**
152
	 * Variable containing all account statuses with their respective translated label.
153
	 * Defined in __construct
154
	 * @var array
155
	 */
156
	public $status = array();
157
158
    /**
159
     * Accountancy code
160
     * @var string
161
     */
162
    public $account_number;
163
	public $accountancy_journal;
164
165
    /**
166
     * Currency code
167
     * @var string
168
     */
169
    public $currency_code;
170
171
    /**
172
     * Currency code
173
     * @var string
174
     * @deprecated Use currency_code instead
175
     */
176
    public $account_currency_code;
177
178
    /**
179
     * Authorized minimum balance
180
     * @var float
181
     */
182
    public $min_allowed;
183
184
    /**
185
     * Desired minimum balance
186
     * @var float
187
     */
188
    public $min_desired;
189
190
    /**
191
     * Notes
192
     * @var string
193
     */
194
    public $comment;
195
196
    /**
197
     * Date of the initial balance. Used in Account::create
198
     * @var int
199
     */
200
    public $date_solde;
201
202
    /**
203
     * Current account
204
     */
205
    const TYPE_CURRENT = 1;
206
    /**
207
     * Cash account
208
     */
209
    const TYPE_CASH = 2;
210
    /**
211
     * Savings account
212
     */
213
    const TYPE_SAVINGS = 0;
214
215
    const STATUS_OPEN = 0;
216
    const STATUS_CLOSED = 1;
217
218
    /**
219
     *  Constructor
220
     *
221
     *  @param	DoliDB		$db		Database handler
222
     */
223
    function __construct(DoliDB $db)
224
    {
225
        global $langs;
226
227
        $this->db = $db;
228
229
        $this->solde = 0;
230
231
        $this->type_lib = array(
232
            self::TYPE_SAVINGS => $langs->trans("BankType0"),
233
            self::TYPE_CURRENT => $langs->trans("BankType1"),
234
            self::TYPE_CASH => $langs->trans("BankType2"),
235
        );
236
237
        $this->status = array(
238
            self::STATUS_OPEN => $langs->trans("StatusAccountOpened"),
239
            self::STATUS_CLOSED => $langs->trans("StatusAccountClosed")
240
        );
241
    }
242
243
	/**
244
	 * Shows the account number in the appropiate format
245
	 *
246
	 * @return string
247
	 */
248
	public function __toString()
249
	{
250
		$string = '';
251
252
		foreach ($this->getFieldsToShow() as $val) {
253
254
			if ($val == 'BankCode') {
255
				$string .= $this->code_banque.' ';
256
			} elseif ($val == 'BankAccountNumber') {
257
				$string .= $this->number.' ';
258
			} elseif ($val == 'DeskCode') {
259
				$string .= $this->code_guichet.' ';
260
			} elseif ($val == 'BankAccountNumberKey') {
261
				$string .= $this->cle_rib.' ';
262
			}elseif ($val == 'BIC') {
263
				$string .= $this->bic.' ';
264
			}elseif ($val == 'IBAN') {
265
				$string .= $this->iban.' ';
266
			}
267
		}
268
269
		return trim($string);
270
	}
271
272
273
    /**
274
     *  Return if a bank account need to be conciliated
275
     *
276
     *  @return     int         1 if need to be concialiated, < 0 otherwise.
277
     */
278
    function canBeConciliated()
279
    {
280
        global $conf;
281
282
        if (empty($this->rappro)) return -1;
283
        if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2;
284
        if ($this->clos) return -3;
285
        return 1;
286
    }
287
288
289
    /**
290
     *      Add a link between bank line record and its source
291
     *
292
     *      @param	int		$line_id    Id ecriture bancaire
293
     *      @param  int		$url_id     Id parametre url
294
     *      @param  string	$url        Url
295
     *      @param  string	$label      Link label
296
     *      @param  string	$type       Type of link ('payment', 'company', 'member', ...)
297
     *      @return int         		<0 if KO, id line if OK
298
     */
299
    function add_url_line($line_id, $url_id, $url, $label, $type)
300
    {
301
        $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
302
        $sql.= "fk_bank";
303
        $sql.= ", url_id";
304
        $sql.= ", url";
305
        $sql.= ", label";
306
        $sql.= ", type";
307
        $sql.= ") VALUES (";
308
        $sql.= "'".$line_id."'";
309
        $sql.= ", '".$url_id."'";
310
        $sql.= ", '".$url."'";
311
        $sql.= ", '".$this->db->escape($label)."'";
312
        $sql.= ", '".$type."'";
313
        $sql.= ")";
314
315
        dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG);
316
        if ($this->db->query($sql))
317
        {
318
            $rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url");
319
            return $rowid;
320
        }
321
        else
322
        {
323
            $this->error=$this->db->lasterror();
324
            return -1;
325
        }
326
    }
327
328
    /**
329
     * 		TODO Move this into AccountLine
330
     *      Return array with links from llx_bank_url
331
     *
332
     *      @param  int         $fk_bank    To search using bank transaction id
333
     *      @param  int         $url_id     To search using link to
334
     *      @param  string      $type       To search using type
335
     *      @return array|-1                Array of links or -1 on error
336
     */
337
    function get_url($fk_bank='', $url_id='', $type='')
338
    {
339
        $lines = array();
340
341
        // Check parameters
342
        if (! empty($fk_bank) && (! empty($url_id) || ! empty($type)))
343
        {
344
            $this->error="ErrorBadParameter";
345
            return -1;
346
        }
347
348
        $sql = "SELECT fk_bank, url_id, url, label, type";
349
        $sql.= " FROM ".MAIN_DB_PREFIX."bank_url";
350
        if ($fk_bank > 0) {
351
            $sql.= " WHERE fk_bank = ".$fk_bank;
352
        }
353
        else { $sql.= " WHERE url_id = ".$url_id." AND type = '".$type."'";
354
        }
355
        $sql.= " ORDER BY type, label";
356
357
        dol_syslog(get_class($this)."::get_url", LOG_DEBUG);
358
        $result = $this->db->query($sql);
359
        if ($result)
360
        {
361
            $i = 0;
362
            $num = $this->db->num_rows($result);
363
            while ($i < $num)
364
            {
365
                $obj = $this->db->fetch_object($result);
366
                // Anciens liens (pour compatibilite)
367
                $lines[$i][0] = $obj->url;
368
                $lines[$i][1] = $obj->url_id;
369
                $lines[$i][2] = $obj->label;
370
                $lines[$i][3] = $obj->type;
371
                // Nouveaux liens
372
                $lines[$i]['url'] = $obj->url;
373
                $lines[$i]['url_id'] = $obj->url_id;
374
                $lines[$i]['label'] = $obj->label;
375
                $lines[$i]['type'] = $obj->type;
376
                $lines[$i]['fk_bank'] = $obj->fk_bank;
377
                $i++;
378
            }
379
        }
380
        else dol_print_error($this->db);
381
382
        return $lines;
383
    }
384
385
    /**
386
     *  Add an entry into table ".MAIN_DB_PREFIX."bank
387
     *
388
     *  @param	int	        $date			Date operation
389
     *  @param	string		$oper			1,2,3,4... (deprecated) or TYP,VIR,PRE,LIQ,VAD,CB,CHQ...
390
     *  @param	string		$label			Descripton
391
     *  @param	float		$amount			Amount
392
     *  @param	string		$num_chq		Numero cheque ou virement
393
     *  @param	string		$categorie		Categorie optionnelle
394
     *  @param	User		$user			User that create
395
     *  @param	string		$emetteur		Name of cheque writer
396
     *  @param	string		$banque			Bank of cheque writer
397
     *  @return	int							Rowid of added entry, <0 if KO
398
     */
399
    function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur='',$banque='')
400
    {
401
	    // Deprecatîon warning
402
	    if (is_numeric($oper)) {
403
		    dol_syslog(__METHOD__ . ": using numeric operations is deprecated", LOG_WARNING);
404
	    }
405
406
        // Clean parameters
407
        $emetteur=trim($emetteur);
408
        $banque=trim($banque);
409
410
        $now=dol_now();
411
412
        if (is_numeric($oper))    // Clean oper to have a code instead of a rowid
413
        {
414
            $sql ="SELECT code FROM ".MAIN_DB_PREFIX."c_paiement";
415
            $sql.=" WHERE id=".$oper;
416
            $resql=$this->db->query($sql);
417
            if ($resql)
418
            {
419
                $obj=$this->db->fetch_object($resql);
420
                $oper=$obj->code;
421
            }
422
            else
423
            {
424
                dol_print_error($this->db,'Failed to get payment type code');
425
                return -1;
426
            }
427
        }
428
429
        // Check parameters
430
        if (! $oper)
431
        {
432
            $this->error="oper not defined";
433
            return -1;
434
        }
435
        if (! $this->rowid)
436
        {
437
            $this->error="this->rowid not defined";
438
            return -2;
439
        }
440
        if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ')
441
        {
442
            $this->error="ErrorCashAccountAcceptsOnlyCashMoney";
443
            return -3;
444
        }
445
446
        $this->db->begin();
447
448
        $datev = $date;
449
450
		$accline = new AccountLine($this->db);
451
		$accline->datec = $now;
452
		$accline->dateo = $date;
453
		$accline->datev = $datev;
454
		$accline->label = $label;
455
		$accline->amount = $amount;
456
		$accline->fk_user_author = $user->id;
457
		$accline->fk_account = $this->rowid;
458
		$accline->fk_type = $oper;
459
460
		if ($num_chq) {
461
			$accline->num_chq = $num_chq;
462
		}
463
464
		if ($emetteur) {
465
			$accline->emetteur = $emetteur;
466
		}
467
468
		if ($banque) {
469
			$accline->bank_chq = $banque;
470
		}
471
472
		if ($accline->insert() > 0) {
473
474
			if ($categorie) {
475
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."categorie_account (";
476
				$sql .= "fk_account, fk_categorie";
477
				$sql .= ") VALUES (";
478
				$sql .= " ".$accline->id.", ".$categorie;
479
				$sql .= ")";
480
481
				$result = $this->db->query($sql);
482
				if (!$result) {
483
					$this->db->rollback();
484
					$this->error = $this->db->error();
485
					return -3;
486
				}
487
			}
488
489
			$this->db->commit();
490
			return $accline->id;
491
		} else {
492
			$this->error = $this->db->lasterror();
493
			$this->db->rollback();
494
			return -2;
495
		}
496
	}
497
498
    /**
499
     *  Create bank account into database
500
     *
501
     *  @param	User	$user		Object user making creation
502
     *  @param  int     $notrigger  1=Disable triggers
503
     *  @return int        			< 0 if KO, > 0 if OK
504
     */
505
    function create(User $user = null, $notrigger=0)
506
    {
507
        global $langs,$conf, $hookmanager;
508
509
        // Clean parameters
510
        if (! $this->min_allowed) $this->min_allowed=0;
511
        if (! $this->min_desired) $this->min_desired=0;
512
        $this->state_id = ($this->state_id?$this->state_id:$this->state_id);
513
        $this->country_id = ($this->country_id?$this->country_id:$this->country_id);
514
515
        // Check parameters
516
        if (empty($this->country_id))
517
        {
518
            $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country"));
519
            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
520
            return -1;
521
        }
522
        if (empty($this->ref))
523
        {
524
            $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref"));
525
            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
526
            return -1;
527
        }
528
        if (empty($this->date_solde))
529
        {
530
            $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("DateInitialBalance"));
531
            dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
532
            return -1;
533
        }
534
535
        // Chargement librairie pour acces fonction controle RIB
536
        require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
537
538
        $now=dol_now();
539
540
        $this->db->begin();
541
        
542
        $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account (";
543
        $sql.= "datec";
544
        $sql.= ", ref";
545
        $sql.= ", label";
546
        $sql.= ", entity";
547
        $sql.= ", account_number";
548
		$sql.= ", accountancy_journal";
549
		$sql.= ", bank";
550
        $sql.= ", code_banque";
551
        $sql.= ", code_guichet";
552
        $sql.= ", number";
553
        $sql.= ", cle_rib";
554
        $sql.= ", bic";
555
        $sql.= ", iban_prefix";
556
        $sql.= ", domiciliation";
557
        $sql.= ", proprio";
558
        $sql.= ", owner_address";
559
		$sql.= ", currency_code";
560
        $sql.= ", rappro";
561
        $sql.= ", min_allowed";
562
        $sql.= ", min_desired";
563
        $sql.= ", comment";
564
        $sql.= ", state_id";
565
        $sql.= ", fk_pays";
566
        $sql.= ") VALUES (";
567
        $sql.= "'".$this->db->idate($now)."'";
568
        $sql.= ", '".$this->db->escape($this->ref)."'";
569
        $sql.= ", '".$this->db->escape($this->label)."'";
570
        $sql.= ", ".$conf->entity;
571
        $sql.= ", '".$this->db->escape($this->account_number)."'";
572
		$sql.= ", '".$this->db->escape($this->accountancy_journal)."'";
573
		$sql.= ", '".$this->db->escape($this->bank)."'";
574
        $sql.= ", '".$this->code_banque."'";
575
        $sql.= ", '".$this->code_guichet."'";
576
        $sql.= ", '".$this->number."'";
577
        $sql.= ", '".$this->cle_rib."'";
578
        $sql.= ", '".$this->bic."'";
579
        $sql.= ", '".$this->iban."'";
580
        $sql.= ", '".$this->db->escape($this->domiciliation)."'";
581
        $sql.= ", '".$this->db->escape($this->proprio)."'";
582
        $sql.= ", '".$this->db->escape($this->owner_address)."'";
583
        $sql.= ", '".$this->currency_code."'";
584
        $sql.= ", ".$this->rappro;
585
        $sql.= ", ".price2num($this->min_allowed);
586
        $sql.= ", ".price2num($this->min_desired);
587
        $sql.= ", '".$this->db->escape($this->comment)."'";
588
        $sql.= ", ".($this->state_id>0?"'".$this->state_id."'":"null");
589
        $sql.= ", ".$this->country_id;
590
        $sql.= ")";
591
592
        dol_syslog(get_class($this)."::create", LOG_DEBUG);
593
        $resql=$this->db->query($sql);
594
        if ($resql)
595
        {
596
            $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account");
597
598
            $result=$this->update($user, 1);
599
            if ($result > 0)
600
            {
601
				$accline = new AccountLine($this->db);
602
				$accline->datec = $this->db->idate($now);
603
				$accline->label = '('.$langs->trans("InitialBankBalance").')';
604
				$accline->amount = price2num($this->solde);
605
				$accline->fk_user_author = $user->id;
606
				$accline->fk_account = $this->id;
607
				$accline->datev = $this->db->idate($this->date_solde);
608
				$accline->dateo = $this->db->idate($this->date_solde);
609
				$accline->fk_type = 'SOLD';
610
611
				if ($accline->insert() < 0) {
612
					$error++;
0 ignored issues
show
Bug introduced by
The variable $error does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
613
				    $this->error = $accline->error;
614
				    $this->errors = $accline->errors;
615
				}
616
617
				if (! $error)
618
				{
619
				    $result=$this->insertExtraFields();
620
				    if ($result < 0) $error++;
621
				}
622
                
623
                if (! $error && ! $notrigger)
624
                {
625
                    // Call trigger
626
                    $result=$this->call_trigger('BANKACCOUNT_CREATE',$user);
627
                    if ($result < 0) $error++;
628
                    // End call triggers
629
                }        
630
            }
631
            else
632
            {
633
                $error++;
634
            }
635
        }
636
        else
637
        {
638
            if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
639
            {
640
                $this->error=$langs->trans("ErrorBankLabelAlreadyExists");
641
                $error++;
642
            }
643
            else {
644
                $this->error=$this->db->error()." sql=".$sql;
645
                $error++;
646
            }
647
        }
648
649
        if (! $error)
650
        {
651
            $this->db->commit();
652
            return $this->id;
653
        }
654
        else
655
        {
656
            $this->db->rollback();
657
            return -1*$error;
658
        }
659
    }
660
661
    /**
662
     *    	Update bank account card
663
     *
664
     *    	@param	User	$user       Object user making action
665
     *      @param  int     $notrigger  1=Disable triggers
666
     *		@return	int					<0 if KO, >0 if OK
667
     */
668
    function update(User $user = null, $notrigger = 0)
669
    {
670
        global $langs,$conf, $hookmanager;
671
672
        $error=0;
673
        
674
        $this->db->begin();
675
        
676
        // Clean parameters
677
        $this->state_id = ($this->state_id?$this->state_id:$this->state_id);
678
        $this->country_id = ($this->country_id?$this->country_id:$this->country_id);
679
680
        // Check parameters
681
        if (empty($this->country_id))
682
        {
683
            $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Country"));
684
            dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
685
            return -1;
686
        }
687
        if (empty($this->ref))
688
        {
689
            $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->transnoentitiesnoconv("Ref"));
690
            dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
691
            return -1;
692
        }
693
        if (! $this->label) $this->label = "???";
694
695
        $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET ";
696
697
        $sql.= " ref   = '".$this->db->escape($this->ref)."'";
698
        $sql.= ",label = '".$this->db->escape($this->label)."'";
699
700
        $sql.= ",courant = ".$this->courant;
701
        $sql.= ",clos = ".$this->clos;
702
        $sql.= ",rappro = ".$this->rappro;
703
        $sql.= ",url = ".($this->url?"'".$this->url."'":"null");
704
        $sql.= ",account_number = '".$this->account_number."'";
705
		$sql.= ",accountancy_journal = '".$this->accountancy_journal."'";
706
707
		$sql.= ",bank  = '".$this->db->escape($this->bank)."'";
708
        $sql.= ",code_banque='".$this->code_banque."'";
709
        $sql.= ",code_guichet='".$this->code_guichet."'";
710
        $sql.= ",number='".$this->number."'";
711
        $sql.= ",cle_rib='".$this->cle_rib."'";
712
        $sql.= ",bic='".$this->bic."'";
713
        $sql.= ",iban_prefix = '".$this->iban."'";
714
        $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'";
715
        $sql.= ",proprio = '".$this->db->escape($this->proprio)."'";
716
        $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'";
717
718
        $sql.= ",currency_code = '".$this->currency_code."'";
719
720
        $sql.= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null");
721
        $sql.= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null");
722
        $sql.= ",comment     = '".$this->db->escape($this->comment)."'";
723
724
        $sql.= ",state_id = ".($this->state_id>0?"'".$this->state_id."'":"null");
725
        $sql.= ",fk_pays = ".$this->country_id;
726
727
        $sql.= " WHERE rowid = ".$this->id;
728
        $sql.= " AND entity = ".$conf->entity;
729
730
        dol_syslog(get_class($this)."::update", LOG_DEBUG);
731
        $result = $this->db->query($sql);
732
        if ($result)
733
        {
734
        	// Actions on extra fields (by external module or standard code)
735
    		if (empty($conf->global->MAIN_EXTRAFIELDS_DISABLED)) // For avoid conflicts if trigger used
736
    		{
737
    		    if (! $error)
738
    		    {
739
    		        $result=$this->insertExtraFields();
740
    		        if ($result < 0) $error++;
741
    		    }
742
    		}
743
    		
744
    		if (! $error && ! $notrigger)
745
    		{
746
    		    // Call trigger
747
    		    $result=$this->call_trigger('BANKACCOUNT_UPDATE',$user);
0 ignored issues
show
Bug introduced by
It seems like $user defined by parameter $user on line 668 can be null; however, CommonObject::call_trigger() does not accept null, maybe add an additional type check?

It seems like you allow that null is being passed for a parameter, however the function which is called does not seem to accept null.

We recommend to add an additional type check (or disallow null for the parameter):

function notNullable(stdClass $x) { }

// Unsafe
function withoutCheck(stdClass $x = null) {
    notNullable($x);
}

// Safe - Alternative 1: Adding Additional Type-Check
function withCheck(stdClass $x = null) {
    if ($x instanceof stdClass) {
        notNullable($x);
    }
}

// Safe - Alternative 2: Changing Parameter
function withNonNullableParam(stdClass $x) {
    notNullable($x);
}
Loading history...
748
    		    if ($result < 0) $error++;
749
    		    // End call triggers
750
    		}
751
        }
752
        else
753
        {
754
            $error++;
755
            $this->error=$this->db->lasterror();
756
            dol_print_error($this->db);
757
        }
758
        
759
		if (! $error)
760
		{
761
		    $this->db->commit();
762
		    return $this->id;
763
		}
764
		else
765
		{
766
		    $this->db->rollback();
767
		    return -1*$error;
768
		}
769
    }
770
771
772
    /**
773
     *    	Update BBAN (RIB) account fields
774
     *
775
     *    	@param	User	$user       Object user making update
776
     *		@return	int					<0 if KO, >0 if OK
777
     */
778
    function update_bban(User $user = null)
779
    {
780
        global $conf,$langs;
781
782
        // Clean parameters
783
        $this->state_id = ($this->state_id?$this->state_id:$this->state_id);
784
        $this->country_id = ($this->country_id?$this->country_id:$this->country_id);
785
786
        // Chargement librairie pour acces fonction controle RIB
787
        require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
788
789
        dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban");
790
791
        // Check parameters
792
        if (! $this->ref)
793
        {
794
            $this->error=$langs->transnoentitiesnoconv("ErrorFieldRequired",$langs->trans("Ref"));
795
            return -2;
796
        }
797
798
        $sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET ";
799
        $sql.= " bank  = '".$this->db->escape($this->bank)."'";
800
        $sql.= ",code_banque='".$this->code_banque."'";
801
        $sql.= ",code_guichet='".$this->code_guichet."'";
802
        $sql.= ",number='".$this->number."'";
803
        $sql.= ",cle_rib='".$this->cle_rib."'";
804
        $sql.= ",bic='".$this->bic."'";
805
        $sql.= ",iban_prefix = '".$this->iban."'";
806
        $sql.= ",domiciliation='".$this->db->escape($this->domiciliation)."'";
807
        $sql.= ",proprio = '".$this->db->escape($this->proprio)."'";
808
        $sql.= ",owner_address = '".$this->db->escape($this->owner_address)."'";
809
        $sql.= ",state_id = ".($this->state_id>0?"'".$this->state_id."'":"null");
810
        $sql.= ",fk_pays = ".$this->country_id;
811
        $sql.= " WHERE rowid = ".$this->id;
812
        $sql.= " AND entity = ".$conf->entity;
813
814
        dol_syslog(get_class($this)."::update_bban", LOG_DEBUG);
815
816
        $result = $this->db->query($sql);
817
        if ($result)
818
        {
819
            return 1;
820
        }
821
        else
822
        {
823
            $this->error=$this->db->lasterror();
824
            dol_print_error($this->db);
825
            return -1;
826
        }
827
    }
828
829
830
    /**
831
     *      Load a bank account into memory from database
832
     *
833
     *      @param	int		$id      	Id of bank account to get
834
     *      @param  string	$ref     	Ref of bank account to get
835
     *      @return	int					<0 if KO, >0 if OK
836
     */
837
    function fetch($id, $ref='')
838
    {
839
        global $conf;
840
841
        if (empty($id) && empty($ref))
842
        {
843
            $this->error="ErrorBadParameters";
844
            return -1;
845
        }
846
847
        $sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,";
848
        $sql.= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,";
849
        $sql.= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,";
850
        $sql.= " ba.account_number, ba.accountancy_journal, ba.currency_code,";
851
        $sql.= " ba.min_allowed, ba.min_desired, ba.comment,";
852
        $sql.= " ba.datec as date_creation, ba.tms as date_update,";
853
        $sql.= ' c.code as country_code, c.label as country,';
854
        $sql.= ' d.code_departement as state_code, d.nom as state';
855
        $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
856
        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid';
857
        $sql.= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid';
858
        $sql.= " WHERE entity IN (".getEntity($this->element, 1).")";
859
        if ($id)  $sql.= " AND ba.rowid  = ".$id;
860
        if ($ref) $sql.= " AND ba.ref = '".$this->db->escape($ref)."'";
861
862
        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
863
        $result = $this->db->query($sql);
864
        if ($result)
865
        {
866
            if ($this->db->num_rows($result))
867
            {
868
                $obj = $this->db->fetch_object($result);
869
870
                $this->id            = $obj->rowid;
871
                $this->rowid         = $obj->rowid;
872
                $this->ref           = $obj->ref;
873
                $this->label         = $obj->label;
874
                $this->type          = $obj->courant;
875
                $this->courant       = $obj->courant;
876
                $this->bank          = $obj->bank;
877
                $this->clos          = $obj->clos;
878
                $this->rappro        = $obj->rappro;
879
                $this->url           = $obj->url;
880
881
                $this->code_banque   = $obj->code_banque;
882
                $this->code_guichet  = $obj->code_guichet;
883
                $this->number        = $obj->number;
884
                $this->cle_rib       = $obj->cle_rib;
885
                $this->bic           = $obj->bic;
886
                $this->iban          = $obj->iban;
887
                $this->domiciliation = $obj->domiciliation;
888
                $this->proprio       = $obj->proprio;
889
                $this->owner_address = $obj->owner_address;
890
891
                $this->state_id        = $obj->state_id;
892
                $this->state_code      = $obj->state_code;
893
                $this->state           = $obj->state;
894
895
                $this->country_id    = $obj->country_id;
896
                $this->country_code  = $obj->country_code;
897
                $this->country       = $obj->country;
898
899
                $this->account_number = $obj->account_number;
900
				$this->accountancy_journal = $obj->accountancy_journal;
901
902
                $this->currency_code  = $obj->currency_code;
903
                $this->account_currency_code  = $obj->currency_code;
904
                $this->min_allowed    = $obj->min_allowed;
905
                $this->min_desired    = $obj->min_desired;
906
                $this->comment        = $obj->comment;
907
908
                $this->date_creation  = $this->db->jdate($obj->date_creation);
909
                $this->date_update    = $this->db->jdate($obj->date_update);
910
                
911
                // Retreive all extrafield for thirdparty
912
                // fetch optionals attributes and labels
913
                require_once(DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php');
914
                $extrafields=new ExtraFields($this->db);
915
                $extralabels=$extrafields->fetch_name_optionals_label($this->table_element,true);
916
                $this->fetch_optionals($this->id,$extralabels);
917
918
                return 1;
919
            }
920
            else
921
			{
922
                return 0;
923
            }
924
        }
925
        else
926
        {
927
            dol_print_error($this->db);
928
            return -1;
929
        }
930
    }
931
932
    /**
933
     * Sets object to supplied categories.
934
     *
935
     * Deletes object from existing categories not supplied.
936
     * Adds it to non existing supplied categories.
937
     * Existing categories are left untouch.
938
     *
939
     * @param int[]|int $categories Category or categories IDs
940
     */
941
    public function setCategories($categories) {
942
        // Handle single category
943
        if (! is_array($categories)) {
944
            $categories = array($categories);
945
        }
946
947
        // Get current categories
948
        require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
949
        $c = new Categorie($this->db);
950
        $existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id');
951
952
        // Diff
953
        if (is_array($existing)) {
954
            $to_del = array_diff($existing, $categories);
955
            $to_add = array_diff($categories, $existing);
956
        } else {
957
            $to_del = array(); // Nothing to delete
958
            $to_add = $categories;
959
        }
960
961
        // Process
962
        foreach($to_del as $del) {
963
            if ($c->fetch($del) > 0) {
964
                $c->del_type($this, 'account');
965
            }
966
        }
967
        foreach ($to_add as $add) {
968
            if ($c->fetch($add) > 0) {
969
                $c->add_type($this, 'account');
970
            }
971
        }
972
973
        return;
974
    }
975
976
    /**
977
     *  Delete bank account from database
978
     *
979
     *	@param	User	$user	User deleting
980
     *  @return int             <0 if KO, >0 if OK
981
     */
982
    function delete(User $user = null)
983
    {
984
        global $conf;
985
986
        $error=0;
987
        
988
        $this->db->begin();
989
        
990
        // Delete link between tag and bank account
991
        if (! $error)
992
        {
993
            $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account";
994
            $sql.= " WHERE fk_account = ".$this->id;
995
        
996
            $resql = $this->db->query($sql);
997
            if (!$resql)
998
            {
999
                $error++;
1000
                $this->error = "Error ".$this->db->lasterror();
1001
            }
1002
        }
1003
        
1004
        if (! $error)
1005
        {
1006
            $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account";
1007
            $sql.= " WHERE rowid = ".$this->rowid;
1008
    
1009
            dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1010
            $result = $this->db->query($sql);
1011
            if ($result) 
1012
            {
1013
            	// Remove extrafields
1014
            	if ((empty($conf->global->MAIN_EXTRAFIELDS_DISABLED))) // For avoid conflicts if trigger used
1015
            	{
1016
            		$result=$this->deleteExtraFields();
1017
            		if ($result < 0)
1018
            		{
1019
            		    $error++;
1020
            			dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1021
            		}
1022
            	}
1023
            }
1024
            else 
1025
            {
1026
                $error++;
1027
                $this->error = "Error ".$this->db->lasterror();
1028
            }            
1029
        }
1030
        
1031
        if (! $error)
1032
        {
1033
            $this->db->commit();
1034
            return 1;
1035
        }
1036
        else
1037
        {
1038
            $this->db->rollback();
1039
            return -1;
1040
        }
1041
    }
1042
1043
1044
    /**
1045
	 *  Return label of object status
1046
     *
1047
	 *  @param      int		$mode			0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto
1048
     *  @return     string        		    Label
1049
     */
1050
    function getLibStatut($mode=0)
1051
    {
1052
        return $this->LibStatut($this->clos,$mode);
1053
    }
1054
1055
    /**
1056
     *  Return label of given object status
1057
     *
1058
     *  @param	 int		$statut        	Id statut
1059
	 *  @param   int		$mode			0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=short label + picto, 6=Long label + picto
1060
     *  @return  string        			    Label
1061
     */
1062
	function LibStatut($statut, $mode = 0)
1063
	{
1064
		global $langs;
1065
		$langs->load('banks');
1066
1067
		if ($statut == self::STATUS_OPEN) {
1068
			$label = $langs->trans("StatusAccountOpened");
1069
			$picto = img_picto($label, 'statut4');
1070
		} else {
1071
			$label = $langs->trans("StatusAccountClosed");
1072
			$picto = img_picto($label, 'statut5');
1073
		}
1074
1075
		if ($mode == 2) {
1076
			return $picto.' '.$label;
1077
		} elseif ($mode == 3) {
1078
			return $picto;
1079
		} elseif ($mode == 4) {
1080
			return $picto.' '.$label;
1081
		} elseif ($mode == 5) {
1082
			return $label.' '.$picto;
1083
		} elseif ($mode == 6) {
1084
		    return $label.' '.$picto;
1085
		}
1086
1087
		//There is no short mode for this label
1088
		return $label;
1089
	}
1090
1091
1092
    /**
1093
     *    Renvoi si un compte peut etre supprimer ou non (sans mouvements)
1094
     *
1095
     *    @return     boolean     vrai si peut etre supprime, faux sinon
1096
     */
1097
    function can_be_deleted()
1098
    {
1099
        $can_be_deleted=false;
1100
1101
        $sql = "SELECT COUNT(rowid) as nb";
1102
        $sql.= " FROM ".MAIN_DB_PREFIX."bank";
1103
        $sql.= " WHERE fk_account=".$this->id;
1104
1105
        $resql = $this->db->query($sql);
1106
        if ($resql) {
1107
            $obj=$this->db->fetch_object($resql);
1108
            if ($obj->nb <= 1) $can_be_deleted=true;    // Juste le solde
1109
        }
1110
        else {
1111
            dol_print_error($this->db);
1112
        }
1113
        return $can_be_deleted;
1114
    }
1115
1116
1117
    /**
1118
     *   Return error
1119
     *
1120
     *   @return	string		Error string
1121
     */
1122
    function error()
1123
    {
1124
        return $this->error;
1125
    }
1126
1127
    /**
1128
     * 	Return current sold
1129
     *
1130
     * 	@param	int		$option		1=Exclude future operation date (this is to exclude input made in advance and have real account sold)
1131
     *	@return	int					Current sold (value date <= today)
1132
     */
1133
    function solde($option=0)
1134
    {
1135
        $sql = "SELECT sum(amount) as amount";
1136
        $sql.= " FROM ".MAIN_DB_PREFIX."bank";
1137
        $sql.= " WHERE fk_account = ".$this->id;
1138
        if ($option == 1) $sql.= " AND dateo <= '".$this->db->idate(dol_now())."'";
1139
1140
        $resql = $this->db->query($sql);
1141
        if ($resql)
1142
        {
1143
            if ($this->db->num_rows($resql))
1144
            {
1145
                $obj=$this->db->fetch_object($resql);
1146
                $solde = $obj->amount;
1147
            }
1148
            $this->db->free($resql);
1149
            return $solde;
0 ignored issues
show
Bug introduced by
The variable $solde does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1150
        }
1151
    }
1152
1153
    /**
1154
     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1155
     *
1156
     *      @param	User	$user        		Objet user
1157
     *		@param	int		$filteraccountid	To get info for a particular account id
1158
     *      @return WorkboardResponse|int 		<0 if KO, WorkboardResponse if OK
1159
     */
1160
    function load_board(User $user, $filteraccountid = 0)
1161
    {
1162
        global $conf, $langs;
1163
1164
        if ($user->societe_id) return -1;   // protection pour eviter appel par utilisateur externe
1165
1166
        $sql = "SELECT b.rowid, b.datev as datefin";
1167
        $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,";
1168
        $sql.= " ".MAIN_DB_PREFIX."bank_account as ba";
1169
        $sql.= " WHERE b.rappro=0";
1170
        $sql.= " AND b.fk_account = ba.rowid";
1171
        $sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")";
1172
        $sql.= " AND (ba.rappro = 1 AND ba.courant != 2)";	// Compte rapprochable
1173
        $sql.= " AND clos = 0";
1174
        if ($filteraccountid) $sql.=" AND ba.rowid = ".$filteraccountid;
1175
1176
        $resql=$this->db->query($sql);
1177
        if ($resql)
1178
        {
1179
	        $langs->load("banks");
1180
	        $now=dol_now();
1181
1182
            require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php';
1183
1184
	        $response = new WorkboardResponse();
1185
	        $response->warning_delay=$conf->bank->rappro->warning_delay/60/60/24;
1186
	        $response->label=$langs->trans("TransactionsToConciliate");
1187
	        $response->url=DOL_URL_ROOT.'/compta/bank/index.php?leftmenu=bank&amp;mainmenu=bank';
1188
	        $response->img=img_object('',"payment");
1189
1190
            while ($obj=$this->db->fetch_object($resql))
1191
            {
1192
                $response->nbtodo++;
1193
                if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) {
1194
	                $response->nbtodolate++;
1195
                }
1196
            }
1197
1198
            return $response;
1199
        }
1200
        else
1201
        {
1202
            dol_print_error($this->db);
1203
            $this->error=$this->db->error();
1204
            return -1;
1205
        }
1206
    }
1207
1208
1209
    /**
1210
     *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1211
     *
1212
     *      @return int     Nb of account we can reconciliate
1213
     */
1214
    public static function countAccountToReconcile()
1215
    {
1216
        global $db, $conf, $user;
1217
1218
        //Protection against external users
1219
        if ($user->societe_id) {
1220
            return 0;
1221
        }
1222
1223
        $nb=0;
1224
1225
        $sql = "SELECT COUNT(ba.rowid) as nb";
1226
        $sql.= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
1227
        $sql.= " WHERE ba.rappro > 0 and ba.clos = 0";
1228
        $sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")";
1229
        if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql.= " AND ba.courant != 2";
1230
        $resql=$db->query($sql);
1231
        if ($resql)
1232
        {
1233
            $obj = $db->fetch_object($resql);
1234
            $nb = $obj->nb;
1235
        }
1236
        else dol_print_error($db);
1237
1238
        return $nb;
1239
    }
1240
1241
    /**
1242
     *    	Return clicable name (with picto eventually)
1243
     *
1244
     *		@param	int		$withpicto		Include picto into link
1245
     *      @param  string	$mode           ''=Link to card, 'transactions'=Link to transactions card
1246
     *		@return	string					Chaine avec URL
1247
     */
1248
    function getNomUrl($withpicto=0, $mode='')
1249
    {
1250
        global $conf, $langs;
1251
1252
        $result='';
1253
        $label = '<u>' . $langs->trans("ShowAccount") . '</u>';
1254
        $label .= '<br><b>' . $langs->trans('BankAccount') . ':</b> ' . $this->label;
1255
        $label .= '<br><b>' . $langs->trans('AccountNumber') . ':</b> ' . $this->number;
1256
        if (! empty($conf->accounting->enabled))
1257
        {
1258
            include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1259
            $langs->load("accountancy");
1260
            $label .= '<br><b>' . $langs->trans('AccountAccounting') . ':</b> ' . length_accountg($this->account_number);
1261
            $label .= '<br><b>' . $langs->trans('AccountancyJournal') . ':</b> ' . $this->accountancy_journal;
1262
        }
1263
        $linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1264
1265
        if (empty($mode))
1266
        {
1267
            $link = '<a href="'.DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id.$linkclose;
1268
            $linkend='</a>';
1269
        }
1270
        else if ($mode == 'transactions')
1271
        {
1272
            $link = '<a href="'.DOL_URL_ROOT.'/compta/bank/bankentries.php?id='.$this->id.$linkclose;
1273
            $linkend='</a>';
1274
        }
1275
        else if ($mode == 'receipts')
1276
        {
1277
            $link = '<a href="'.DOL_URL_ROOT.'/compta/bank/releve.php?account='.$this->id.$linkclose;
1278
            $linkend='</a>';
1279
        }
1280
1281
        if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' ');
0 ignored issues
show
Bug introduced by
The variable $link does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $linkend does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
1282
        $result.=$link.$this->ref.$linkend;
1283
        return $result;
1284
    }
1285
1286
1287
    // Method after here are common to Account and CompanyBankAccount
1288
1289
1290
    /**
1291
     *     Return if an account has valid information
1292
     *
1293
     *     @return     int         1 if correct, <=0 if wrong
1294
     */
1295
    function verif()
1296
    {
1297
        require_once DOL_DOCUMENT_ROOT . '/core/lib/bank.lib.php';
1298
1299
        // Call function to check BAN
1300
        if (! checkBanForAccount($this))
1301
        {
1302
            $this->error_number = 12;
1303
            $this->error_message = 'RIBControlError';
1304
        }
1305
1306
        if ($this->error_number == 0)
1307
        {
1308
            return 1;
1309
        }
1310
        else
1311
        {
1312
            return 0;
1313
        }
1314
    }
1315
1316
    /**
1317
     * 	Return account country code
1318
     *
1319
     *	@return		string		country code
1320
     */
1321
    function getCountryCode()
1322
    {
1323
        global $mysoc;
1324
1325
        // We return country code of bank account
1326
        if (! empty($this->country_code)) return $this->country_code;
1327
1328
        // For backward compatibility, we try to guess country from other information
1329
        if (! empty($this->iban))
1330
        {
1331
            // If IBAN defined, we can know country of account from it
1332
            if (preg_match("/^([a-zA-Z][a-zA-Z])/i",$this->iban,$reg)) return $reg[1];
1333
        }
1334
1335
        // If this class is linked to a third party
1336
        if (! empty($this->socid))
1337
        {
1338
            require_once DOL_DOCUMENT_ROOT .'/societe/class/societe.class.php';
1339
            $company=new Societe($this->db);
1340
            $result=$company->fetch($this->socid);
1341
            if (! empty($company->country_code)) return $company->country_code;
1342
        }
1343
1344
        // We return country code of managed company
1345
        if (! empty($mysoc->country_code)) return $mysoc->country_code;
1346
1347
        return '';
1348
    }
1349
1350
    /**
1351
     * Return if a bank account is defined with detailed information (bank code, desk code, number and key).
1352
     * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code
1353
     *
1354
     * @return		int        0=No bank code need + Account number is enough
1355
     *                         1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key
1356
     *                         2=Need 1 field for bank code:  Bank only (Sort code for Great Britain, BSB for Australia) + Account number
1357
     */
1358
    function useDetailedBBAN()
1359
    {
1360
        $country_code=$this->getCountryCode();
1361
1362
        if (in_array($country_code,array('CH','FR','ES','GA','IT'))) return 1; // France, Spain, Gabon, ...
1363
        if (in_array($country_code,array('AU','BE','CA','DE','DK','GR','GB','ID','IE','IR','KR','NL','NZ','UK','US'))) return 2;      // Australia, England...
1364
        return 0;
1365
    }
1366
1367
    /**
1368
     * Return 1 if IBAN / BIC is mandatory (otherwise option)
1369
     *
1370
     * @return		int        1 = mandatory / 0 = Not mandatory
1371
     */
1372
    function needIBAN()
1373
    {
1374
    	$country_code=$this->getCountryCode();
1375
1376
    	$country_code_in_EEC=array(
1377
    			'AT',	// Austria
1378
    			'BE',	// Belgium
1379
    			'BG',	// Bulgaria
1380
    			'CY',	// Cyprus
1381
    			'CZ',	// Czech republic
1382
    			'DE',	// Germany
1383
    			'DK',	// Danemark
1384
    			'EE',	// Estonia
1385
    			'ES',	// Spain
1386
    			'FI',	// Finland
1387
    			'FR',	// France
1388
    			'GB',	// United Kingdom
1389
    			'GR',	// Greece
1390
    			'HR',   // Croatia
1391
    			'NL',	// Holland
1392
    			'HU',	// Hungary
1393
    			'IE',	// Ireland
1394
    			'IM',	// Isle of Man - Included in UK
1395
    			'IT',	// Italy
1396
    			'LT',	// Lithuania
1397
    			'LU',	// Luxembourg
1398
    			'LV',	// Latvia
1399
    			'MC',	// Monaco - Included in France
1400
    			'MT',	// Malta
1401
    			//'NO',	// Norway
1402
    			'PL',	// Poland
1403
    			'PT',	// Portugal
1404
    			'RO',	// Romania
1405
    			'SE',	// Sweden
1406
    			'SK',	// Slovakia
1407
    			'SI',	// Slovenia
1408
    			'UK',	// United Kingdom
1409
    			//'CH',	// Switzerland - No. Swizerland in not in EEC
1410
    	);
1411
1412
    	if (in_array($country_code,$country_code_in_EEC)) return 1; // France, Spain, ...
1413
    	return 0;
1414
    }
1415
1416
    /**
1417
     *	Load miscellaneous information for tab "Info"
1418
     *
1419
     *	@param  int		$id		Id of object to load
1420
     *	@return	void
1421
     */
1422
    function info($id)
1423
    {
1424
1425
    }
1426
1427
	/**
1428
	 * Returns the fields in order that this bank account should show to the user
1429
	 * Will return an array with the following values:
1430
	 * - BankAccountNumber
1431
	 * - BankCode
1432
	 * - BankAccountNumberKey
1433
	 * - DeskCode
1434
	 *
1435
	 * Some countries show less or more bank account properties to the user
1436
	 * 
1437
	 * @param  int     $includeibanbic         1=Return also key for IBAN and BIC
1438
	 * @return array
1439
	 * @see useDetailedBBAN
1440
	 */
1441
	public function getFieldsToShow($includeibanbic=0)
1442
	{
1443
		//Get the required properties depending on the country
1444
		$detailedBBAN = $this->useDetailedBBAN();
1445
1446
		if ($detailedBBAN == 0) {
1447
			$fieldarray= array(
1448
					'BankAccountNumber'
1449
			);
1450
		} elseif ($detailedBBAN == 2) {
1451
			$fieldarray= array(
1452
					'BankCode',
1453
					'BankAccountNumber'
1454
			);
1455
		} else {
1456
			$fieldarray=self::getAccountNumberOrder();
1457
		}
1458
1459
		//if ($this->needIBAN()) {    // return always IBAN and BIC (this was old behaviour)
1460
		if ($includeibanbic)
1461
		{
1462
			$fieldarray[]='IBAN';
1463
			$fieldarray[]='BIC';
1464
		}
1465
		//}
1466
1467
		//Get the order the properties are shown
1468
		return $fieldarray;
1469
1470
	}
1471
1472
	/**
1473
	 * Returns the components of the bank account in order.
1474
	 * Will return an array with the following values:
1475
	 * - BankAccountNumber
1476
	 * - BankCode
1477
	 * - BankAccountNumberKey
1478
	 * - DeskCode
1479
	 *
1480
	 * @return array
1481
	 */
1482
	public static function getAccountNumberOrder()
1483
	{
1484
		global $conf;
1485
1486
		$fieldlists = array(
1487
				'BankCode',
1488
				'DeskCode',
1489
				'BankAccountNumber',
1490
				'BankAccountNumberKey'
1491
		);
1492
1493
		if (!empty($conf->global->BANK_SHOW_ORDER_OPTION)) {
1494
			if (is_numeric($conf->global->BANK_SHOW_ORDER_OPTION)) {
1495
				if ($conf->global->BANK_SHOW_ORDER_OPTION == '1') {
1496
					$fieldlists = array(
1497
						'BankCode',
1498
						'DeskCode',
1499
						'BankAccountNumberKey',
1500
						'BankAccountNumber'
1501
					);
1502
				}
1503
			} else {
1504
				//Replace the old AccountNumber key with the new BankAccountNumber key
1505
				$fieldlists = explode(
1506
					' ',
1507
					preg_replace('/ ?[^Bank]AccountNumber ?/', 'BankAccountNumber',
1508
						$conf->global->BANK_SHOW_ORDER_OPTION)
1509
				);
1510
			}
1511
		}
1512
1513
		return $fieldlists;
1514
	}
1515
1516
1517
    /**
1518
     *  Initialise an instance with random values.
1519
     *  Used to build previews or test instances.
1520
     *	id must be 0 if object instance is a specimen.
1521
     *
1522
     *  @return	void
1523
     */
1524
    function initAsSpecimen()
1525
    {
1526
        $this->specimen        = 1;
1527
        $this->ref             = 'MBA';
1528
        $this->label           = 'My Big Company Bank account';
1529
        $this->bank            = 'MyBank';
1530
        $this->courant         = Account::TYPE_CURRENT;
1531
        $this->clos            = Account::STATUS_OPEN;
1532
        $this->code_banque     = '123';
1533
        $this->code_guichet    = '456';
1534
        $this->number          = 'ABC12345';
1535
        $this->cle_rib         = 50;
0 ignored issues
show
Documentation Bug introduced by
The property $cle_rib was declared of type string, but 50 is of type integer. Maybe add a type cast?

This check looks for assignments to scalar types that may be of the wrong type.

To ensure the code behaves as expected, it may be a good idea to add an explicit type cast.

$answer = 42;

$correct = false;

$correct = (bool) $answer;
Loading history...
1536
        $this->bic             = 'AA12';
1537
        $this->iban            = 'FR999999999';
1538
        $this->domiciliation   = 'My bank address';
1539
        $this->proprio         = 'Owner';
1540
        $this->owner_address   = 'Owner address';
1541
        $this->country_id      = 1;
1542
    }
1543
1544
}
1545
1546
1547
/**
1548
 *	Class to manage bank transaction lines
1549
 */
1550
class AccountLine extends CommonObject
1551
{
1552
    var $error;
1553
    var $db;
1554
    var $element='bank';
1555
    var $table_element='bank';
1556
    var $picto = 'generic';
1557
    
1558
    var $id;
1559
    var $ref;
1560
    var $datec;
1561
    var $dateo;
1562
1563
    /**
1564
     * Value date
1565
     */
1566
    var $datev;
1567
    var $amount;
1568
    var $label;
1569
    var $note;
1570
    var $fk_user_author;
1571
    var $fk_user_rappro;
1572
    var $fk_type;
1573
    var $rappro;        // Is it conciliated
1574
    var $num_releve;    // If conciliated, what is bank statement
1575
    var $num_chq;       // Num of cheque
1576
    var $bank_chq;      // Bank of cheque
1577
    var $fk_bordereau;  // Id of cheque receipt
1578
1579
    var $fk_account;            // Id of bank account
1580
    var $bank_account_label;    // Label of bank account
1581
1582
    public $emetteur;
1583
1584
    /**
1585
     *  Constructor
1586
     *
1587
     *  @param	DoliDB	$db		Database handler
1588
     */
1589
    function __construct(DoliDB $db)
1590
    {
1591
        $this->db = $db;
1592
    }
1593
1594
    /**
1595
     *  Load into memory content of a bank transaction line
1596
     *
1597
     *  @param		int		$rowid   	Id of bank transaction to load
1598
     *  @param      string	$ref     	Ref of bank transaction to load
1599
     *  @param      string	$num     	External num to load (ex: num of transaction for paypal fee)
1600
     *	@return		int					<0 if KO, 0 if OK but not found, >0 if OK and found
1601
     */
1602
    function fetch($rowid,$ref='',$num='')
1603
    {
1604
        global $conf;
1605
1606
        // Check parameters
1607
        if (empty($rowid) && empty($ref) && empty($num)) return -1;
1608
1609
        $sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,";
1610
        $sql.= " b.fk_user_author, b.fk_user_rappro,";
1611
        $sql.= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,";
1612
        $sql.= " b.fk_bordereau, b.banque, b.emetteur,";
1613
        //$sql.= " b.author"; // Is this used ?
1614
        $sql.= " ba.ref as bank_account_ref, ba.label as bank_account_label";
1615
        $sql.= " FROM ".MAIN_DB_PREFIX."bank as b,";
1616
        $sql.= " ".MAIN_DB_PREFIX."bank_account as ba";
1617
        $sql.= " WHERE b.fk_account = ba.rowid";
1618
        $sql.= " AND ba.entity IN (".getEntity('bank_account', 1).")";
1619
        if ($num) $sql.= " AND b.num_chq='".$this->db->escape($num)."'";
1620
        else if ($ref) $sql.= " AND b.rowid='".$this->db->escape($ref)."'";
1621
        else $sql.= " AND b.rowid=".$rowid;
1622
1623
        dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1624
        $result = $this->db->query($sql);
1625
        if ($result)
1626
        {
1627
            $ret=0;
1628
1629
            $obj = $this->db->fetch_object($result);
1630
            if ($obj)
1631
            {
1632
                $this->id				= $obj->rowid;
1633
                $this->rowid			= $obj->rowid;
1634
                $this->ref				= $obj->rowid;
1635
1636
                $this->datec			= $obj->datec;
1637
                $this->datev			= $obj->datev;
1638
                $this->dateo			= $obj->dateo;
1639
                $this->amount			= $obj->amount;
1640
                $this->label			= $obj->label;
1641
                $this->note				= $obj->note;
1642
1643
                $this->fk_user_author	= $obj->fk_user_author;
1644
                $this->fk_user_rappro	= $obj->fk_user_rappro;
1645
1646
                $this->fk_type			= $obj->fk_type;      // Type of transaction
1647
                $this->rappro			= $obj->rappro;
1648
                $this->num_releve		= $obj->num_releve;
1649
1650
                $this->num_chq			= $obj->num_chq;
1651
                $this->bank_chq			= $obj->banque;
1652
                $this->fk_bordereau		= $obj->fk_bordereau;
1653
1654
                $this->fk_account		= $obj->fk_account;
1655
                $this->bank_account_ref   = $obj->bank_account_ref;
1656
                $this->bank_account_label = $obj->bank_account_label;
1657
1658
                $ret=1;
1659
            }
1660
            $this->db->free($result);
1661
            return $ret;
1662
        }
1663
        else
1664
        {
1665
            return -1;
1666
        }
1667
    }
1668
1669
	/**
1670
	 * Inserts a transaction to a bank account
1671
	 *
1672
	 * @return int <0 if KO, rowid of the line if OK
1673
	 */
1674
	public function insert()
1675
	{
1676
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."bank (";
1677
		$sql .= "datec";
1678
		$sql .= ", dateo";
1679
		$sql .= ", datev";
1680
		$sql .= ", label";
1681
		$sql .= ", amount";
1682
		$sql .= ", fk_user_author";
1683
		$sql .= ", num_chq";
1684
		$sql .= ", fk_account";
1685
		$sql .= ", fk_type";
1686
		$sql .= ",emetteur,banque";
1687
		$sql .= ", rappro";
1688
		$sql .= ") VALUES (";
1689
		$sql .= "'".$this->db->idate($this->datec)."'";
1690
		$sql .= ", '".$this->db->idate($this->dateo)."'";
1691
		$sql .= ", '".$this->db->idate($this->datev)."'";
1692
		$sql .= ", '".$this->db->escape($this->label)."'";
1693
		$sql .= ", ".price2num($this->amount);
1694
		$sql .= ", ".($this->fk_user_author > 0 ? "'".$this->fk_user_author."'":"null");
1695
		$sql .= ", ".($this->num_chq ? "'".$this->num_chq."'" : "null");
1696
		$sql .= ", '".$this->fk_account."'";
1697
		$sql .= ", '".$this->db->escape($this->fk_type)."'";
1698
		$sql .= ", ".($this->emetteur ? "'".$this->db->escape($this->emetteur)."'" : "null");
1699
		$sql .= ", ".($this->bank_chq ? "'".$this->db->escape($this->bank_chq)."'" : "null");
1700
		$sql .= ", ".(int) $this->rappro;
1701
		$sql .= ")";
1702
1703
		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
1704
		$resql = $this->db->query($sql);
1705
1706
		if (!$resql) {
1707
			$this->error = $this->db->lasterror();
1708
			return -1;
1709
		}
1710
1711
		$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'bank');
1712
1713
		return $this->id;
1714
	}
1715
1716
    /**
1717
     *      Delete transaction bank line record
1718
     *
1719
     *		@param	User	$user	User object that delete
1720
     *      @return	int 			<0 if KO, >0 if OK
1721
     */
1722
    function delete(User $user = null)
1723
    {
1724
        $nbko=0;
1725
1726
        if ($this->rappro)
1727
        {
1728
            // Protection to avoid any delete of consolidated lines
1729
            $this->error="ErrorDeleteNotPossibleLineIsConsolidated";
1730
            return -1;
1731
        }
1732
1733
        $this->db->begin();
1734
1735
        // Delete urls
1736
        $result=$this->delete_urls($user);
1737
        if ($result < 0)
1738
        {
1739
            $nbko++;
1740
        }
1741
1742
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid;
1743
        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1744
        $result = $this->db->query($sql);
1745
        if (! $result) $nbko++;
1746
1747
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid;
1748
        dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1749
        $result = $this->db->query($sql);
1750
        if (! $result) $nbko++;
1751
1752
        if (! $nbko)
1753
        {
1754
            $this->db->commit();
1755
            return 1;
1756
        }
1757
        else
1758
        {
1759
            $this->db->rollback();
1760
            return -$nbko;
1761
        }
1762
    }
1763
1764
1765
    /**
1766
     *      Delete bank line records
1767
     *
1768
     *		@param	User	$user	User object that delete
1769
     *      @return	int 			<0 if KO, >0 if OK
1770
     */
1771
    function delete_urls(User $user = null)
1772
    {
1773
        $nbko=0;
1774
1775
        if ($this->rappro)
1776
        {
1777
            // Protection to avoid any delete of consolidated lines
1778
            $this->error="ErrorDeleteNotPossibleLineIsConsolidated";
1779
            return -1;
1780
        }
1781
1782
        $this->db->begin();
1783
1784
        $sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid;
1785
        dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG);
1786
        $result = $this->db->query($sql);
1787
        if (! $result) $nbko++;
1788
1789
        if (! $nbko)
1790
        {
1791
            $this->db->commit();
1792
            return 1;
1793
        }
1794
        else
1795
        {
1796
            $this->db->rollback();
1797
            return -$nbko;
1798
        }
1799
    }
1800
1801
1802
    /**
1803
     *		Update bank account record in database
1804
     *
1805
     *		@param	User	$user			Object user making update
1806
     *		@param 	int		$notrigger		0=Disable all triggers
1807
     *		@return	int						<0 if KO, >0 if OK
1808
     */
1809
    function update(User $user, $notrigger = 0)
1810
    {
1811
        $this->db->begin();
1812
1813
        $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
1814
        $sql.= " amount = ".price2num($this->amount).",";
1815
        $sql.= " datev='".$this->db->idate($this->datev)."',";
1816
        $sql.= " dateo='".$this->db->idate($this->dateo)."'";
1817
        $sql.= " WHERE rowid = ".$this->rowid;
1818
1819
        dol_syslog(get_class($this)."::update", LOG_DEBUG);
1820
        $resql = $this->db->query($sql);
1821
        if ($resql)
1822
        {
1823
            $this->db->commit();
1824
            return 1;
1825
        }
1826
        else
1827
        {
1828
            $this->db->rollback();
1829
            $this->error=$this->db->error();
1830
            return -1;
1831
        }
1832
    }
1833
1834
1835
    /**
1836
     *		Update conciliation field
1837
     *
1838
     *		@param	User	$user		Objet user making update
1839
     *		@param 	int		$cat		Category id
1840
     *		@return	int					<0 if KO, >0 if OK
1841
     */
1842
    function update_conciliation(User $user, $cat)
1843
    {
1844
        global $conf;
1845
        
1846
        $this->db->begin();
1847
1848
        // Check statement field
1849
        if (! empty($conf->global->BANK_STATEMENT_REGEX_RULE))
1850
        {
1851
            if (! preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve))
1852
            {
1853
                $this->errors[]=$langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE);
0 ignored issues
show
Bug introduced by
The variable $langs does not exist. Did you forget to declare it?

This check marks access to variables or properties that have not been declared yet. While PHP has no explicit notion of declaring a variable, accessing it before a value is assigned to it is most likely a bug.

Loading history...
1854
                return -1;
1855
            }
1856
        }
1857
        
1858
        $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
1859
        $sql.= " rappro = 1";
1860
        $sql.= ", num_releve = '".$this->num_releve."'";
1861
        $sql.= ", fk_user_rappro = ".$user->id;
1862
        $sql.= " WHERE rowid = ".$this->id;
1863
1864
        dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG);
1865
        $resql = $this->db->query($sql);
1866
        if ($resql)
1867
        {
1868
            if (! empty($cat))
1869
            {
1870
                $sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class (";
1871
                $sql.= "lineid";
1872
                $sql.= ", fk_categ";
1873
                $sql.= ") VALUES (";
1874
                $sql.= $this->id;
1875
                $sql.= ", ".$cat;
1876
                $sql.= ")";
1877
1878
                dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG);
1879
                $this->db->query($sql);
1880
1881
                // No error check. Can fail if category already affected
1882
            }
1883
1884
            $this->rappro=1;
1885
1886
            $this->db->commit();
1887
            return 1;
1888
        }
1889
        else
1890
        {
1891
            $this->db->rollback();
1892
            return -1;
1893
        }
1894
    }
1895
1896
1897
    /**
1898
     * 	Increase/decrease value date of a rowid
1899
     *
1900
     *	@param	int		$rowid		Id of line
1901
     *	@param	int		$sign		1 or -1
1902
     *	@return	int					>0 if OK, 0 if KO
1903
     */
1904
    function datev_change($rowid,$sign=1)
1905
    {
1906
        $sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid;
1907
        $resql = $this->db->query($sql);
1908
        if ($resql)
1909
        {
1910
            $obj=$this->db->fetch_object($resql);
1911
            $newdate=$this->db->jdate($obj->datev)+(3600*24*$sign);
1912
1913
            $sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
1914
            $sql.= " datev = '".$this->db->idate($newdate)."'";
1915
            $sql.= " WHERE rowid = ".$rowid;
1916
1917
            $result = $this->db->query($sql);
1918
            if ($result)
1919
            {
1920
                if ($this->db->affected_rows($result))
1921
                {
1922
                    return 1;
1923
                }
1924
            }
1925
            else
1926
            {
1927
                dol_print_error($this->db);
1928
                return 0;
1929
            }
1930
        }
1931
        else dol_print_error($this->db);
1932
        return 0;
1933
    }
1934
1935
    /**
1936
     * 	Increase value date of a rowid
1937
     *
1938
     *	@param	int		$id		Id of line to change
1939
     *	@return	int				>0 if OK, 0 if KO
1940
     */
1941
    function datev_next($id)
1942
    {
1943
        return $this->datev_change($id,1);
1944
    }
1945
1946
    /**
1947
     * 	Decrease value date of a rowid
1948
     *
1949
     *	@param	int		$id		Id of line to change
1950
     *	@return	int				>0 if OK, 0 if KO
1951
     */
1952
    function datev_previous($id)
1953
    {
1954
        return $this->datev_change($id,-1);
1955
    }
1956
1957
1958
    /**
1959
     *	Load miscellaneous information for tab "Info"
1960
     *
1961
     *	@param  int		$id		Id of object to load
1962
     *	@return	void
1963
     */
1964
    function info($id)
1965
    {
1966
        $sql = 'SELECT b.rowid, b.datec, b.tms as datem,';
1967
        $sql.= ' b.fk_user_author, b.fk_user_rappro';
1968
        $sql.= ' FROM '.MAIN_DB_PREFIX.'bank as b';
1969
        $sql.= ' WHERE b.rowid = '.$id;
1970
1971
        $result=$this->db->query($sql);
1972
        if ($result)
1973
        {
1974
            if ($this->db->num_rows($result))
1975
            {
1976
                $obj = $this->db->fetch_object($result);
1977
                $this->id = $obj->rowid;
1978
1979
                if ($obj->fk_user_author)
1980
                {
1981
                    $cuser = new User($this->db);
1982
                    $cuser->fetch($obj->fk_user_author);
1983
                    $this->user_creation     = $cuser;
1984
                }
1985
                if ($obj->fk_user_rappro)
1986
                {
1987
                    $ruser = new User($this->db);
1988
                    $ruser->fetch($obj->fk_user_rappro);
1989
                    $this->user_rappro = $ruser;
1990
                }
1991
1992
                $this->date_creation     = $this->db->jdate($obj->datec);
1993
                $this->date_modification = $this->db->jdate($obj->datem);
1994
                //$this->date_rappro       = $obj->daterappro;    // Not yet managed
1995
            }
1996
            $this->db->free($result);
1997
        }
1998
        else
1999
        {
2000
            dol_print_error($this->db);
2001
        }
2002
    }
2003
2004
2005
    /**
2006
     *    	Return clicable name (with picto eventually)
2007
     *
2008
     *		@param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
2009
     *		@param	int		$maxlen			Longueur max libelle
2010
     *		@param	string	$option			Option ('showall')
2011
     *		@return	string					Chaine avec URL
2012
     */
2013
    function getNomUrl($withpicto=0,$maxlen=0,$option='')
2014
    {
2015
        global $langs;
2016
2017
        $result='';
2018
        $label=$langs->trans("ShowTransaction").': '.$this->rowid;
2019
        $link = '<a href="'.DOL_URL_ROOT.'/compta/bank/ligne.php?rowid='.$this->rowid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
2020
        $linkend='</a>';
2021
2022
        if ($withpicto) $result.=($link.img_object($label, 'account', 'class="classfortooltip"').$linkend.' ');
2023
        $result.=$link.$this->rowid.$linkend;
2024
2025
        if ($option == 'showall' || $option == 'showconciliated') $result.=' (';
2026
        if ($option == 'showall')
2027
        {
2028
            $result.=$langs->trans("BankAccount").': ';
2029
            $accountstatic=new Account($this->db);
2030
            $accountstatic->id=$this->fk_account;
2031
            $accountstatic->label=$this->bank_account_label;
2032
            $result.=$accountstatic->getNomUrl(0).', ';
2033
        }
2034
        if ($option == 'showall' || $option == 'showconciliated')
2035
        {
2036
            $result.=$langs->trans("BankLineConciliated").': ';
2037
            $result.=yn($this->rappro);
2038
        }
2039
        if ($option == 'showall' || $option == 'showconciliated') $result.=')';
2040
2041
        return $result;
2042
    }
2043
2044
    
2045
    /**
2046
     *    Return label of status (activity, closed)
2047
     *
2048
     *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
2049
     *    @return   string        		Libelle
2050
     */
2051
    function getLibStatut($mode=0)
2052
    {
2053
        return $this->LibStatut($this->status,$mode);
2054
    }
2055
    
2056
    /**
2057
     *  Renvoi le libelle d'un statut donne
2058
     *
2059
     *  @param	int		$statut         Id statut
2060
     *  @param	int		$mode           0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2061
     *  @return	string          		Libelle du statut
2062
     */
2063
    function LibStatut($statut,$mode=0)
2064
    {
2065
        global $langs;
2066
        //$langs->load('companies');
2067
        /*
2068
        if ($mode == 0)
2069
        {
2070
            if ($statut==0) return $langs->trans("ActivityCeased");
2071
            if ($statut==1) return $langs->trans("InActivity");
2072
        }
2073
        if ($mode == 1)
2074
        {
2075
            if ($statut==0) return $langs->trans("ActivityCeased");
2076
            if ($statut==1) return $langs->trans("InActivity");
2077
        }
2078
        if ($mode == 2)
2079
        {
2080
            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2081
            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2082
        }
2083
        if ($mode == 3)
2084
        {
2085
            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2086
            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2087
        }
2088
        if ($mode == 4)
2089
        {
2090
            if ($statut==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2091
            if ($statut==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2092
        }
2093
        if ($mode == 5)
2094
        {
2095
            if ($statut==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2096
            if ($statut==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2097
        }*/
2098
    }
2099
    
2100
}
2101
2102