Passed
Branch develop (f6c1a1)
by
unknown
28:54
created

Account::fetch()   B

Complexity

Conditions 7
Paths 13

Size

Total Lines 89
Code Lines 68

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 7
eloc 68
nc 13
nop 2
dl 0
loc 89
rs 7.7648
c 0
b 0
f 0

How to fix   Long Method   

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) 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-2017	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 <https://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
	/**
40
	 * @var string ID to identify managed object
41
	 */
42
	public $element = 'bank_account';
43
44
	/**
45
	 * @var string Name of table without prefix where object is stored
46
	 */
47
	public $table_element = 'bank_account';
48
49
	/**
50
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
51
	 */
52
	public $picto = 'account';
53
54
	/**
55
	 * @var	int		Use id instead of rowid
56
	 * @deprecated
57
	 * @see $id
58
	 */
59
	public $rowid;
60
61
	/**
62
	 * Account Label
63
	 * @var string
64
	 */
65
	public $label;
66
67
	/**
68
	 * Bank account type. Check TYPE_ constants
69
	 * @var int
70
	 */
71
	public $courant;
72
73
	/**
74
	 * Bank account type. Check TYPE_ constants
75
	 * @var int
76
	 */
77
	public $type;
78
79
	/**
80
	 * Bank name
81
	 * @var string
82
	 */
83
	public $bank;
84
85
	/**
86
	 * Status
87
	 * @var int
88
	 */
89
	public $clos = self::STATUS_OPEN;
90
91
	/**
92
	 * Does it need to be conciliated?
93
	 * @var int
94
	 */
95
	public $rappro = 1;
96
97
	/**
98
	 * Webpage
99
	 * @var string
100
	 */
101
	public $url;
102
103
	/**
104
	 * Bank number. If in SEPA area, you should move to IBAN field
105
	 * @var string
106
	 */
107
	public $code_banque;
108
109
	/**
110
	 * Branch number. If in SEPA area, you should move to IBAN field
111
	 * @var string
112
	 */
113
	public $code_guichet;
114
115
	/**
116
	 * Account number. If in SEPA area, you should move to IBAN field
117
	 * @var string
118
	 */
119
	public $number;
120
121
	/**
122
	 * Bank account number control digit. If in SEPA area, you should move to IBAN field
123
	 * @var string
124
	 */
125
	public $cle_rib;
126
127
	/**
128
	 * BIC/Swift code
129
	 * @var string
130
	 */
131
	public $bic;
132
133
	/**
134
	 * IBAN number (International Bank Account Number). Stored into iban_prefix field into database
135
	 * @var string
136
	 */
137
	public $iban;
138
139
	/**
140
	 * Name of account holder
141
	 * @var string
142
	 */
143
	public $proprio;
144
145
	/**
146
	 * Address of account holder
147
	 * @var string
148
	 */
149
	public $owner_address;
150
151
	public $state_id;
152
	public $state_code;
153
	public $state;
154
155
	/**
156
	 * Variable containing all account types with their respective translated label.
157
	 * Defined in __construct
158
	 * @var array
159
	 */
160
	public $type_lib = array();
161
162
	/**
163
	 * Variable containing all account statuses with their respective translated label.
164
	 * Defined in __construct
165
	 * @var array
166
	 */
167
	public $status = array();
168
169
	/**
170
	 * Accountancy code
171
	 * @var string
172
	 */
173
	public $account_number;
174
175
	/**
176
     * @var int ID
177
     */
178
	public $fk_accountancy_journal;
179
180
	/**
181
	 * Currency code
182
	 * @var string
183
	 */
184
	public $currency_code;
185
186
	/**
187
	 * Currency code
188
	 * @var string
189
	 * @deprecated Use currency_code instead
190
	 */
191
	public $account_currency_code;
192
193
	/**
194
	 * Authorized minimum balance
195
	 * @var float
196
	 */
197
	public $min_allowed;
198
199
	/**
200
	 * Desired minimum balance
201
	 * @var float
202
	 */
203
	public $min_desired;
204
205
	/**
206
	 * Notes
207
	 * @var string
208
	 */
209
	public $comment;
210
211
	/**
212
	 * Date of the initial balance. Used in Account::create
213
	 * @var int
214
	 */
215
	public $date_solde;
216
217
218
	/**
219
	 *  'type' if the field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
220
	 *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
221
	 *  'label' the translation key.
222
	 *  'enabled' is a condition when the field must be managed.
223
	 *  'position' is the sort order of field.
224
	 *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
225
	 *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
226
	 *  'noteditable' says if field is not editable (1 or 0)
227
	 *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
228
	 *  'index' if we want an index in database.
229
	 *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
230
	 *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
231
	 *  'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
232
	 *  'css' is the CSS style to use on field. For example: 'maxwidth200'
233
	 *  'help' is a string visible as a tooltip on field
234
	 *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
235
	 *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
236
	 *  'arraykeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
237
	 *  'comment' is not used. You can store here any text of your choice. It is not used by application.
238
	 *
239
	 *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
240
	 */
241
242
	// BEGIN MODULEBUILDER PROPERTIES
243
	/**
244
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
245
	 */
246
	public $fields = array(
247
		'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
248
		'ref' =>array('type'=>'varchar(12)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'showoncombobox'=>1, 'position'=>25),
249
		'label' =>array('type'=>'varchar(30)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>30),
250
		'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>35, 'index'=>1),
251
		'bank' =>array('type'=>'varchar(60)', 'label'=>'Bank', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
252
		'code_banque' =>array('type'=>'varchar(128)', 'label'=>'Code banque', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
253
		'code_guichet' =>array('type'=>'varchar(6)', 'label'=>'Code guichet', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
254
		'number' =>array('type'=>'varchar(255)', 'label'=>'Number', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
255
		'cle_rib' =>array('type'=>'varchar(5)', 'label'=>'Cle rib', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
256
		'bic' =>array('type'=>'varchar(11)', 'label'=>'Bic', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
257
		'iban_prefix' =>array('type'=>'varchar(34)', 'label'=>'Iban prefix', 'enabled'=>1, 'visible'=>-1, 'position'=>70),
258
		'country_iban' =>array('type'=>'varchar(2)', 'label'=>'Country iban', 'enabled'=>1, 'visible'=>-1, 'position'=>75),
259
		'cle_iban' =>array('type'=>'varchar(2)', 'label'=>'Cle iban', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
260
		'domiciliation' =>array('type'=>'varchar(255)', 'label'=>'Domiciliation', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
261
		'state_id' =>array('type'=>'integer', 'label'=>'State id', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
262
		'fk_pays' =>array('type'=>'integer', 'label'=>'Fk pays', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>95),
263
		'proprio' =>array('type'=>'varchar(60)', 'label'=>'Proprio', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
264
		'owner_address' =>array('type'=>'text', 'label'=>'Owner address', 'enabled'=>1, 'visible'=>-1, 'position'=>105),
265
		'courant' =>array('type'=>'smallint(6)', 'label'=>'Courant', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>110),
266
		'clos' =>array('type'=>'smallint(6)', 'label'=>'Clos', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>115),
267
		'rappro' =>array('type'=>'smallint(6)', 'label'=>'Rappro', 'enabled'=>1, 'visible'=>-1, 'position'=>120),
268
		'url' =>array('type'=>'varchar(128)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>125),
269
		'account_number' =>array('type'=>'varchar(32)', 'label'=>'Account number', 'enabled'=>1, 'visible'=>-1, 'position'=>130),
270
		'accountancy_journal' =>array('type'=>'varchar(20)', 'label'=>'Accountancy journal', 'enabled'=>1, 'visible'=>-1, 'position'=>135),
271
		'currency_code' =>array('type'=>'varchar(3)', 'label'=>'Currency code', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>140),
272
		'min_allowed' =>array('type'=>'integer', 'label'=>'Min allowed', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
273
		'min_desired' =>array('type'=>'integer', 'label'=>'Min desired', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
274
		'comment' =>array('type'=>'text', 'label'=>'Comment', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
275
		'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'position'=>156),
276
		'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>157),
277
		'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>160),
278
		'fk_user_modif' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>165),
279
		'note_public' =>array('type'=>'text', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>170),
280
		'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>175),
281
		'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>180),
282
		'extraparams' =>array('type'=>'varchar(255)', 'label'=>'Extraparams', 'enabled'=>1, 'visible'=>-1, 'position'=>185),
283
		'fk_accountancy_journal' =>array('type'=>'integer', 'label'=>'Fk accountancy journal', 'enabled'=>1, 'visible'=>-1, 'position'=>190),
284
	);
285
	// END MODULEBUILDER PROPERTIES
286
287
	/**
288
	 * Current account
289
	 */
290
	const TYPE_CURRENT = 1;
291
	/**
292
	 * Cash account
293
	 */
294
	const TYPE_CASH = 2;
295
	/**
296
	 * Savings account
297
	 */
298
	const TYPE_SAVINGS = 0;
299
300
	const STATUS_OPEN = 0;
301
	const STATUS_CLOSED = 1;
302
303
	/**
304
	 *  Constructor
305
	 *
306
	 *  @param	DoliDB		$db		Database handler
307
	 */
308
    public function __construct(DoliDB $db)
309
	{
310
		global $langs;
311
312
		$this->db = $db;
313
314
		$this->solde = 0;
315
316
		$this->type_lib = array(
317
			self::TYPE_SAVINGS => $langs->trans("BankType0"),
318
			self::TYPE_CURRENT => $langs->trans("BankType1"),
319
			self::TYPE_CASH => $langs->trans("BankType2"),
320
		);
321
322
		$this->status = array(
323
			self::STATUS_OPEN => $langs->trans("StatusAccountOpened"),
324
			self::STATUS_CLOSED => $langs->trans("StatusAccountClosed")
325
		);
326
	}
327
328
	/**
329
	 * Shows the account number in the appropriate format
330
	 *
331
	 * @return string
332
	 */
333
	public function __toString()
334
	{
335
		$string = '';
336
		foreach ($this->getFieldsToShow() as $val) {
337
			if ($val == 'BankCode') {
338
				$string .= $this->code_banque.' ';
339
			} elseif ($val == 'BankAccountNumber') {
340
				$string .= $this->number.' ';
341
			} elseif ($val == 'DeskCode') {
342
				$string .= $this->code_guichet.' ';
343
			} elseif ($val == 'BankAccountNumberKey') {
344
				$string .= $this->cle_rib.' ';
345
			} elseif ($val == 'BIC') {
346
				$string .= $this->bic.' ';
347
			} elseif ($val == 'IBAN') {
348
				$string .= $this->iban.' ';
349
			}
350
		}
351
352
		return trim($string);
353
	}
354
355
356
	/**
357
	 *  Return if a bank account need to be conciliated
358
	 *
359
	 *  @return     int         1 if need to be concialiated, < 0 otherwise.
360
	 */
361
    public function canBeConciliated()
362
	{
363
		global $conf;
364
365
		if (empty($this->rappro)) return -1;
366
		if ($this->courant == Account::TYPE_CASH && empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) return -2;
367
		if ($this->clos) return -3;
368
		return 1;
369
	}
370
371
372
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
373
	/**
374
	 *      Add a link between bank line record and its source
375
	 *
376
	 *      @param	int		$line_id    Id ecriture bancaire
377
	 *      @param  int		$url_id     Id parametre url
378
	 *      @param  string	$url        Url
379
	 *      @param  string	$label      Link label
380
	 *      @param  string	$type       Type of link ('payment', 'company', 'member', ...)
381
	 *      @return int         		<0 if KO, id line if OK
382
	 */
383
    public function add_url_line($line_id, $url_id, $url, $label, $type)
384
	{
385
        // phpcs:enable
386
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_url (";
387
		$sql .= "fk_bank";
388
		$sql .= ", url_id";
389
		$sql .= ", url";
390
		$sql .= ", label";
391
		$sql .= ", type";
392
		$sql .= ") VALUES (";
393
		$sql .= "'".$line_id."'";
394
		$sql .= ", '".$url_id."'";
395
		$sql .= ", '".$url."'";
396
		$sql .= ", '".$this->db->escape($label)."'";
397
		$sql .= ", '".$type."'";
398
		$sql .= ")";
399
400
		dol_syslog(get_class($this)."::add_url_line", LOG_DEBUG);
401
		if ($this->db->query($sql))
402
		{
403
			$rowid = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_url");
404
			return $rowid;
405
		} else {
406
			$this->error = $this->db->lasterror();
407
			return -1;
408
		}
409
	}
410
411
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
412
	/**
413
	 * 		TODO Move this into AccountLine
414
	 *      Return array with links from llx_bank_url
415
	 *
416
	 *      @param  int         $fk_bank    To search using bank transaction id
417
	 *      @param  int         $url_id     To search using link to
418
	 *      @param  string      $type       To search using type
419
	 *      @return array|int               Array of links array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> ) or -1 on error
420
	 */
421
    public function get_url($fk_bank = '', $url_id = '', $type = '')
422
	{
423
        // phpcs:enable
424
		$lines = array();
425
426
		// Check parameters
427
		if (!empty($fk_bank) && (!empty($url_id) || !empty($type)))
428
		{
429
			$this->error = "ErrorBadParameter";
430
			return -1;
431
		}
432
433
		$sql = "SELECT fk_bank, url_id, url, label, type";
434
		$sql .= " FROM ".MAIN_DB_PREFIX."bank_url";
435
		if ($fk_bank > 0) {
436
			$sql .= " WHERE fk_bank = ".$fk_bank;
437
		} else { $sql .= " WHERE url_id = ".$url_id." AND type = '".$type."'";
438
		}
439
		$sql .= " ORDER BY type, label";
440
441
		dol_syslog(get_class($this)."::get_url", LOG_DEBUG);
442
		$result = $this->db->query($sql);
443
		if ($result)
444
		{
445
			$i = 0;
446
			$num = $this->db->num_rows($result);
447
			while ($i < $num)
448
			{
449
				$obj = $this->db->fetch_object($result);
450
				// Anciens liens (pour compatibilite)
451
				$lines[$i][0] = $obj->url;
452
				$lines[$i][1] = $obj->url_id;
453
				$lines[$i][2] = $obj->label;
454
				$lines[$i][3] = $obj->type;
455
				// Nouveaux liens
456
				$lines[$i]['url'] = $obj->url;
457
				$lines[$i]['url_id'] = $obj->url_id;
458
				$lines[$i]['label'] = $obj->label;
459
				$lines[$i]['type'] = $obj->type;
460
				$lines[$i]['fk_bank'] = $obj->fk_bank;
461
				$i++;
462
			}
463
		} else dol_print_error($this->db);
464
465
		return $lines;
466
	}
467
468
	/**
469
	 *  Add an entry into table ".MAIN_DB_PREFIX."bank
470
	 *
471
	 *  @param	int	        $date			Date operation
472
	 *  @param	string		$oper			'VIR','PRE','LIQ','VAD','CB','CHQ'...
473
	 *  @param	string		$label			Descripton
474
	 *  @param	float		$amount			Amount
475
	 *  @param	string		$num_chq		Numero cheque ou virement
476
	 *  @param	int  		$categorie		Category id (optionnal)
477
	 *  @param	User		$user			User that create
478
	 *  @param	string		$emetteur		Name of cheque writer
479
	 *  @param	string		$banque			Bank of cheque writer
480
	 *  @param	string		$accountancycode	When we record a free bank entry, we must provide accounting account if accountancy module is on.
481
	 *  @param	int			$datev			Date value
482
	 *  @return	int							Rowid of added entry, <0 if KO
483
	 */
484
    public function addline($date, $oper, $label, $amount, $num_chq, $categorie, User $user, $emetteur = '', $banque = '', $accountancycode = '', $datev = null)
485
	{
486
		// Deprecation warning
487
		if (is_numeric($oper)) {
488
			dol_syslog(__METHOD__.": using numeric operations is deprecated", LOG_WARNING);
489
		}
490
491
		// Clean parameters
492
		$emetteur = trim($emetteur);
493
		$banque = trim($banque);
494
495
		$now = dol_now();
496
497
		if (is_numeric($oper))    // Clean operation to have a code instead of a rowid
498
		{
499
			$sql = "SELECT code FROM ".MAIN_DB_PREFIX."c_paiement";
500
			$sql .= " WHERE id=".$oper;
501
			$sql .= " AND entity IN (".getEntity('c_paiement').")";
502
			$resql = $this->db->query($sql);
503
			if ($resql)
504
			{
505
				$obj = $this->db->fetch_object($resql);
506
				$oper = $obj->code;
507
			} else {
508
				dol_print_error($this->db, 'Failed to get payment type code');
509
				return -1;
510
			}
511
		}
512
513
		// Check parameters
514
		if (!$oper)
515
		{
516
			$this->error = "oper not defined";
517
			return -1;
518
		}
519
		if (!$this->rowid)
1 ignored issue
show
Deprecated Code introduced by
The property Account::$rowid has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

519
		if (!/** @scrutinizer ignore-deprecated */ $this->rowid)
Loading history...
520
		{
521
			$this->error = "this->rowid not defined";
522
			return -2;
523
		}
524
		if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ')
525
		{
526
			$this->error = "ErrorCashAccountAcceptsOnlyCashMoney";
527
			return -3;
528
		}
529
530
		$this->db->begin();
531
532
		if (is_null($datev) || empty($datev)) $datev = $date;
533
534
		$accline = new AccountLine($this->db);
535
		$accline->datec = $now;
536
		$accline->dateo = $date;
537
		$accline->datev = $datev;
538
		$accline->label = $label;
539
		$accline->amount = $amount;
540
		$accline->fk_user_author = $user->id;
541
		$accline->fk_account = $this->rowid;
1 ignored issue
show
Deprecated Code introduced by
The property Account::$rowid has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

541
		$accline->fk_account = /** @scrutinizer ignore-deprecated */ $this->rowid;
Loading history...
542
		$accline->fk_type = $oper;
543
		$accline->numero_compte = $accountancycode;
0 ignored issues
show
Bug introduced by
The property numero_compte does not seem to exist on AccountLine.
Loading history...
544
545
		if ($num_chq) {
546
			$accline->num_chq = $num_chq;
547
		}
548
549
		if ($emetteur) {
550
			$accline->emetteur = $emetteur;
551
		}
552
553
		if ($banque) {
554
			$accline->bank_chq = $banque;
555
		}
556
557
		if ($accline->insert() > 0) {
558
			if ($categorie > 0) {
559
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class (";
560
				$sql .= "lineid, fk_categ";
561
				$sql .= ") VALUES (";
562
				$sql .= $accline->id.", ".$categorie;
563
				$sql .= ")";
564
565
				$result = $this->db->query($sql);
566
				if (!$result) {
567
					$this->error = $this->db->lasterror();
568
					$this->db->rollback();
569
					return -3;
570
				}
571
			}
572
573
			$this->db->commit();
574
			return $accline->id;
575
		} else {
576
			$this->error = $this->db->lasterror();
577
			$this->db->rollback();
578
			return -2;
579
		}
580
	}
581
582
	/**
583
	 *  Create bank account into database
584
	 *
585
	 *  @param	User	$user		Object user making creation
586
	 *  @param  int     $notrigger  1=Disable triggers
587
	 *  @return int        			< 0 if KO, > 0 if OK
588
	 */
589
    public function create(User $user, $notrigger = 0)
590
	{
591
		global $langs, $conf, $hookmanager;
592
593
		$error = 0;
594
595
		// Clean parameters
596
		if (!$this->min_allowed) $this->min_allowed = 0;
597
		if (!$this->min_desired) $this->min_desired = 0;
598
		$this->state_id = ($this->state_id ? $this->state_id : $this->state_id);
599
		$this->country_id = ($this->country_id ? $this->country_id : $this->country_id);
600
601
		// Check parameters
602
		if (empty($this->country_id))
603
		{
604
			$this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country"));
605
			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
606
			return -1;
607
		}
608
		if (empty($this->ref))
609
		{
610
			$this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
611
			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
612
			return -1;
613
		}
614
		if (empty($this->date_solde))
615
		{
616
			$this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("DateInitialBalance"));
617
			dol_syslog(get_class($this)."::create ".$this->error, LOG_ERR);
618
			return -1;
619
		}
620
621
		// Chargement librairie pour acces fonction controle RIB
622
		require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
623
624
		$now = dol_now();
625
626
		$this->db->begin();
627
628
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_account (";
629
		$sql .= "datec";
630
		$sql .= ", ref";
631
		$sql .= ", label";
632
		$sql .= ", entity";
633
		$sql .= ", account_number";
634
		$sql .= ", fk_accountancy_journal";
635
		$sql .= ", bank";
636
		$sql .= ", code_banque";
637
		$sql .= ", code_guichet";
638
		$sql .= ", number";
639
		$sql .= ", cle_rib";
640
		$sql .= ", bic";
641
		$sql .= ", iban_prefix";
642
		$sql .= ", domiciliation";
643
		$sql .= ", proprio";
644
		$sql .= ", owner_address";
645
		$sql .= ", currency_code";
646
		$sql .= ", rappro";
647
		$sql .= ", min_allowed";
648
		$sql .= ", min_desired";
649
		$sql .= ", comment";
650
		$sql .= ", state_id";
651
		$sql .= ", fk_pays";
652
		$sql .= ") VALUES (";
653
		$sql .= "'".$this->db->idate($now)."'";
654
		$sql .= ", '".$this->db->escape($this->ref)."'";
655
		$sql .= ", '".$this->db->escape($this->label)."'";
656
		$sql .= ", ".$conf->entity;
657
		$sql .= ", '".$this->db->escape($this->account_number)."'";
658
		$sql .= ", ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null");
659
		$sql .= ", '".$this->db->escape($this->bank)."'";
660
		$sql .= ", '".$this->db->escape($this->code_banque)."'";
661
		$sql .= ", '".$this->db->escape($this->code_guichet)."'";
662
		$sql .= ", '".$this->db->escape($this->number)."'";
663
		$sql .= ", '".$this->db->escape($this->cle_rib)."'";
664
		$sql .= ", '".$this->db->escape($this->bic)."'";
665
		$sql .= ", '".$this->db->escape($this->iban)."'";
666
		$sql .= ", '".$this->db->escape($this->domiciliation)."'";
667
		$sql .= ", '".$this->db->escape($this->proprio)."'";
668
		$sql .= ", '".$this->db->escape($this->owner_address)."'";
669
		$sql .= ", '".$this->db->escape($this->currency_code)."'";
670
		$sql .= ", ".$this->rappro;
671
		$sql .= ", ".price2num($this->min_allowed);
672
		$sql .= ", ".price2num($this->min_desired);
673
		$sql .= ", '".$this->db->escape($this->comment)."'";
674
		$sql .= ", ".($this->state_id > 0 ? $this->state_id : "null");
675
		$sql .= ", ".$this->country_id;
676
		$sql .= ")";
677
678
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
679
		$resql = $this->db->query($sql);
680
		if ($resql)
681
		{
682
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."bank_account");
683
684
			$result = $this->update($user, 1);
685
			if ($result > 0)
686
			{
687
				$accline = new AccountLine($this->db);
688
				$accline->datec = $this->db->idate($now);
689
				$accline->label = '('.$langs->trans("InitialBankBalance").')';
690
				$accline->amount = price2num($this->solde);
691
				$accline->fk_user_author = $user->id;
692
				$accline->fk_account = $this->id;
693
				$accline->datev = $this->db->idate($this->date_solde);
694
				$accline->dateo = $this->db->idate($this->date_solde);
695
				$accline->fk_type = 'SOLD';
696
697
				if ($accline->insert() < 0) {
698
					$error++;
699
					$this->error = $accline->error;
700
					$this->errors = $accline->errors;
701
				}
702
703
				if (!$error)
704
				{
705
					$result = $this->insertExtraFields();
706
					if ($result < 0) $error++;
707
				}
708
709
				if (!$error && !$notrigger)
710
				{
711
					// Call trigger
712
					$result = $this->call_trigger('BANKACCOUNT_CREATE', $user);
713
					if ($result < 0) $error++;
714
					// End call triggers
715
				}
716
			} else {
717
				$error++;
718
			}
719
		} else {
720
			if ($this->db->errno() == 'DB_ERROR_RECORD_ALREADY_EXISTS')
721
			{
722
				$this->error = $langs->trans("ErrorBankLabelAlreadyExists");
723
				$error++;
724
			} else {
725
				$this->error = $this->db->error()." sql=".$sql;
726
				$error++;
727
			}
728
		}
729
730
		if (!$error)
731
		{
732
			$this->db->commit();
733
			return $this->id;
734
		} else {
735
			$this->db->rollback();
736
			return -1 * $error;
737
		}
738
	}
739
740
	/**
741
	 *    	Update bank account card
742
	 *
743
	 *    	@param	User	$user       Object user making action
744
	 *      @param  int     $notrigger  1=Disable triggers
745
	 *		@return	int					<0 if KO, >0 if OK
746
	 */
747
    public function update(User $user, $notrigger = 0)
748
	{
749
		global $langs, $conf, $hookmanager;
750
751
		$error = 0;
752
753
		$this->db->begin();
754
755
		// Clean parameters
756
		$this->state_id = ($this->state_id ? $this->state_id : $this->state_id);
757
		$this->country_id = ($this->country_id ? $this->country_id : $this->country_id);
758
759
		// Check parameters
760
		if (empty($this->country_id))
761
		{
762
			$this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Country"));
763
			dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
764
			return -1;
765
		}
766
		if (empty($this->ref))
767
		{
768
			$this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
769
			dol_syslog(get_class($this)."::update ".$this->error, LOG_ERR);
770
			return -1;
771
		}
772
		if (!$this->label) $this->label = "???";
773
774
		$sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET ";
775
776
		$sql .= " ref   = '".$this->db->escape($this->ref)."'";
777
		$sql .= ",label = '".$this->db->escape($this->label)."'";
778
779
		$sql .= ",courant = ".$this->courant;
780
		$sql .= ",clos = ".$this->clos;
781
		$sql .= ",rappro = ".$this->rappro;
782
		$sql .= ",url = ".($this->url ? "'".$this->db->escape($this->url)."'" : "null");
783
		$sql .= ",account_number = '".$this->db->escape($this->account_number)."'";
784
		$sql .= ",fk_accountancy_journal = ".($this->fk_accountancy_journal > 0 ? $this->db->escape($this->fk_accountancy_journal) : "null");
785
		$sql .= ",bank  = '".$this->db->escape($this->bank)."'";
786
		$sql .= ",code_banque='".$this->db->escape($this->code_banque)."'";
787
		$sql .= ",code_guichet='".$this->db->escape($this->code_guichet)."'";
788
		$sql .= ",number='".$this->db->escape($this->number)."'";
789
		$sql .= ",cle_rib='".$this->db->escape($this->cle_rib)."'";
790
		$sql .= ",bic='".$this->db->escape($this->bic)."'";
791
		$sql .= ",iban_prefix = '".$this->db->escape($this->iban)."'";
792
		$sql .= ",domiciliation='".$this->db->escape($this->domiciliation)."'";
793
		$sql .= ",proprio = '".$this->db->escape($this->proprio)."'";
794
		$sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'";
795
796
		$sql .= ",currency_code = '".$this->db->escape($this->currency_code)."'";
797
798
		$sql .= ",min_allowed = ".($this->min_allowed != '' ? price2num($this->min_allowed) : "null");
799
		$sql .= ",min_desired = ".($this->min_desired != '' ? price2num($this->min_desired) : "null");
800
		$sql .= ",comment     = '".$this->db->escape($this->comment)."'";
801
802
		$sql .= ",state_id = ".($this->state_id > 0 ? $this->state_id : "null");
803
		$sql .= ",fk_pays = ".$this->country_id;
804
805
		$sql .= " WHERE rowid = ".$this->id;
806
807
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
808
		$result = $this->db->query($sql);
809
		if ($result)
810
		{
811
			// Actions on extra fields (by external module or standard code)
812
			if (!$error)
813
			{
814
				$result = $this->insertExtraFields();
815
				if ($result < 0) $error++;
816
			}
817
818
			if (!$error && !$notrigger)
819
			{
820
				// Call trigger
821
				$result = $this->call_trigger('BANKACCOUNT_UPDATE', $user);
822
				if ($result < 0) $error++;
823
				// End call triggers
824
			}
825
		} else {
826
			$error++;
827
			$this->error = $this->db->lasterror();
828
			dol_print_error($this->db);
829
		}
830
831
		if (!$error)
832
		{
833
			$this->db->commit();
834
			return $this->id;
835
		} else {
836
			$this->db->rollback();
837
			return -1 * $error;
838
		}
839
	}
840
841
842
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
843
	/**
844
	 *  Update BBAN (RIB) account fields
845
	 *
846
	 *  @param	User	$user       Object user making update
847
	 *	@return	int					<0 if KO, >0 if OK
848
	 */
849
    public function update_bban(User $user = null)
850
	{
851
        // phpcs:enable
852
		global $conf, $langs;
853
854
		// Clean parameters
855
		$this->state_id = ($this->state_id ? $this->state_id : $this->state_id);
856
		$this->country_id = ($this->country_id ? $this->country_id : $this->country_id);
857
858
		// Chargement librairie pour acces fonction controle RIB
859
		require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
860
861
		dol_syslog(get_class($this)."::update_bban $this->code_banque,$this->code_guichet,$this->number,$this->cle_rib,$this->iban");
862
863
		// Check parameters
864
		if (!$this->ref)
865
		{
866
			$this->error = $langs->transnoentitiesnoconv("ErrorFieldRequired", $langs->trans("Ref"));
867
			return -2;
868
		}
869
870
		$sql = "UPDATE ".MAIN_DB_PREFIX."bank_account SET ";
871
		$sql .= " bank  = '".$this->db->escape($this->bank)."'";
872
		$sql .= ",code_banque='".$this->db->escape($this->code_banque)."'";
873
		$sql .= ",code_guichet='".$this->db->escape($this->code_guichet)."'";
874
		$sql .= ",number='".$this->db->escape($this->number)."'";
875
		$sql .= ",cle_rib='".$this->db->escape($this->cle_rib)."'";
876
		$sql .= ",bic='".$this->db->escape($this->bic)."'";
877
		$sql .= ",iban_prefix = '".$this->db->escape($this->iban)."'";
878
		$sql .= ",domiciliation='".$this->db->escape($this->domiciliation)."'";
879
		$sql .= ",proprio = '".$this->db->escape($this->proprio)."'";
880
		$sql .= ",owner_address = '".$this->db->escape($this->owner_address)."'";
881
		$sql .= ",state_id = ".($this->state_id > 0 ? $this->state_id : "null");
882
		$sql .= ",fk_pays = ".$this->country_id;
883
		$sql .= " WHERE rowid = ".$this->id;
884
		$sql .= " AND entity = ".$conf->entity;
885
886
		dol_syslog(get_class($this)."::update_bban", LOG_DEBUG);
887
888
		$result = $this->db->query($sql);
889
		if ($result)
890
		{
891
			return 1;
892
		} else {
893
			$this->error = $this->db->lasterror();
894
			dol_print_error($this->db);
895
			return -1;
896
		}
897
	}
898
899
900
	/**
901
	 *      Load a bank account into memory from database
902
	 *
903
	 *      @param	int		$id      	Id of bank account to get
904
	 *      @param  string	$ref     	Ref of bank account to get
905
	 *      @return	int					<0 if KO, >0 if OK
906
	 */
907
    public function fetch($id, $ref = '')
908
	{
909
		global $conf;
910
911
		if (empty($id) && empty($ref))
912
		{
913
			$this->error = "ErrorBadParameters";
914
			return -1;
915
		}
916
917
		$sql = "SELECT ba.rowid, ba.ref, ba.label, ba.bank, ba.number, ba.courant, ba.clos, ba.rappro, ba.url,";
918
		$sql .= " ba.code_banque, ba.code_guichet, ba.cle_rib, ba.bic, ba.iban_prefix as iban,";
919
		$sql .= " ba.domiciliation, ba.proprio, ba.owner_address, ba.state_id, ba.fk_pays as country_id,";
920
		$sql .= " ba.account_number, ba.fk_accountancy_journal, ba.currency_code,";
921
		$sql .= " ba.min_allowed, ba.min_desired, ba.comment,";
922
		$sql .= " ba.datec as date_creation, ba.tms as date_update,";
923
		$sql .= ' c.code as country_code, c.label as country,';
924
		$sql .= ' d.code_departement as state_code, d.nom as state';
925
        $sql .= ' , aj.code as accountancy_journal';
926
		$sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
927
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_country as c ON ba.fk_pays = c.rowid';
928
		$sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'c_departements as d ON ba.state_id = d.rowid';
929
        $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'accounting_journal as aj ON aj.rowid=ba.fk_accountancy_journal';
930
		$sql .= " WHERE ba.entity IN (".getEntity($this->element).")";
931
		if ($id)  $sql .= " AND ba.rowid  = ".$id;
932
		if ($ref) $sql .= " AND ba.ref = '".$this->db->escape($ref)."'";
933
934
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
935
		$result = $this->db->query($sql);
936
		if ($result)
937
		{
938
			if ($this->db->num_rows($result))
939
			{
940
				$obj = $this->db->fetch_object($result);
941
942
				$this->id            = $obj->rowid;
943
				$this->rowid         = $obj->rowid;
944
				$this->ref           = $obj->ref;
945
				$this->label         = $obj->label;
946
				$this->type          = $obj->courant;
947
				$this->courant       = $obj->courant;
948
				$this->bank          = $obj->bank;
949
				$this->clos          = $obj->clos;
950
				$this->rappro        = $obj->rappro;
951
				$this->url           = $obj->url;
952
953
				$this->code_banque   = $obj->code_banque;
954
				$this->code_guichet  = $obj->code_guichet;
955
				$this->number        = $obj->number;
956
				$this->cle_rib       = $obj->cle_rib;
957
				$this->bic           = $obj->bic;
958
				$this->iban          = $obj->iban;
959
				$this->domiciliation = $obj->domiciliation;
960
				$this->proprio       = $obj->proprio;
961
				$this->owner_address = $obj->owner_address;
962
963
				$this->state_id        = $obj->state_id;
964
				$this->state_code      = $obj->state_code;
965
				$this->state           = $obj->state;
966
967
				$this->country_id    = $obj->country_id;
968
				$this->country_code  = $obj->country_code;
969
				$this->country       = $obj->country;
970
971
				$this->account_number = $obj->account_number;
972
				$this->fk_accountancy_journal = $obj->fk_accountancy_journal;
973
				$this->accountancy_journal = $obj->accountancy_journal;
974
975
				$this->currency_code  = $obj->currency_code;
976
				$this->account_currency_code = $obj->currency_code;
977
				$this->min_allowed    = $obj->min_allowed;
978
				$this->min_desired    = $obj->min_desired;
979
				$this->comment        = $obj->comment;
980
981
				$this->date_creation  = $this->db->jdate($obj->date_creation);
982
				$this->date_update    = $this->db->jdate($obj->date_update);
983
984
				// Retreive all extrafield
985
				// fetch optionals attributes and labels
986
				$this->fetch_optionals();
987
988
				return 1;
989
			} else {
990
				return 0;
991
			}
992
		} else {
993
			$this->error = $this->db->lasterror;
994
			$this->errors[] = $this->error;
995
			return -1;
996
		}
997
	}
998
999
	/**
1000
	 * Sets object to supplied categories.
1001
	 *
1002
	 * Deletes object from existing categories not supplied.
1003
	 * Adds it to non existing supplied categories.
1004
	 * Existing categories are left untouch.
1005
	 *
1006
	 * @param int[]|int $categories Category or categories IDs
1007
     * @return void
1008
	 */
1009
    public function setCategories($categories)
1010
    {
1011
		// Handle single category
1012
		if (!is_array($categories)) {
1013
			$categories = array($categories);
1014
		}
1015
1016
		// Get current categories
1017
		require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1018
		$c = new Categorie($this->db);
1019
		$existing = $c->containing($this->id, Categorie::TYPE_ACCOUNT, 'id');
1020
1021
		// Diff
1022
		if (is_array($existing)) {
0 ignored issues
show
introduced by
The condition is_array($existing) is always false.
Loading history...
1023
			$to_del = array_diff($existing, $categories);
1024
			$to_add = array_diff($categories, $existing);
1025
		} else {
1026
			$to_del = array(); // Nothing to delete
1027
			$to_add = $categories;
1028
		}
1029
1030
		// Process
1031
		foreach ($to_del as $del) {
1032
			if ($c->fetch($del) > 0) {
1033
				$c->del_type($this, Categorie::TYPE_ACCOUNT);
1034
			}
1035
		}
1036
		foreach ($to_add as $add) {
1037
			if ($c->fetch($add) > 0) {
1038
				$c->add_type($this, Categorie::TYPE_ACCOUNT);
1039
			}
1040
		}
1041
1042
		return;
1043
	}
1044
1045
	/**
1046
	 *  Delete bank account from database
1047
	 *
1048
	 *	@param	User	$user	User deleting
1049
	 *  @return int             <0 if KO, >0 if OK
1050
	 */
1051
    public function delete(User $user = null)
1052
	{
1053
		global $conf;
1054
1055
		$error = 0;
1056
1057
		$this->db->begin();
1058
1059
		// Delete link between tag and bank account
1060
		if (!$error)
1061
		{
1062
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_account";
1063
			$sql .= " WHERE fk_account = ".$this->id;
1064
1065
			$resql = $this->db->query($sql);
1066
			if (!$resql)
1067
			{
1068
				$error++;
1069
				$this->error = "Error ".$this->db->lasterror();
1070
			}
1071
		}
1072
1073
		if (!$error)
1074
		{
1075
			$sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_account";
1076
			$sql .= " WHERE rowid = ".$this->rowid;
1 ignored issue
show
Deprecated Code introduced by
The property Account::$rowid has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

1076
			$sql .= " WHERE rowid = "./** @scrutinizer ignore-deprecated */ $this->rowid;
Loading history...
1077
1078
			dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1079
			$result = $this->db->query($sql);
1080
			if ($result)
1081
			{
1082
				// Remove extrafields
1083
				if (!$error)
1084
				{
1085
					$result = $this->deleteExtraFields();
1086
					if ($result < 0)
1087
					{
1088
						$error++;
1089
						dol_syslog(get_class($this)."::delete error -4 ".$this->error, LOG_ERR);
1090
					}
1091
				}
1092
			} else {
1093
				$error++;
1094
				$this->error = "Error ".$this->db->lasterror();
1095
			}
1096
		}
1097
1098
		if (!$error)
1099
		{
1100
			$this->db->commit();
1101
			return 1;
1102
		} else {
1103
			$this->db->rollback();
1104
			return -1;
1105
		}
1106
	}
1107
1108
1109
	/**
1110
	 *  Return label of object status
1111
	 *
1112
	 *  @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
1113
	 *  @return     string        		    Label
1114
	 */
1115
    public function getLibStatut($mode = 0)
1116
	{
1117
		return $this->LibStatut($this->clos, $mode);
1118
	}
1119
1120
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1121
	/**
1122
	 *  Return label of given object status
1123
	 *
1124
	 *  @param	 int		$status        	Id status
1125
	 *  @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
1126
	 *  @return  string        			    Label
1127
	 */
1128
    public function LibStatut($status, $mode = 0)
1129
	{
1130
        // phpcs:enable
1131
		global $langs;
1132
		$langs->load('banks');
1133
1134
		if ($status == self::STATUS_OPEN) {
1135
			$label = $langs->trans("StatusAccountOpened");
1136
			$labelshort = $langs->trans("StatusAccountOpened");
1137
			$statusType = 'status4';
1138
		} else {
1139
			$label = $langs->trans("StatusAccountClosed");
1140
			$labelshort = $langs->trans("StatusAccountClosed");
1141
			$statusType = 'status5';
1142
		}
1143
1144
		return dolGetStatus($label, $labelshort, '', $statusType, $mode);
1145
	}
1146
1147
1148
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1149
	/**
1150
	 *    Renvoi si un compte peut etre supprimer ou non (sans mouvements)
1151
	 *
1152
	 *    @return     boolean     vrai si peut etre supprime, faux sinon
1153
	 */
1154
    public function can_be_deleted()
1155
	{
1156
        // phpcs:enable
1157
		$can_be_deleted = false;
1158
1159
		$sql = "SELECT COUNT(rowid) as nb";
1160
		$sql .= " FROM ".MAIN_DB_PREFIX."bank";
1161
		$sql .= " WHERE fk_account=".$this->id;
1162
1163
		$resql = $this->db->query($sql);
1164
		if ($resql) {
1165
			$obj = $this->db->fetch_object($resql);
1166
			if ($obj->nb <= 1) $can_be_deleted = true; // Juste le solde
1167
		} else {
1168
			dol_print_error($this->db);
1169
		}
1170
		return $can_be_deleted;
1171
	}
1172
1173
1174
	/**
1175
	 *   Return error
1176
	 *
1177
	 *   @return	string		Error string
1178
	 */
1179
    public function error()
1180
	{
1181
		return $this->error;
1182
	}
1183
1184
	/**
1185
	 * 	Return current sold
1186
	 *
1187
	 * 	@param	int		$option		1=Exclude future operation date (this is to exclude input made in advance and have real account sold)
1188
	 *	@return	int					Current sold (value date <= today)
1189
	 */
1190
    public function solde($option = 0)
1191
	{
1192
		$solde = 0;
1193
1194
		$sql = "SELECT sum(amount) as amount";
1195
		$sql .= " FROM ".MAIN_DB_PREFIX."bank";
1196
		$sql .= " WHERE fk_account = ".$this->id;
1197
		if ($option == 1) $sql .= " AND dateo <= '".$this->db->idate(dol_now())."'";
1198
1199
		$resql = $this->db->query($sql);
1200
		if ($resql)
1201
		{
1202
			if ($this->db->num_rows($resql))
1203
			{
1204
				$obj = $this->db->fetch_object($resql);
1205
				$solde = $obj->amount;
1206
			}
1207
			$this->db->free($resql);
1208
		} else {
1209
			$this->errors[] = $this->db->lasterror;
1210
			return -1;
1211
		}
1212
1213
		return price2num($solde, 'MU');
1214
	}
1215
1216
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1217
	/**
1218
	 *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1219
	 *
1220
	 *      @param	User	$user        		Objet user
1221
	 *		@param	int		$filteraccountid	To get info for a particular account id
1222
	 *      @return WorkboardResponse|int 		<0 if KO, WorkboardResponse if OK
1223
	 */
1224
    public function load_board(User $user, $filteraccountid = 0)
1225
	{
1226
        // phpcs:enable
1227
		global $conf, $langs;
1228
1229
		if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
1230
1231
		$sql = "SELECT b.rowid, b.datev as datefin";
1232
		$sql .= " FROM ".MAIN_DB_PREFIX."bank as b,";
1233
		$sql .= " ".MAIN_DB_PREFIX."bank_account as ba";
1234
		$sql .= " WHERE b.rappro=0";
1235
		$sql .= " AND b.fk_account = ba.rowid";
1236
		$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
1237
		$sql .= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable
1238
		$sql .= " AND clos = 0";
1239
		if ($filteraccountid) $sql .= " AND ba.rowid = ".$filteraccountid;
1240
1241
		$resql = $this->db->query($sql);
1242
		if ($resql)
1243
		{
1244
			$langs->load("banks");
1245
			$now = dol_now();
1246
1247
			require_once DOL_DOCUMENT_ROOT.'/core/class/workboardresponse.class.php';
1248
1249
			$response = new WorkboardResponse();
1250
			$response->warning_delay = $conf->bank->rappro->warning_delay / 60 / 60 / 24;
1251
			$response->label = $langs->trans("TransactionsToConciliate");
1252
			$response->labelShort = $langs->trans("TransactionsToConciliateShort");
1253
			$response->url = DOL_URL_ROOT.'/compta/bank/list.php?leftmenu=bank&amp;mainmenu=bank';
1254
			$response->img = img_object('', "payment");
1255
1256
			while ($obj = $this->db->fetch_object($resql))
1257
			{
1258
				$response->nbtodo++;
1259
				if ($this->db->jdate($obj->datefin) < ($now - $conf->bank->rappro->warning_delay)) {
1260
					$response->nbtodolate++;
1261
				}
1262
			}
1263
1264
			return $response;
1265
		} else {
1266
			dol_print_error($this->db);
1267
			$this->error = $this->db->error();
1268
			return -1;
1269
		}
1270
	}
1271
1272
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1273
	/**
1274
	 *      Charge indicateurs this->nb de tableau de bord
1275
	 *		@param		int			$filteraccountid	To get info for a particular account id
1276
	 *      @return     int         <0 if ko, >0 if ok
1277
	 */
1278
    public function load_state_board($filteraccountid = 0)
1279
	{
1280
        // phpcs:enable
1281
		global $user;
1282
1283
		if ($user->socid) return -1; // protection pour eviter appel par utilisateur externe
1284
1285
		$sql = "SELECT count(b.rowid) as nb";
1286
		$sql .= " FROM ".MAIN_DB_PREFIX."bank as b,";
1287
		$sql .= " ".MAIN_DB_PREFIX."bank_account as ba";
1288
		$sql .= " WHERE b.fk_account = ba.rowid";
1289
		$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
1290
		$sql .= " AND (ba.rappro = 1 AND ba.courant != 2)"; // Compte rapprochable
1291
		$sql .= " AND clos = 0";
1292
		if ($filteraccountid) $sql .= " AND ba.rowid = ".$filteraccountid;
1293
1294
		$resql = $this->db->query($sql);
1295
		if ($resql)
1296
		{
1297
			while ($obj = $this->db->fetch_object($resql))
1298
			{
1299
				$this->nb["banklines"] = $obj->nb;
1300
			}
1301
			$this->db->free($resql);
1302
		} else {
1303
			dol_print_error($this->db);
1304
			$this->error = $this->db->error();
1305
			return -1;
1306
		}
1307
	}
1308
1309
1310
	/**
1311
	 *      Load indicators for dashboard (this->nbtodo and this->nbtodolate)
1312
	 *
1313
	 *      @return int     Nb of account we can reconciliate
1314
	 */
1315
	public static function countAccountToReconcile()
1316
	{
1317
		global $db, $conf, $user;
1318
1319
		//Protection against external users
1320
		if ($user->socid) {
1321
			return 0;
1322
		}
1323
1324
		$nb = 0;
1325
1326
		$sql = "SELECT COUNT(ba.rowid) as nb";
1327
		$sql .= " FROM ".MAIN_DB_PREFIX."bank_account as ba";
1328
		$sql .= " WHERE ba.rappro > 0 and ba.clos = 0";
1329
		$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
1330
		if (empty($conf->global->BANK_CAN_RECONCILIATE_CASHACCOUNT)) $sql .= " AND ba.courant != 2";
1331
		$resql = $db->query($sql);
1332
		if ($resql)
1333
		{
1334
			$obj = $db->fetch_object($resql);
1335
			$nb = $obj->nb;
1336
		} else dol_print_error($db);
1337
1338
		return $nb;
1339
	}
1340
1341
	/**
1342
	 *  Return clicable name (with picto eventually)
1343
	 *
1344
	 *	@param	int		$withpicto					Include picto into link
1345
	 *  @param  string	$mode           			''=Link to card, 'transactions'=Link to transactions card
1346
	 *  @param  string  $option         			''=Show ref, 'reflabel'=Show ref+label
1347
	 *  @param  int     $save_lastsearch_value    	-1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
1348
     *  @param	int  	$notooltip		 			1=Disable tooltip
1349
	 *	@return	string								Chaine avec URL
1350
	 */
1351
    public function getNomUrl($withpicto = 0, $mode = '', $option = '', $save_lastsearch_value = -1, $notooltip = 0)
1352
	{
1353
		global $conf, $langs, $user;
1354
1355
		$result = '';
1356
		$label = '<u>'.$langs->trans("BankAccount").'</u>';
1357
		$label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1358
		$label .= '<br><b>'.$langs->trans('AccountNumber').':</b> '.$this->number;
1359
		$label .= '<br><b>'.$langs->trans('IBAN').':</b> '.$this->iban;
1360
		$label .= '<br><b>'.$langs->trans('BIC').':</b> '.$this->bic;
1361
		$label .= '<br><b>'.$langs->trans("AccountCurrency").':</b> '.$this->currency_code;
1362
1363
		if (empty($user->rights->banque->lire) || !empty($user->socid))
1364
		{
1365
			$option = 'nolink';
1366
		}
1367
1368
		if (!empty($conf->accounting->enabled))
1369
		{
1370
			include_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
1371
			$langs->load("accountancy");
1372
			$label .= '<br><b>'.$langs->trans('AccountAccounting').':</b> '.length_accountg($this->account_number);
1373
			$label .= '<br><b>'.$langs->trans('AccountancyJournal').':</b> '.$this->accountancy_journal;
1374
		}
1375
		if (isset($this->status)) {
1376
			$label .= '<br><b>'.$langs->trans("Status").":</b> ".$this->getLibStatut(5);
1377
		}
1378
1379
		$linkclose = '" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
1380
1381
		$url = DOL_URL_ROOT.'/compta/bank/card.php?id='.$this->id;
1382
		if ($mode == 'transactions')
1383
		{
1384
			$url = DOL_URL_ROOT.'/compta/bank/bankentries_list.php?id='.$this->id;
1385
		} elseif ($mode == 'receipts')
1386
		{
1387
			$url = DOL_URL_ROOT.'/compta/bank/releve.php?account='.$this->id;
1388
		}
1389
1390
		if ($option != 'nolink')
1391
		{
1392
			// Add param to save lastsearch_values or not
1393
			$add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1394
			if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1395
			if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1396
		}
1397
1398
		$linkstart = '<a href="'.$url.$linkclose;
1399
		$linkend = '</a>';
1400
1401
        if ($option == 'nolink') {
1402
            $linkstart = '';
1403
            $linkend = '';
1404
        }
1405
1406
		$result .= $linkstart;
1407
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), $this->picto, ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1408
		if ($withpicto != 2) $result .= $this->ref.($option == 'reflabel' && $this->label ? ' - '.$this->label : '');
1409
		$result .= $linkend;
1410
1411
		return $result;
1412
	}
1413
1414
1415
	// Method after here are common to Account and CompanyBankAccount
1416
1417
1418
	/**
1419
	 *     Return if an account has valid information for Direct debit payment
1420
	 *
1421
	 *     @return     int         1 if correct, <=0 if wrong
1422
	 */
1423
    public function verif()
1424
	{
1425
		require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php';
1426
1427
		$this->error_number = 0;
1428
1429
		// Call function to check BAN
1430
1431
		if (!checkIbanForAccount($this) || !checkSwiftForAccount($this))
1432
		{
1433
			$this->error_number = 12;
1434
			$this->error_message = 'IBANSWIFTControlError';
1435
		}
1436
		/*if (! checkBanForAccount($this))
1437
        {
1438
            $this->error_number = 12;
1439
            $this->error_message = 'BANControlError';
1440
        }*/
1441
1442
		if ($this->error_number == 0)
1443
		{
1444
			return 1;
1445
		} else {
1446
			return 0;
1447
		}
1448
	}
1449
1450
	/**
1451
	 * 	Return account country code
1452
	 *
1453
	 *	@return		string		country code
1454
	 */
1455
    public function getCountryCode()
1456
	{
1457
		global $mysoc;
1458
1459
		// We return country code of bank account
1460
		if (!empty($this->country_code)) return $this->country_code;
1461
1462
		// For backward compatibility, we try to guess country from other information
1463
		if (!empty($this->iban))
1464
		{
1465
			// If IBAN defined, we can know country of account from it
1466
			$reg = array();
1467
			if (preg_match("/^([a-zA-Z][a-zA-Z])/i", $this->iban, $reg)) return $reg[1];
1468
		}
1469
1470
		// If this class is linked to a third party
1471
		if (!empty($this->socid))
1472
		{
1473
			require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
1474
			$company = new Societe($this->db);
1475
			$result = $company->fetch($this->socid);
1476
			if (!empty($company->country_code)) return $company->country_code;
1477
		}
1478
1479
		// We return country code of managed company
1480
		if (!empty($mysoc->country_code)) return $mysoc->country_code;
1481
1482
		return '';
1483
	}
1484
1485
	/**
1486
	 * Return if a bank account is defined with detailed information (bank code, desk code, number and key).
1487
	 * More information on codes used by countries on page http://en.wikipedia.org/wiki/Bank_code
1488
	 *
1489
	 * @return		int        0=No bank code need + Account number is enough
1490
	 *                         1=Need 2 fields for bank code: Bank, Desk (France, Spain, ...) + Account number and key
1491
	 *                         2=Need 1 field for bank code:  Bank only (Sort code for Great Britain, BSB for Australia) + Account number
1492
	 */
1493
    public function useDetailedBBAN()
1494
	{
1495
		$country_code = $this->getCountryCode();
1496
1497
		if (in_array($country_code, array('FR', 'ES', 'GA', 'IT', 'NC'))) return 1; // France, Spain, Gabon, ... - Not valid for CH
1498
		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...
1499
		return 0;
1500
	}
1501
1502
	/**
1503
	 * Return 1 if IBAN / BIC is mandatory (otherwise option)
1504
	 *
1505
	 * @return		int        1 = mandatory / 0 = Not mandatory
1506
	 */
1507
    public function needIBAN()
1508
	{
1509
		$country_code = $this->getCountryCode();
1510
1511
		$country_code_in_EEC = array(
1512
				'AT', // Austria
1513
				'BE', // Belgium
1514
				'BG', // Bulgaria
1515
				'CY', // Cyprus
1516
				'CZ', // Czech republic
1517
				'DE', // Germany
1518
				'DK', // Danemark
1519
				'EE', // Estonia
1520
				'ES', // Spain
1521
				'FI', // Finland
1522
				'FR', // France
1523
				'GB', // United Kingdom
1524
				'GR', // Greece
1525
				'HR', // Croatia
1526
				'NL', // Holland
1527
				'HU', // Hungary
1528
				'IE', // Ireland
1529
				'IM', // Isle of Man - Included in UK
1530
				'IT', // Italy
1531
				'LT', // Lithuania
1532
				'LU', // Luxembourg
1533
				'LV', // Latvia
1534
				'MC', // Monaco - Included in France
1535
				'MT', // Malta
1536
				//'NO',	// Norway
1537
				'PL', // Poland
1538
				'PT', // Portugal
1539
				'RO', // Romania
1540
				'SE', // Sweden
1541
				'SK', // Slovakia
1542
				'SI', // Slovenia
1543
				'UK', // United Kingdom
1544
				//'CH',	// Switzerland - No. Swizerland in not in EEC
1545
		);
1546
1547
		if (in_array($country_code, $country_code_in_EEC)) return 1; // France, Spain, ...
1548
		return 0;
1549
	}
1550
1551
	/**
1552
	 *	Load miscellaneous information for tab "Info"
1553
	 *
1554
	 *	@param  int		$id		Id of object to load
1555
	 *	@return	void
1556
	 */
1557
    public function info($id)
1558
	{
1559
	}
1560
1561
	/**
1562
	 * Returns the fields in order that this bank account should show to the user
1563
	 * Will return an array with the following values:
1564
	 * - BankAccountNumber
1565
	 * - BankCode
1566
	 * - BankAccountNumberKey
1567
	 * - DeskCode
1568
	 *
1569
	 * Some countries show less or more bank account properties to the user
1570
	 *
1571
	 * @param  int     $includeibanbic         1=Return also key for IBAN and BIC
1572
	 * @return array                           Array of fields to show
1573
	 * @see useDetailedBBAN()
1574
	 */
1575
	public function getFieldsToShow($includeibanbic = 0)
1576
	{
1577
		//Get the required properties depending on the country
1578
		$detailedBBAN = $this->useDetailedBBAN();
1579
1580
		if ($detailedBBAN == 0) {
1581
			$fieldarray = array(
1582
					'BankAccountNumber'
1583
			);
1584
		} elseif ($detailedBBAN == 2) {
1585
			$fieldarray = array(
1586
					'BankCode',
1587
					'BankAccountNumber'
1588
			);
1589
		} else {
1590
			$fieldarray = self::getAccountNumberOrder();
1591
		}
1592
1593
		//if ($this->needIBAN()) {    // return always IBAN and BIC (this was old behaviour)
1594
		if ($includeibanbic)
1595
		{
1596
			$fieldarray[] = 'IBAN';
1597
			$fieldarray[] = 'BIC';
1598
		}
1599
		//}
1600
1601
		//Get the order the properties are shown
1602
		return $fieldarray;
1603
	}
1604
1605
	/**
1606
	 * Returns the components of the bank account in order.
1607
	 * Will return an array with the following values:
1608
	 * - BankAccountNumber
1609
	 * - BankCode
1610
	 * - BankAccountNumberKey
1611
	 * - DeskCode
1612
	 *
1613
	 * @return array
1614
	 */
1615
	public static function getAccountNumberOrder()
1616
	{
1617
		global $conf;
1618
1619
		$fieldlists = array(
1620
				'BankCode',
1621
				'DeskCode',
1622
				'BankAccountNumber',
1623
				'BankAccountNumberKey'
1624
		);
1625
1626
		if (!empty($conf->global->BANK_SHOW_ORDER_OPTION)) {
1627
			if (is_numeric($conf->global->BANK_SHOW_ORDER_OPTION)) {
1628
				if ($conf->global->BANK_SHOW_ORDER_OPTION == '1') {
1629
					$fieldlists = array(
1630
						'BankCode',
1631
						'DeskCode',
1632
						'BankAccountNumberKey',
1633
						'BankAccountNumber'
1634
					);
1635
				}
1636
			} else {
1637
				//Replace the old AccountNumber key with the new BankAccountNumber key
1638
				$fieldlists = explode(
1639
					' ',
1640
                    preg_replace('/ ?[^Bank]AccountNumber ?/', 'BankAccountNumber', $conf->global->BANK_SHOW_ORDER_OPTION)
1641
				);
1642
			}
1643
		}
1644
1645
		return $fieldlists;
1646
	}
1647
1648
1649
	/**
1650
	 *  Initialise an instance with random values.
1651
	 *  Used to build previews or test instances.
1652
	 *	id must be 0 if object instance is a specimen.
1653
	 *
1654
	 *  @return	void
1655
	 */
1656
    public function initAsSpecimen()
1657
	{
1658
		$this->specimen        = 1;
1659
		$this->ref             = 'MBA';
1660
		$this->label           = 'My Big Company Bank account';
1661
		$this->bank            = 'MyBank';
1662
		$this->courant         = Account::TYPE_CURRENT;
1663
		$this->clos            = Account::STATUS_OPEN;
1664
		$this->code_banque     = '123';
1665
		$this->code_guichet    = '456';
1666
		$this->number          = 'ABC12345';
1667
		$this->cle_rib         = '50';
1668
		$this->bic             = 'AA12';
1669
		$this->iban            = 'FR999999999';
1670
		$this->domiciliation   = 'My bank address';
1671
		$this->proprio         = 'Owner';
1672
		$this->owner_address   = 'Owner address';
1673
		$this->country_id      = 1;
1674
	}
1675
}
1676
1677
1678
/**
1679
 *	Class to manage bank transaction lines
1680
 */
1681
class AccountLine extends CommonObject
1682
{
1683
	/**
1684
	 * @var string Error code (or message)
1685
	 */
1686
	public $error = '';
1687
1688
    /**
1689
     * @var DoliDB Database handler.
1690
     */
1691
    public $db;
1692
1693
	/**
1694
	 * @var string ID to identify managed object
1695
	 */
1696
	public $element = 'bank';
1697
1698
	/**
1699
	 * @var string Name of table without prefix where object is stored
1700
	 */
1701
	public $table_element = 'bank';
1702
1703
	/**
1704
	 * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
1705
	 */
1706
	public $picto = 'generic';
1707
1708
	/**
1709
	 * @var int ID
1710
	 */
1711
	public $id;
1712
1713
    /**
1714
     * @var string Ref
1715
     */
1716
    public $ref;
1717
1718
	/**
1719
     * Date creation record (datec)
1720
     *
1721
     * @var integer
1722
     */
1723
    public $datec;
1724
1725
    /**
1726
     * Date (dateo)
1727
     *
1728
     * @var integer
1729
     */
1730
	public $dateo;
1731
1732
	/**
1733
     * Date value (datev)
1734
     *
1735
     * @var integer
1736
     */
1737
	public $datev;
1738
1739
	public $amount;
1740
1741
    /**
1742
     * @var string bank transaction lines label
1743
     */
1744
    public $label;
1745
1746
    public $note;
1747
1748
    /**
1749
     * @var int ID
1750
     */
1751
	public $fk_user_author;
1752
1753
	/**
1754
     * @var int ID
1755
     */
1756
	public $fk_user_rappro;
1757
1758
	/**
1759
     * @var int ID
1760
     */
1761
	public $fk_type;
1762
1763
	public $rappro; // Is it conciliated
1764
	public $num_releve; // If conciliated, what is bank statement
1765
	public $num_chq; // Num of cheque
1766
	public $bank_chq; // Bank of cheque
1767
1768
	/**
1769
     * @var int ID of cheque receipt
1770
     */
1771
	public $fk_bordereau;
1772
1773
	/**
1774
     * @var int ID of bank account
1775
     */
1776
	public $fk_account;
1777
1778
	/**
1779
	 * @var string		Label of bank account
1780
	 */
1781
	public $bank_account_label;
1782
1783
    /**
1784
	 * @var string		Name of check issuer
1785
	 */
1786
	public $emetteur;
1787
1788
	/**
1789
	 *  Constructor
1790
	 *
1791
	 *  @param	DoliDB	$db		Database handler
1792
	 */
1793
    public function __construct(DoliDB $db)
1794
	{
1795
		$this->db = $db;
1796
	}
1797
1798
	/**
1799
	 *  Load into memory content of a bank transaction line
1800
	 *
1801
	 *  @param		int		$rowid   	Id of bank transaction to load
1802
	 *  @param      string	$ref     	Ref of bank transaction to load
1803
	 *  @param      string	$num     	External num to load (ex: num of transaction for paypal fee)
1804
	 *	@return		int					<0 if KO, 0 if OK but not found, >0 if OK and found
1805
	 */
1806
    public function fetch($rowid, $ref = '', $num = '')
1807
	{
1808
		global $conf;
1809
1810
		// Check parameters
1811
		if (empty($rowid) && empty($ref) && empty($num)) return -1;
1812
1813
		$sql = "SELECT b.rowid, b.datec, b.datev, b.dateo, b.amount, b.label as label, b.fk_account,";
1814
		$sql .= " b.fk_user_author, b.fk_user_rappro,";
1815
		$sql .= " b.fk_type, b.num_releve, b.num_chq, b.rappro, b.note,";
1816
		$sql .= " b.fk_bordereau, b.banque, b.emetteur,";
1817
		//$sql.= " b.author"; // Is this used ?
1818
		$sql .= " ba.ref as bank_account_ref, ba.label as bank_account_label";
1819
		$sql .= " FROM ".MAIN_DB_PREFIX."bank as b,";
1820
		$sql .= " ".MAIN_DB_PREFIX."bank_account as ba";
1821
		$sql .= " WHERE b.fk_account = ba.rowid";
1822
		$sql .= " AND ba.entity IN (".getEntity('bank_account').")";
1823
		if ($num) $sql .= " AND b.num_chq='".$this->db->escape($num)."'";
1824
		elseif ($ref) $sql .= " AND b.rowid='".$this->db->escape($ref)."'";
1825
		else $sql .= " AND b.rowid=".$rowid;
1826
1827
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
1828
		$result = $this->db->query($sql);
1829
		if ($result)
1830
		{
1831
			$ret = 0;
1832
1833
			$obj = $this->db->fetch_object($result);
1834
			if ($obj)
1835
			{
1836
				$this->id = $obj->rowid;
1837
				$this->rowid			= $obj->rowid;
1838
				$this->ref = $obj->rowid;
1839
1840
				$this->datec			= $obj->datec;
1841
				$this->datev			= $obj->datev;
1842
				$this->dateo			= $obj->dateo;
1843
				$this->amount = $obj->amount;
1844
				$this->label			= $obj->label;
1845
				$this->note				= $obj->note;
1846
1847
				$this->fk_user_author	= $obj->fk_user_author;
1848
				$this->fk_user_rappro	= $obj->fk_user_rappro;
1849
1850
				$this->fk_type = $obj->fk_type; // Type of transaction
1851
				$this->rappro = $obj->rappro;
1852
				$this->num_releve = $obj->num_releve;
1853
1854
				$this->num_chq = $obj->num_chq;
1855
				$this->bank_chq = $obj->banque;
1856
				$this->fk_bordereau = $obj->fk_bordereau;
1857
1858
				$this->fk_account = $obj->fk_account;
1859
				$this->bank_account_ref   = $obj->bank_account_ref;
1860
				$this->bank_account_label = $obj->bank_account_label;
1861
1862
				$ret = 1;
1863
			}
1864
			$this->db->free($result);
1865
			return $ret;
1866
		} else {
1867
			return -1;
1868
		}
1869
	}
1870
1871
	/**
1872
	 * Inserts a transaction to a bank account
1873
	 *
1874
	 * @return int <0 if KO, rowid of the line if OK
1875
	 */
1876
	public function insert()
1877
	{
1878
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."bank (";
1879
		$sql .= "datec";
1880
		$sql .= ", dateo";
1881
		$sql .= ", datev";
1882
		$sql .= ", label";
1883
		$sql .= ", amount";
1884
		$sql .= ", fk_user_author";
1885
		$sql .= ", num_chq";
1886
		$sql .= ", fk_account";
1887
		$sql .= ", fk_type";
1888
		$sql .= ", emetteur,banque";
1889
		$sql .= ", rappro";
1890
		$sql .= ", numero_compte";
1891
		$sql .= ") VALUES (";
1892
		$sql .= "'".$this->db->idate($this->datec)."'";
1893
		$sql .= ", '".$this->db->idate($this->dateo)."'";
1894
		$sql .= ", '".$this->db->idate($this->datev)."'";
1895
		$sql .= ", '".$this->db->escape($this->label)."'";
1896
		$sql .= ", ".price2num($this->amount);
1897
		$sql .= ", ".($this->fk_user_author > 0 ? $this->fk_user_author : "null");
1898
		$sql .= ", ".($this->num_chq ? "'".$this->db->escape($this->num_chq)."'" : "null");
1899
		$sql .= ", '".$this->db->escape($this->fk_account)."'";
1900
		$sql .= ", '".$this->db->escape($this->fk_type)."'";
1901
		$sql .= ", ".($this->emetteur ? "'".$this->db->escape($this->emetteur)."'" : "null");
1902
		$sql .= ", ".($this->bank_chq ? "'".$this->db->escape($this->bank_chq)."'" : "null");
1903
		$sql .= ", ".(int) $this->rappro;
1904
		$sql .= ", ".($this->numero_compte ? "'".$this->db->escape($this->numero_compte)."'" : "''");
0 ignored issues
show
Bug Best Practice introduced by
The property numero_compte does not exist on AccountLine. Did you maybe forget to declare it?
Loading history...
1905
		$sql .= ")";
1906
1907
		dol_syslog(get_class($this)."::insert", LOG_DEBUG);
1908
		$resql = $this->db->query($sql);
1909
1910
		if (!$resql) {
1911
			$this->error = $this->db->lasterror();
1912
			return -1;
1913
		}
1914
1915
		$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'bank');
1916
1917
		return $this->id;
1918
	}
1919
1920
	/**
1921
	 *      Delete bank transaction record
1922
	 *
1923
	 *		@param	User	$user	User object that delete
1924
	 *      @return	int 			<0 if KO, >0 if OK
1925
	 */
1926
    public function delete(User $user = null)
1927
	{
1928
    	global $conf;
1929
1930
		$nbko = 0;
1931
1932
		if ($this->rappro)
1933
		{
1934
			// Protection to avoid any delete of consolidated lines
1935
			$this->error = "ErrorDeleteNotPossibleLineIsConsolidated";
1936
			return -1;
1937
		}
1938
1939
		$this->db->begin();
1940
1941
		// Protection to avoid any delete of accounted lines. Protection on by default
1942
		if (empty($conf->global->BANK_ALLOW_TRANSACTION_DELETION_EVEN_IF_IN_ACCOUNTING))
1943
		{
1944
			$sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE doc_type = 'bank' AND fk_doc = ".$this->id;
1945
			$resql = $this->db->query($sql);
1946
			if ($resql) {
1947
				$obj = $this->db->fetch_object($resql);
1948
				if ($obj && $obj->nb) {
1949
					$this->error = 'ErrorRecordAlreadyInAccountingDeletionNotPossible';
1950
					$this->db->rollback();
1951
					return -1;
1952
				}
1953
			} else {
1954
				$this->error = $this->db->lasterror();
1955
				$this->db->rollback();
1956
				return -1;
1957
			}
1958
		}
1959
1960
		// Delete urls
1961
		$result = $this->delete_urls($user);
1962
		if ($result < 0)
1963
		{
1964
			$nbko++;
1965
		}
1966
1967
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_class WHERE lineid=".(int) $this->rowid;
1968
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1969
		$result = $this->db->query($sql);
1970
		if (!$result) $nbko++;
1971
1972
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."bank WHERE rowid=".(int) $this->rowid;
1973
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
1974
		$result = $this->db->query($sql);
1975
		if (!$result) $nbko++;
1976
1977
		if (!$nbko)
1978
		{
1979
			$this->db->commit();
1980
			return 1;
1981
		} else {
1982
			$this->db->rollback();
1983
			return -$nbko;
1984
		}
1985
	}
1986
1987
1988
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1989
	/**
1990
	 *      Delete bank line records
1991
	 *
1992
	 *		@param	User	$user	User object that delete
1993
	 *      @return	int 			<0 if KO, >0 if OK
1994
	 */
1995
    public function delete_urls(User $user = null)
1996
	{
1997
        // phpcs:enable
1998
		$nbko = 0;
1999
2000
		if ($this->rappro)
2001
		{
2002
			// Protection to avoid any delete of consolidated lines
2003
			$this->error = "ErrorDeleteNotPossibleLineIsConsolidated";
2004
			return -1;
2005
		}
2006
2007
		$this->db->begin();
2008
2009
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."bank_url WHERE fk_bank=".(int) $this->rowid;
2010
		dol_syslog(get_class($this)."::delete_urls", LOG_DEBUG);
2011
		$result = $this->db->query($sql);
2012
		if (!$result) $nbko++;
2013
2014
		if (!$nbko)
2015
		{
2016
			$this->db->commit();
2017
			return 1;
2018
		} else {
2019
			$this->db->rollback();
2020
			return -$nbko;
2021
		}
2022
	}
2023
2024
2025
	/**
2026
	 *		Update bank account record in database
2027
	 *
2028
	 *		@param	User	$user			Object user making update
2029
	 *		@param 	int		$notrigger		0=Disable all triggers
2030
	 *		@return	int						<0 if KO, >0 if OK
2031
	 */
2032
    public function update(User $user, $notrigger = 0)
2033
	{
2034
		$this->db->begin();
2035
2036
		$sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
2037
		$sql .= " amount = ".price2num($this->amount).",";
2038
		$sql .= " datev='".$this->db->idate($this->datev)."',";
2039
		$sql .= " dateo='".$this->db->idate($this->dateo)."'";
2040
		$sql .= " WHERE rowid = ".$this->rowid;
2041
2042
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
2043
		$resql = $this->db->query($sql);
2044
		if ($resql)
2045
		{
2046
			$this->db->commit();
2047
			return 1;
2048
		} else {
2049
			$this->db->rollback();
2050
			$this->error = $this->db->error();
2051
			return -1;
2052
		}
2053
	}
2054
2055
2056
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2057
	/**
2058
	 *	Update conciliation field
2059
	 *
2060
	 *	@param	User	$user			Objet user making update
2061
	 *	@param 	int		$cat			Category id
2062
	 *	@param	int		$conciliated	1=Set transaction to conciliated, 0=Keep transaction non conciliated
2063
	 *	@return	int						<0 if KO, >0 if OK
2064
	 */
2065
    public function update_conciliation(User $user, $cat, $conciliated = 1)
2066
	{
2067
        // phpcs:enable
2068
		global $conf, $langs;
2069
2070
		$this->db->begin();
2071
2072
		// Check statement field
2073
		if (!empty($conf->global->BANK_STATEMENT_REGEX_RULE))
2074
		{
2075
			if (!preg_match('/'.$conf->global->BANK_STATEMENT_REGEX_RULE.'/', $this->num_releve))
2076
			{
2077
				$this->errors[] = $langs->trans("ErrorBankStatementNameMustFollowRegex", $conf->global->BANK_STATEMENT_REGEX_RULE);
2078
				return -1;
2079
			}
2080
		}
2081
2082
		$sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
2083
		$sql .= " rappro = ".$conciliated;
2084
		$sql .= ", num_releve = '".$this->db->escape($this->num_releve)."'";
2085
		if ($conciliated) $sql .= ", fk_user_rappro = ".$user->id;
2086
		$sql .= " WHERE rowid = ".$this->id;
2087
2088
		dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG);
2089
		$resql = $this->db->query($sql);
2090
		if ($resql)
2091
		{
2092
			if (!empty($cat))
2093
			{
2094
				$sql = "INSERT INTO ".MAIN_DB_PREFIX."bank_class (";
2095
				$sql .= "lineid";
2096
				$sql .= ", fk_categ";
2097
				$sql .= ") VALUES (";
2098
				$sql .= $this->id;
2099
				$sql .= ", ".$cat;
2100
				$sql .= ")";
2101
2102
				dol_syslog(get_class($this)."::update_conciliation", LOG_DEBUG);
2103
				$this->db->query($sql);
2104
2105
				// No error check. Can fail if category already affected
2106
			}
2107
2108
			$this->rappro = 1;
2109
2110
			$this->db->commit();
2111
			return 1;
2112
		} else {
2113
			$this->db->rollback();
2114
			return -1;
2115
		}
2116
	}
2117
2118
2119
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2120
	/**
2121
	 * 	Increase/decrease value date of a rowid
2122
	 *
2123
	 *	@param	int		$rowid		Id of line
2124
	 *	@param	int		$sign		1 or -1
2125
	 *	@return	int					>0 if OK, 0 if KO
2126
	 */
2127
    public function datev_change($rowid, $sign = 1)
2128
	{
2129
        // phpcs:enable
2130
		$sql = "SELECT datev FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid;
2131
		$resql = $this->db->query($sql);
2132
		if ($resql)
2133
		{
2134
			$obj = $this->db->fetch_object($resql);
2135
			$newdate = $this->db->jdate($obj->datev) + (3600 * 24 * $sign);
2136
2137
			$sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
2138
			$sql .= " datev = '".$this->db->idate($newdate)."'";
2139
			$sql .= " WHERE rowid = ".$rowid;
2140
2141
			$result = $this->db->query($sql);
2142
			if ($result)
2143
			{
2144
				if ($this->db->affected_rows($result))
2145
				{
2146
					return 1;
2147
				}
2148
			} else {
2149
				dol_print_error($this->db);
2150
				return 0;
2151
			}
2152
		} else dol_print_error($this->db);
2153
		return 0;
2154
	}
2155
2156
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2157
	/**
2158
	 * 	Increase value date of a rowid
2159
	 *
2160
	 *	@param	int		$id		Id of line to change
2161
	 *	@return	int				>0 if OK, 0 if KO
2162
	 */
2163
    public function datev_next($id)
2164
	{
2165
        // phpcs:enable
2166
		return $this->datev_change($id, 1);
2167
	}
2168
2169
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2170
	/**
2171
	 * 	Decrease value date of a rowid
2172
	 *
2173
	 *	@param	int		$id		Id of line to change
2174
	 *	@return	int				>0 if OK, 0 if KO
2175
	 */
2176
    public function datev_previous($id)
2177
	{
2178
        // phpcs:enable
2179
		return $this->datev_change($id, -1);
2180
	}
2181
2182
2183
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2184
	/**
2185
	 * 	Increase/decrease operation date of a rowid
2186
	 *
2187
	 *	@param	int		$rowid		Id of line
2188
	 *	@param	int		$sign		1 or -1
2189
	 *	@return	int					>0 if OK, 0 if KO
2190
	 */
2191
    public function dateo_change($rowid, $sign = 1)
2192
	{
2193
        // phpcs:enable
2194
		$sql = "SELECT dateo FROM ".MAIN_DB_PREFIX."bank WHERE rowid = ".$rowid;
2195
		$resql = $this->db->query($sql);
2196
		if ($resql)
2197
		{
2198
			$obj = $this->db->fetch_object($resql);
2199
			$newdate = $this->db->jdate($obj->dateo) + (3600 * 24 * $sign);
2200
2201
			$sql = "UPDATE ".MAIN_DB_PREFIX."bank SET";
2202
			$sql .= " dateo = '".$this->db->idate($newdate)."'";
2203
			$sql .= " WHERE rowid = ".$rowid;
2204
2205
			$result = $this->db->query($sql);
2206
			if ($result)
2207
			{
2208
				if ($this->db->affected_rows($result))
2209
				{
2210
					return 1;
2211
				}
2212
			} else {
2213
				dol_print_error($this->db);
2214
				return 0;
2215
			}
2216
		} else dol_print_error($this->db);
2217
		return 0;
2218
	}
2219
2220
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2221
	/**
2222
	 * 	Increase operation date of a rowid
2223
	 *
2224
	 *	@param	int		$id		Id of line to change
2225
	 *	@return	int				>0 if OK, 0 if KO
2226
	 */
2227
    public function dateo_next($id)
2228
	{
2229
        // phpcs:enable
2230
		return $this->dateo_change($id, 1);
2231
	}
2232
2233
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2234
	/**
2235
	 * 	Decrease operation date of a rowid
2236
	 *
2237
	 *	@param	int		$id		Id of line to change
2238
	 *	@return	int				>0 if OK, 0 if KO
2239
	 */
2240
    public function dateo_previous($id)
2241
	{
2242
        // phpcs:enable
2243
		return $this->dateo_change($id, -1);
2244
	}
2245
2246
2247
	/**
2248
	 *	Load miscellaneous information for tab "Info"
2249
	 *
2250
	 *	@param  int		$id		Id of object to load
2251
	 *	@return	void
2252
	 */
2253
    public function info($id)
2254
	{
2255
		$sql = 'SELECT b.rowid, b.datec, b.tms as datem,';
2256
		$sql .= ' b.fk_user_author, b.fk_user_rappro';
2257
		$sql .= ' FROM '.MAIN_DB_PREFIX.'bank as b';
2258
		$sql .= ' WHERE b.rowid = '.$id;
2259
2260
		$result = $this->db->query($sql);
2261
		if ($result)
2262
		{
2263
			if ($this->db->num_rows($result))
2264
			{
2265
				$obj = $this->db->fetch_object($result);
2266
				$this->id = $obj->rowid;
2267
2268
				if ($obj->fk_user_author)
2269
				{
2270
					$cuser = new User($this->db);
2271
					$cuser->fetch($obj->fk_user_author);
2272
					$this->user_creation = $cuser;
2273
				}
2274
				if ($obj->fk_user_rappro)
2275
				{
2276
					$ruser = new User($this->db);
2277
					$ruser->fetch($obj->fk_user_rappro);
2278
					$this->user_rappro = $ruser;
2279
				}
2280
2281
				$this->date_creation     = $this->db->jdate($obj->datec);
2282
				$this->date_modification = $this->db->jdate($obj->datem);
2283
				//$this->date_rappro       = $obj->daterappro;    // Not yet managed
2284
			}
2285
			$this->db->free($result);
2286
		} else {
2287
			dol_print_error($this->db);
2288
		}
2289
	}
2290
2291
2292
	/**
2293
	 *    	Return clickable name (with picto eventually)
2294
	 *
2295
	 *		@param	int		$withpicto		0=No picto, 1=Include picto into link, 2=Only picto
2296
	 *		@param	int		$maxlen			Longueur max libelle
2297
	 *		@param	string	$option			Option ('', 'showall', 'showconciliated', 'showconciliatedandaccounted'). Options may be slow.
2298
	 * 		@param	int     $notooltip		1=Disable tooltip
2299
	 *		@return	string					Chaine avec URL
2300
	 */
2301
    public function getNomUrl($withpicto = 0, $maxlen = 0, $option = '', $notooltip = 0)
2302
	{
2303
		global $langs;
2304
2305
		$result = '';
2306
		$label = $langs->trans("ShowTransaction").': '.$this->rowid;
2307
		$linkstart = '<a href="'.DOL_URL_ROOT.'/compta/bank/line.php?rowid='.$this->rowid.'" title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip">';
2308
		$linkend = '</a>';
2309
2310
		$result .= $linkstart;
2311
		if ($withpicto) $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'account'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
2312
		if ($withpicto != 2) $result .= ($this->ref ? $this->ref : $this->rowid);
2313
		$result .= $linkend;
2314
2315
		if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted') $result .= ' <span class="opacitymedium">(';
2316
		if ($option == 'showall')
2317
		{
2318
			$result .= $langs->trans("BankAccount").': ';
2319
			$accountstatic = new Account($this->db);
2320
			$accountstatic->id = $this->fk_account;
2321
			$accountstatic->ref = $this->bank_account_ref;
2322
			$accountstatic->label = $this->bank_account_label;
2323
			$result .= $accountstatic->getNomUrl(0).', ';
2324
		}
2325
		if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted')
2326
		{
2327
			$result .= $langs->trans("BankLineConciliated").': ';
2328
			$result .= yn($this->rappro);
2329
		}
2330
		if ($option == 'showall' || $option == 'showconciliatedandaccounted')
2331
		{
2332
			$sql = "SELECT COUNT(rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping WHERE doc_type = 'bank' AND fk_doc = ".$this->id;
2333
			$resql = $this->db->query($sql);
2334
			if ($resql) {
2335
				$obj = $this->db->fetch_object($resql);
2336
				if ($obj && $obj->nb) {
2337
					$result .= ' - '.$langs->trans("Accounted").': '.yn(1);
2338
				} else {
2339
					$result .= ' - '.$langs->trans("Accounted").': '.yn(0);
2340
				}
2341
			}
2342
		}
2343
		if ($option == 'showall' || $option == 'showconciliated' || $option == 'showconciliatedandaccounted') $result .= ')</span>';
2344
2345
		return $result;
2346
	}
2347
2348
2349
	/**
2350
	 *    Return label of status (activity, closed)
2351
	 *
2352
	 *    @param	int		$mode       0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long
2353
	 *    @return   string        		Libelle
2354
	 */
2355
    public function getLibStatut($mode = 0)
2356
	{
2357
		return $this->LibStatut($this->status, $mode);
2358
	}
2359
2360
    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2361
	/**
2362
	 *  Renvoi le libelle d'un statut donne
2363
	 *
2364
	 *  @param	int		$status         Id statut
2365
	 *  @param	int		$mode           0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
2366
	 *  @return	string          		Libelle du statut
2367
	 */
2368
    public function LibStatut($status, $mode = 0)
2369
	{
2370
        // phpcs:enable
2371
		global $langs;
2372
		//$langs->load('companies');
2373
		/*
2374
        if ($mode == 0)
2375
        {
2376
            if ($status==0) return $langs->trans("ActivityCeased");
2377
            if ($status==1) return $langs->trans("InActivity");
2378
        }
2379
        if ($mode == 1)
2380
        {
2381
            if ($status==0) return $langs->trans("ActivityCeased");
2382
            if ($status==1) return $langs->trans("InActivity");
2383
        }
2384
        if ($mode == 2)
2385
        {
2386
            if ($status==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2387
            if ($status==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2388
        }
2389
        if ($mode == 3)
2390
        {
2391
            if ($status==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2392
            if ($status==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2393
        }
2394
        if ($mode == 4)
2395
        {
2396
            if ($status==0) return img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"').' '.$langs->trans("ActivityCeased");
2397
            if ($status==1) return img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"').' '.$langs->trans("InActivity");
2398
        }
2399
        if ($mode == 5)
2400
        {
2401
            if ($status==0) return $langs->trans("ActivityCeased").' '.img_picto($langs->trans("ActivityCeased"),'statut5', 'class="pictostatus"');
2402
            if ($status==1) return $langs->trans("InActivity").' '.img_picto($langs->trans("InActivity"),'statut4', 'class="pictostatus"');
2403
        }*/
2404
	}
2405
2406
2407
	/**
2408
	 *	Return if a bank line was dispatched into bookkeeping
2409
	 *
2410
	 *	@return     int         <0 if KO, 0=no, 1=yes
2411
	 */
2412
	public function getVentilExportCompta()
2413
	{
2414
		$alreadydispatched = 0;
2415
2416
		$type = 'bank';
2417
2418
		$sql = " SELECT COUNT(ab.rowid) as nb FROM ".MAIN_DB_PREFIX."accounting_bookkeeping as ab WHERE ab.doc_type='".$type."' AND ab.fk_doc = ".$this->id;
2419
		$resql = $this->db->query($sql);
2420
		if ($resql)
2421
		{
2422
			$obj = $this->db->fetch_object($resql);
2423
			if ($obj)
2424
			{
2425
				$alreadydispatched = $obj->nb;
2426
			}
2427
		} else {
2428
			$this->error = $this->db->lasterror();
2429
			return -1;
2430
		}
2431
2432
		if ($alreadydispatched)
2433
		{
2434
			return 1;
2435
		}
2436
		return 0;
2437
	}
2438
}
2439