Passed
Branch develop (07a336)
by
unknown
39:19
created

Account::getCountryCode()   B

Complexity

Conditions 7
Paths 12

Size

Total Lines 28
Code Lines 12

Duplication

Lines 0
Ratio 0 %

Importance

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

533
		if (!/** @scrutinizer ignore-deprecated */ $this->rowid)
Loading history...
534
		{
535
			$this->error = "this->rowid not defined";
536
			return -2;
537
		}
538
		if ($this->courant == Account::TYPE_CASH && $oper != 'LIQ')
539
		{
540
			$this->error = "ErrorCashAccountAcceptsOnlyCashMoney";
541
			return -3;
542
		}
543
544
		$this->db->begin();
545
546
		if (is_null($datev) || empty($datev)) $datev = $date;
547
548
		$accline = new AccountLine($this->db);
549
		$accline->datec = $now;
550
		$accline->dateo = $date;
551
		$accline->datev = $datev;
552
		$accline->label = $label;
553
		$accline->amount = $amount;
554
		$accline->fk_user_author = $user->id;
555
		$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

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

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