Passed
Branch develop (5cbde9)
by
unknown
26:38
created

AccountancyCategory::update()   F

Complexity

Conditions 23
Paths > 20000

Size

Total Lines 69
Code Lines 35

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 23
eloc 35
c 0
b 0
f 0
nc 2097152
nop 2
dl 0
loc 69
rs 0

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2016		Jamal Elbaz			<[email protected]>
3
 * Copyright (C) 2016-2017	Alexandre Spangaro	<[email protected]>
4
 * Copyright (C) 2018-2019  Frédéric France     <[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
18
 */
19
20
/**
21
 * \file	htdocs/accountancy/class/accountancycategory.class.php
22
 * \ingroup Accountancy (Double entries)
23
 * \brief	File of class to manage categories of an accounting category_type
24
 */
25
26
// Class
27
require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
28
29
/**
30
 * Class to manage categories of an accounting account
31
 */
32
class AccountancyCategory // extends CommonObject
33
{
34
    /**
35
     * @var DoliDB Database handler.
36
     */
37
    public $db;
38
39
	/**
40
	 * @var string 		Error string
41
	 * @see             $errors
42
	 */
43
	public $error;
44
45
	/**
46
	 * @var string[] Error codes (or messages)
47
	 */
48
	public $errors = array();
49
50
	/**
51
	 * @var string ID to identify managed object
52
	 */
53
	public $element='c_accounting_category';
54
55
	/**
56
	 * @var string Name of table without prefix where object is stored
57
	 */
58
	public $table_element='c_accounting_category';
59
60
	/**
61
     * @var int ID
62
     */
63
    public $id;
64
65
	/**
66
	 * @var string Accountancy code
67
	 */
68
	public $code;
69
70
	/**
71
     * @var string Accountancy Category label
72
     */
73
    public $label;
74
75
    /**
76
	 * @var string Accountancy range account
77
	 */
78
	public $range_account;
79
80
	/**
81
	 * @var int Sens of the account:  0: credit - debit, 1: debit - credit
82
	 */
83
	public $sens;
84
85
	/**
86
	 * @var int Category type of accountancy
87
	 */
88
	public $category_type;
89
90
	/**
91
	 * @var string Formula
92
	 */
93
	public $formula;
94
95
	/**
96
	 * @var int     Position
97
	 */
98
	public $position;
99
100
	/**
101
	 * @var int country id
102
	 */
103
	public $fk_country;
104
105
	/**
106
	 * @var int Is active
107
	 */
108
	public $active;
109
110
	/**
111
	 * @var array Lines cptbk
112
	 */
113
	public $lines_cptbk;
114
115
	/**
116
	 * @var array Lines display
117
	 */
118
	public $lines_display;
119
120
	/**
121
	 * @var mixed Sample property 1
122
	 */
123
	public $sdc;
124
125
126
127
	/**
128
	 *  Constructor
129
	 *
130
	 *  @param      DoliDb		$db      Database handler
131
	 */
132
	public function __construct($db)
133
	{
134
		$this->db = $db;
135
	}
136
137
138
	/**
139
	 *  Create object into database
140
	 *
141
	 *  @param      User	$user        User that create
142
	 *  @param      int		$notrigger   0=launch triggers after, 1=disable triggers
143
	 *  @return     int      		   	 <0 if KO, Id of created object if OK
144
	 */
145
	public function create($user, $notrigger = 0)
146
	{
147
		global $conf, $langs;
148
		$error=0;
149
150
		// Clean parameters
151
		if (isset($this->code)) $this->code=trim($this->code);
152
		if (isset($this->label)) $this->label=trim($this->label);
153
		if (isset($this->range_account)) $this->range_account=trim($this->range_account);
154
		if (isset($this->sens)) $this->sens = (int) $this->sens;
155
		if (isset($this->category_type)) $this->category_type = (int) $this->category_type;
156
		if (isset($this->formula)) $this->formula=trim($this->formula);
157
		if (isset($this->position)) $this->position = (int) $this->position;
158
		if (isset($this->fk_country)) $this->fk_country = (int) $this->fk_country;
159
		if (isset($this->active)) $this->active = (int) $this->active;
160
161
		// Check parameters
162
		// Put here code to add control on parameters values
163
164
		// Insert request
165
		$sql = "INSERT INTO ".MAIN_DB_PREFIX."c_accounting_category(";
166
		if ($this->rowid > 0) $sql.= "rowid, ";
167
		$sql.= "code, ";
168
		$sql.= "label, ";
169
		$sql.= "range_account, ";
170
		$sql.= "sens, ";
171
		$sql.= "category_type, ";
172
		$sql.= "formula, ";
173
		$sql.= "position, ";
174
		$sql.= "fk_country, ";
175
		$sql.= "active, ";
176
		$sql.= "entity";
177
		$sql.= ") VALUES (";
178
		if ($this->rowid > 0) $sql.= " ".$this->rowid.",";
179
		$sql.= " ".(! isset($this->code)?'NULL':"'".$this->db->escape($this->code)."'").",";
180
		$sql.= " ".(! isset($this->label)?'NULL':"'".$this->db->escape($this->label)."'").",";
181
		$sql.= " ".(! isset($this->range_account)?'NULL':"'".$this->db->escape($this->range_account)."'").",";
182
		$sql.= " ".(! isset($this->sens)?'NULL':"'".$this->db->escape($this->sens)."'").",";
183
		$sql.= " ".(! isset($this->category_type)?'NULL':"'".$this->db->escape($this->category_type)."'").",";
184
		$sql.= " ".(! isset($this->formula)?'NULL':"'".$this->db->escape($this->formula)."'").",";
185
		$sql.= " ".(! isset($this->position)?'NULL':$this->db->escape($this->position)).",";
186
		$sql.= " ".(! isset($this->fk_country)?'NULL':$this->db->escape($this->fk_country)).",";
187
		$sql.= " ".(! isset($this->active)?'NULL':$this->db->escape($this->active));
188
		$sql.= ", ".$conf->entity;
189
		$sql.= ")";
190
191
		$this->db->begin();
192
193
		dol_syslog(get_class($this)."::create", LOG_DEBUG);
194
		$resql=$this->db->query($sql);
195
		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
196
197
		if (! $error)
198
		{
199
			$this->id = $this->db->last_insert_id(MAIN_DB_PREFIX."c_accounting_category");
200
201
			// Uncomment this and change MYOBJECT to your own tag if you
202
			// want this action call a trigger.
203
			//if (! $notrigger)
204
			//{
205
206
			//	// Call triggers
207
			//	include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
208
			//	$interface=new Interfaces($this->db);
209
			//	$result=$interface->run_triggers('MYOBJECT_CREATE',$this,$user,$langs,$conf);
210
			//	if ($result < 0) { $error++; $this->errors=$interface->errors; }
211
			//	// End call triggers
212
			//}
213
		}
214
215
		// Commit or rollback
216
		if ($error)
217
		{
218
			foreach($this->errors as $errmsg)
219
			{
220
				dol_syslog(get_class($this)."::create ".$errmsg, LOG_ERR);
221
				$this->error.=($this->error?', '.$errmsg:$errmsg);
222
			}
223
			$this->db->rollback();
224
			return -1*$error;
225
		}
226
		else
227
		{
228
			$this->db->commit();
229
			return $this->id;
230
		}
231
	}
232
233
234
	/**
235
	 *  Load object in memory from database
236
	 *
237
	 *  @param      int		$id    	Id object
238
	 *  @param		string	$code	Code
239
	 *  @param		string	$label	Label
240
	 *  @return     int          	<0 if KO, >0 if OK
241
	 */
242
	public function fetch($id, $code = '', $label = '')
243
	{
244
		$sql = "SELECT";
245
		$sql.= " t.rowid,";
246
		$sql.= " t.code,";
247
		$sql.= " t.label,";
248
		$sql.= " t.range_account,";
249
		$sql.= " t.sens,";
250
		$sql.= " t.category_type,";
251
		$sql.= " t.formula,";
252
		$sql.= " t.position,";
253
		$sql.= " t.fk_country,";
254
		$sql.= " t.active";
255
		$sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as t";
256
		if ($id)   $sql.= " WHERE t.rowid = ".$id;
257
		else
258
		{
259
			$sql.= " WHERE t.entity IN (".getEntity('c_accounting_category').")"; // Dont't use entity if you use rowid
260
			if ($code) $sql.= " AND t.code = '".$this->db->escape($code)."'";
261
			elseif ($label) $sql.= " AND t.label = '".$this->db->escape($label)."'";
262
		}
263
264
		dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
265
		$resql=$this->db->query($sql);
266
		if ($resql)
267
		{
268
			if ($this->db->num_rows($resql))
269
			{
270
				$obj = $this->db->fetch_object($resql);
271
272
				$this->id            = $obj->rowid;
273
				$this->code          = $obj->code;
274
				$this->label         = $obj->label;
275
				$this->range_account = $obj->range_account;
276
				$this->sens          = $obj->sens;
277
				$this->category_type = $obj->category_type;
278
				$this->formula       = $obj->formula;
279
				$this->position      = $obj->position;
280
				$this->fk_country    = $obj->fk_country;
281
				$this->active        = $obj->active;
282
			}
283
			$this->db->free($resql);
284
285
			return 1;
286
		}
287
		else
288
		{
289
			$this->error="Error ".$this->db->lasterror();
290
			return -1;
291
		}
292
	}
293
294
295
	/**
296
	 *  Update object into database
297
	 *
298
	 *  @param      User	$user        User that modify
299
	 *  @param      int		$notrigger	 0=launch triggers after, 1=disable triggers
300
	 *  @return     int     		   	 <0 if KO, >0 if OK
301
	 */
302
	public function update($user = null, $notrigger = 0)
303
	{
304
		global $conf, $langs;
305
		$error=0;
306
307
		// Clean parameters
308
		if (isset($this->code)) $this->code=trim($this->code);
309
		if (isset($this->label)) $this->label=trim($this->label);
310
		if (isset($this->range_account)) $this->range_account=trim($this->range_account);
311
		if (isset($this->sens)) $this->sens = (int) $this->sens;
312
		if (isset($this->category_type)) $this->category_type = (int) $this->category_type;
313
		if (isset($this->formula)) $this->formula=trim($this->formula);
314
		if (isset($this->position)) $this->position = (int) $this->position;
315
		if (isset($this->fk_country)) $this->fk_country = (int) $this->fk_country;
316
		if (isset($this->active)) $this->active = (int) $this->active;
317
318
319
		// Check parameters
320
		// Put here code to add control on parameters values
321
322
		// Update request
323
		$sql = "UPDATE ".MAIN_DB_PREFIX."c_accounting_category SET";
324
		$sql.= " code=".(isset($this->code)?"'".$this->db->escape($this->code)."'":"null").",";
325
		$sql.= " label=".(isset($this->label)?"'".$this->db->escape($this->label)."'":"null").",";
326
		$sql.= " range_account=".(isset($this->range_account)?"'".$this->db->escape($this->range_account)."'":"null").",";
327
		$sql.= " sens=".(isset($this->sens)?$this->sens:"null").",";
328
		$sql.= " category_type=".(isset($this->category_type)?$this->category_type:"null").",";
329
		$sql.= " formula=".(isset($this->formula)?"'".$this->db->escape($this->formula)."'":"null").",";
330
		$sql.= " position=".(isset($this->position)?$this->position:"null").",";
331
		$sql.= " fk_country=".(isset($this->fk_country)?$this->fk_country:"null").",";
332
		$sql.= " active=".(isset($this->active)?$this->active:"null")."";
333
		$sql.= " WHERE rowid=".$this->id;
334
335
		$this->db->begin();
336
337
		dol_syslog(get_class($this)."::update", LOG_DEBUG);
338
		$resql = $this->db->query($sql);
339
		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
340
341
		//if (! $error)
342
		//{
343
			// Uncomment this and change MYOBJECT to your own tag if you
344
			// want this action call a trigger.
345
			//if (! $notrigger)
346
			//{
347
			//	// Call triggers
348
			//	include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
349
			//	$interface=new Interfaces($this->db);
350
			//	$result=$interface->run_triggers('MYOBJECT_MODIFY',$this,$user,$langs,$conf);
351
			//	if ($result < 0) { $error++; $this->errors=$interface->errors; }
352
			//	// End call triggers
353
			//}
354
		//}
355
356
		// Commit or rollback
357
		if ($error)
358
		{
359
			foreach($this->errors as $errmsg)
360
			{
361
				dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
362
				$this->error.=($this->error?', '.$errmsg:$errmsg);
363
			}
364
			$this->db->rollback();
365
			return -1*$error;
366
		}
367
		else
368
		{
369
			$this->db->commit();
370
			return 1;
371
		}
372
	}
373
374
375
	/**
376
	 *  Delete object in database
377
	 *
378
	 *	@param  User	$user        User that delete
379
	 *  @param	int		$notrigger	 0=launch triggers after, 1=disable triggers
380
	 *  @return	int					 <0 if KO, >0 if OK
381
	 */
382
	public function delete($user, $notrigger = 0)
383
	{
384
		global $conf, $langs;
385
		$error=0;
386
387
		$sql = "DELETE FROM ".MAIN_DB_PREFIX."c_accounting_category";
388
		$sql.= " WHERE rowid=".$this->id;
389
390
		$this->db->begin();
391
392
		dol_syslog(get_class($this)."::delete", LOG_DEBUG);
393
		$resql = $this->db->query($sql);
394
		if (! $resql) { $error++; $this->errors[]="Error ".$this->db->lasterror(); }
395
396
		//if (! $error)
397
		//{
398
			// Uncomment this and change MYOBJECT to your own tag if you
399
			// want this action call a trigger.
400
			//if (! $notrigger)
401
			//{
402
			//	// Call triggers
403
			//	include_once DOL_DOCUMENT_ROOT . '/core/class/interfaces.class.php';
404
			//	$interface=new Interfaces($this->db);
405
			//	$result=$interface->run_triggers('MYOBJECT_DELETE',$this,$user,$langs,$conf);
406
			//	if ($result < 0) { $error++; $this->errors=$interface->errors; }
407
			//	// End call triggers
408
			//}
409
		//}
410
411
		// Commit or rollback
412
		if ($error)
413
		{
414
			foreach($this->errors as $errmsg)
415
			{
416
				dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
417
				$this->error.=($this->error?', '.$errmsg:$errmsg);
418
			}
419
			$this->db->rollback();
420
			return -1*$error;
421
		}
422
		else
423
		{
424
			$this->db->commit();
425
			return 1;
426
		}
427
	}
428
429
430
	/**
431
	 * Function to select all accounting accounts from an accounting category
432
	 *
433
	 * @param int $id Id
434
	 * @return int <0 if KO, 0 if not found, >0 if OK
435
	 */
436
    public function display($id)
437
    {
438
		global $conf;
439
		$sql = "SELECT t.rowid, t.account_number, t.label";
440
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t";
441
		$sql .= " WHERE t.fk_accounting_category = " . $id;
442
		$sql .= " AND t.entity = " . $conf->entity;
443
444
		$this->lines_display = array();
445
446
		dol_syslog(__METHOD__ . " sql=" . $sql, LOG_DEBUG);
447
		$resql = $this->db->query($sql);
448
		if ($resql) {
449
			$num = $this->db->num_rows($resql);
450
			if ($num) {
451
				while ( $obj = $this->db->fetch_object($resql) ) {
452
					$this->lines_display[] = $obj;
453
				}
454
			}
455
			return $num;
456
		} else {
457
			$this->error = "Error " . $this->db->lasterror();
458
			$this->errors[] = $this->error;
459
			dol_syslog(__METHOD__ . " " . implode(',' . $this->errors), LOG_ERR);
1 ignored issue
show
Bug introduced by
Are you sure $this->errors of type string[] can be used in concatenation? ( Ignorable by Annotation )

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

459
			dol_syslog(__METHOD__ . " " . implode(',' . /** @scrutinizer ignore-type */ $this->errors), LOG_ERR);
Loading history...
460
461
			return - 1;
462
		}
463
    }
464
465
	/**
466
	 * Function to select accounting category of an accounting account present in chart of accounts
467
	 *
468
	 * @param int $id Id category
469
	 *
470
	 * @return int <0 if KO, 0 if not found, >0 if OK
471
	 */
472
    public function getCptBK($id)
473
    {
474
		global $conf;
475
476
		$sql = "SELECT t.numero_compte, t.label_operation, t.doc_ref";
477
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as t";
478
		$sql .= " WHERE t.numero_compte NOT IN (";
479
		$sql .= " SELECT t.account_number";
480
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t";
481
		$sql .= " WHERE t.fk_accounting_category = " . $id . " AND t.entity = " . $conf->entity.")";
482
		$sql .= " AND t.numero_compte IN (";
483
		$sql .= " SELECT DISTINCT aa.account_number";
484
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
485
		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
486
		$sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
487
		$sql .= " AND aa.active = 1";
488
		$sql .= " AND aa.entity = " . $conf->entity . ")";
489
		$sql .= " GROUP BY t.numero_compte, t.label_operation, t.doc_ref";
490
		$sql .= " ORDER BY t.numero_compte";
491
492
		$this->lines_CptBk = array ();
493
494
		dol_syslog(__METHOD__, LOG_DEBUG);
495
		$resql = $this->db->query($sql);
496
		if ($resql) {
497
			$num = $this->db->num_rows($resql);
498
			if ($num) {
499
				while ( $obj = $this->db->fetch_object($resql) ) {
500
					$this->lines_cptbk[] = $obj;
501
				}
502
			}
503
504
			return $num;
505
		} else {
506
			$this->error = "Error " . $this->db->lasterror();
507
			$this->errors[] = $this->error;
508
			dol_syslog(__METHOD__ . " " . implode(',' . $this->errors), LOG_ERR);
1 ignored issue
show
Bug introduced by
Are you sure $this->errors of type string[] can be used in concatenation? ( Ignorable by Annotation )

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

508
			dol_syslog(__METHOD__ . " " . implode(',' . /** @scrutinizer ignore-type */ $this->errors), LOG_ERR);
Loading history...
509
510
			return - 1;
511
		}
512
    }
513
514
	/**
515
	 * Function to select accounting category of an accounting account present in chart of accounts
516
	 *
517
	 * @param int $id      Id of category to know which account to exclude
518
	 *
519
	 * @return int <0 if KO, 0 if not found, >0 if OK
520
	 */
521
    public function getAccountsWithNoCategory($id)
522
    {
523
        global $conf;
524
525
	    $sql = "SELECT aa.account_number as numero_compte, aa.label as label_compte";
526
	    $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
527
	    $sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
528
	    $sql .= " WHERE (aa.fk_accounting_category != ".$id." OR aa.fk_accounting_category IS NULL)";
529
	    $sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
530
	    $sql .= " AND aa.active = 1";
531
	    $sql .= " AND aa.entity = " . $conf->entity;
532
	    $sql .= " GROUP BY aa.account_number, aa.label";
533
	    $sql .= " ORDER BY aa.account_number, aa.label";
534
535
	    $this->lines_CptBk = array ();
536
537
	    dol_syslog(__METHOD__, LOG_DEBUG);
538
	    $resql = $this->db->query($sql);
539
	    if ($resql) {
540
	        $num = $this->db->num_rows($resql);
541
	        if ($num) {
542
	            while ( $obj = $this->db->fetch_object($resql) ) {
543
	                $this->lines_cptbk[] = $obj;
544
	            }
545
	        }
546
547
	        return $num;
548
	    } else {
549
	        $this->error = "Error " . $this->db->lasterror();
550
	        $this->errors[] = $this->error;
551
	        dol_syslog(__METHOD__ . " " . implode(',' . $this->errors), LOG_ERR);
1 ignored issue
show
Bug introduced by
Are you sure $this->errors of type string[] can be used in concatenation? ( Ignorable by Annotation )

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

551
	        dol_syslog(__METHOD__ . " " . implode(',' . /** @scrutinizer ignore-type */ $this->errors), LOG_ERR);
Loading history...
552
553
	        return - 1;
554
	    }
555
    }
556
557
	/**
558
	 * Function to add an accounting account in an accounting category
559
	 *
560
	 * @param int $id_cat Id category
561
	 * @param array $cpts list of accounts array
562
	 *
563
	 * @return int <0 if KO, >0 if OK
564
	 */
565
    public function updateAccAcc($id_cat, $cpts = array())
566
    {
567
		global $conf;
568
		$error = 0;
569
570
		require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
571
572
		$sql = "SELECT aa.rowid, aa.account_number";
573
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
574
		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
575
		$sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
576
		$sql .= " AND aa.active = 1";
577
		$sql .= " AND aa.entity = " . $conf->entity;
578
        $sql .= " ORDER BY LENGTH(aa.account_number) DESC;";    // LENGTH is ok with mysql and postgresql
579
580
		$this->db->begin();
581
582
		dol_syslog(__METHOD__, LOG_DEBUG);
583
		$resql = $this->db->query($sql);
584
		if (! $resql) {
585
			$error ++;
586
			$this->errors[] = "Error " . $this->db->lasterror();
587
			$this->db->rollback();
588
			return -1;
589
		}
590
591
		$accountincptsadded=array();
592
		while ($obj = $this->db->fetch_object($resql))
593
		{
594
		    $account_number_formated=length_accountg($obj->account_number);
595
		    if (! empty($accountincptsadded[$account_number_formated])) continue;
596
597
		    if (array_key_exists($account_number_formated, $cpts))
598
			{
599
			    $accountincptsadded[$account_number_formated]=1;
600
			    // We found an account number that is in list $cpts of account to add
601
				$sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_account";
602
				$sql .= " SET fk_accounting_category=" . $id_cat;
603
				$sql .= " WHERE rowid=".$obj->rowid;
604
				dol_syslog(__METHOD__, LOG_DEBUG);
605
				$resqlupdate = $this->db->query($sql);
606
				if (! $resqlupdate) {
607
					$error ++;
608
					$this->errors[] = "Error " . $this->db->lasterror();
609
				}
610
			}
611
		}
612
613
		// Commit or rollback
614
		if ($error) {
615
			foreach ($this->errors as $errmsg) {
616
				dol_syslog(__METHOD__ . " " . $errmsg, LOG_ERR);
617
				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
618
			}
619
			$this->db->rollback();
620
621
			return - 1 * $error;
622
		} else {
623
			$this->db->commit();
624
625
			return 1;
626
		}
627
    }
628
629
	/**
630
	 * Function to delete an accounting account from an accounting category
631
	 *
632
	 * @param int $cpt_id Id of accounting account
633
	 *
634
	 * @return int <0 if KO, >0 if OK
635
	 */
636
    public function deleteCptCat($cpt_id)
637
    {
638
		$error = 0;
639
640
		$sql = "UPDATE " . MAIN_DB_PREFIX . "accounting_account as aa";
641
		$sql .= " SET fk_accounting_category= 0";
642
		$sql .= " WHERE aa.rowid= " . $cpt_id;
643
		$this->db->begin();
644
645
		dol_syslog(__METHOD__ . " sql=" . $sql, LOG_DEBUG);
646
		$resql = $this->db->query($sql);
647
		if (! $resql) {
648
			$error ++;
649
			$this->errors[] = "Error " . $this->db->lasterror();
650
		}
651
652
		// Commit or rollback
653
        if ($error) {
654
			foreach ($this->errors as $errmsg) {
655
				dol_syslog(__METHOD__ . " " . $errmsg, LOG_ERR);
656
				$this->error .= ($this->error ? ', ' . $errmsg : $errmsg);
657
			}
658
			$this->db->rollback();
659
660
			return - 1 * $error;
661
        } else {
662
			$this->db->commit();
663
664
            return 1;
665
        }
666
    }
667
668
	/**
669
	 * Function to know all category from accounting account
670
	 *
671
	 * @return array|integer       Result in table (array), -1 if KO
672
	 */
673
	public function getCatsCpts()
674
	{
675
		global $mysoc, $conf;
676
677
		if (empty($mysoc->country_id)) {
678
			dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined');
679
			exit();
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
680
		}
681
682
		$sql = "SELECT t.rowid, t.account_number, t.label as account_label, cat.code, cat.position, cat.label as name_cat, cat.sens ";
683
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t, " . MAIN_DB_PREFIX . "c_accounting_category as cat";
684
		$sql .= " WHERE t.fk_accounting_category IN ( SELECT c.rowid ";
685
		$sql .= " FROM " . MAIN_DB_PREFIX . "c_accounting_category as c";
686
		$sql .= " WHERE c.active = 1";
687
		$sql .= " AND c.entity = " . $conf->entity;
688
		$sql .= " AND (c.fk_country = ".$mysoc->country_id." OR c.fk_country = 0)";
689
		$sql .= " AND cat.rowid = t.fk_accounting_category";
690
		$sql .= " AND t.entity = " . $conf->entity;
691
		$sql .= " ORDER BY cat.position ASC";
692
693
		$resql = $this->db->query($sql);
694
		if ($resql) {
695
			$i = 0;
696
			$obj = '';
697
			$num = $this->db->num_rows($resql);
698
			$data = array ();
699
			if ($num) {
700
				while ( $obj = $this->db->fetch_object($resql) ) {
701
					$name_cat = $obj->name_cat;
702
					$data[$name_cat][$i] = array (
703
							'id' => $obj->rowid,
704
							'code' => $obj->code,
705
							'position' => $obj->position,
706
							'account_number' => $obj->account_number,
707
							'account_label' => $obj->account_label,
708
							'sens' => $obj->sens
709
					);
710
					$i ++;
711
				}
712
			}
713
			return $data;
714
		} else {
715
			$this->error = "Error " . $this->db->lasterror();
716
			dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR);
717
718
			return -1;
719
		}
720
	}
721
722
	/**
723
	 * Function to show result of an accounting account from the ledger with a direction and a period
724
	 *
725
	 * @param int|array	$cpt 				Accounting account or array of accounting account
726
	 * @param string 	$date_start			Date start
727
	 * @param string 	$date_end			Date end
728
	 * @param int 		$sens 				Sens of the account:  0: credit - debit (use this by default), 1: debit - credit
729
	 * @param string	$thirdparty_code	Thirdparty code
730
	 * @param int       $month 				Specifig month - Can be empty
731
	 * @param int       $year 				Specifig year - Can be empty
732
	 * @return integer 						<0 if KO, >= 0 if OK
733
	 */
734
	public function getSumDebitCredit($cpt, $date_start, $date_end, $sens, $thirdparty_code = 'nofilter', $month = 0, $year = 0)
735
	{
736
		global $conf;
737
738
		$this->sdc = 0;
739
		$this->sdcpermonth = array();
740
741
		$sql = "SELECT SUM(t.debit) as debit, SUM(t.credit) as credit";
742
		if (is_array($cpt)) $sql.=", t.numero_compte as accountancy_account";
743
		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping as t";
744
		//if (in_array($this->db->type, array('mysql', 'mysqli'))) $sql.=' USE INDEX idx_accounting_bookkeeping_doc_date';
745
		$sql .= " WHERE t.entity = ".$conf->entity;
746
		if (is_array($cpt))
747
		{
748
			$listofaccount='';
749
			foreach($cpt as $cptcursor)
750
			{
751
				if ($listofaccount) $listofaccount.=",";
752
				$listofaccount.="'".$cptcursor."'";
753
			}
754
			$sql .= " AND t.numero_compte IN (" .$listofaccount. ")";
755
		}
756
		else
757
		{
758
			$sql .= " AND t.numero_compte = '" . $this->db->escape($cpt) . "'";
759
		}
760
		if (! empty($date_start) && ! empty($date_end) && (empty($month) || empty($year)))	// If month/year provided, it is stronger than filter date_start/date_end
761
			$sql .= " AND (t.doc_date BETWEEN '".$this->db->idate($date_start)."' AND '".$this->db->idate($date_end)."')";
762
		if (! empty($month) && ! empty($year)) {
763
			$sql .= " AND (t.doc_date BETWEEN '".$this->db->idate(dol_get_first_day($year, $month))."' AND '".$this->db->idate(dol_get_last_day($year, $month))."')";
764
		}
765
		if ($thirdparty_code != 'nofilter')
766
		{
767
			$sql .= " AND t.thirdparty_code = '".$this->db->escape($thirdparty_code)."'";
768
		}
769
		if (is_array($cpt)) $sql.=" GROUP BY t.numero_compte";
770
		//print $sql;
771
772
		$resql = $this->db->query($sql);
773
		if ($resql)
774
		{
775
			$num = $this->db->num_rows($resql);
776
			if ($num)
777
			{
778
				$obj = $this->db->fetch_object($resql);
779
				if ($sens == 1) {
780
					$this->sdc = $obj->debit - $obj->credit;
781
				} else {
782
					$this->sdc = $obj->credit - $obj->debit;
783
				}
784
				if (is_array($cpt))
785
				{
786
					$this->sdcperaccount[$obj->accountancy_account] = $this->sdc;
787
				}
788
			}
789
			return $num;
790
		} else {
791
			$this->error = "Error " . $this->db->lasterror();
792
			$this->errors[] = $this->error;
793
			dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR);
794
			return -1;
795
		}
796
	}
797
798
	/**
799
	 * Return list of personalized groups that are active
800
	 *
801
	 * @param	int			$categorytype		-1=All, 0=Only non computed groups, 1=Only computed groups
802
	 * @return	array|int						Array of groups or -1 if error
803
	 */
804
	public function getCats($categorytype = -1)
805
	{
806
		global $conf, $mysoc;
807
808
		if (empty($mysoc->country_id)) {
809
			dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined');
810
			exit();
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
811
		}
812
813
		$sql = "SELECT c.rowid, c.code, c.label, c.formula, c.position, c.category_type, c.sens";
814
		$sql .= " FROM " . MAIN_DB_PREFIX . "c_accounting_category as c";
815
		$sql .= " WHERE c.active = 1";
816
		$sql .= " AND c.entity = " . $conf->entity;
817
		if ($categorytype >= 0) $sql.=" AND c.category_type = 1";
818
		$sql .= " AND (c.fk_country = ".$mysoc->country_id." OR c.fk_country = 0)";
819
		$sql .= " ORDER BY c.position ASC";
820
821
		$resql = $this->db->query($sql);
822
		if ($resql) {
823
			$i = 0;
824
			$obj = '';
825
			$num = $this->db->num_rows($resql);
826
			$data = array ();
827
			if ($num) {
828
				while ( $i < $num ) {
829
					$obj = $this->db->fetch_object($resql);
830
831
					$data[] = array (
832
							'rowid' => $obj->rowid,
833
							'code' => $obj->code,
834
							'label' => $obj->label,
835
							'formula' => $obj->formula,
836
							'position' => $obj->position,
837
							'category_type' => $obj->category_type,
838
					        'bc' => $obj->sens
839
					);
840
					$i++;
841
				}
842
			}
843
			return $data;
844
		} else {
845
			$this->error = "Error " . $this->db->lasterror();
846
			$this->errors[] = $this->error;
847
			dol_syslog(__METHOD__ . " " . implode(',', $this->errors), LOG_ERR);
848
849
			return - 1;
850
		}
851
	}
852
853
854
	/**
855
	 * Get all accounting account of a group.
856
	 * You must choose between first parameter (personalized group) or the second (free criteria filter)
857
	 *
858
	 * @param 	int 		$cat_id 				Id if personalized accounting group/category
859
	 * @param 	string 		$predefinedgroupwhere 	Sql criteria filter to select accounting accounts
860
	 * @return 	array|int							Array of accounting accounts or -1 if error
861
	 */
862
	public function getCptsCat($cat_id, $predefinedgroupwhere = '')
863
	{
864
		global $conf, $mysoc;
865
		$sql = '';
866
867
		if (empty($mysoc->country_id) && empty($mysoc->country_code)) {
868
			dol_print_error('', 'Call to select_accounting_account with mysoc country not yet defined');
869
			exit();
1 ignored issue
show
Best Practice introduced by
Using exit here is not recommended.

In general, usage of exit should be done with care and only when running in a scripting context like a CLI script.

Loading history...
870
		}
871
872
		if (! empty($cat_id))
873
		{
874
			$sql = "SELECT t.rowid, t.account_number, t.label as account_label";
875
			$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t";
876
			$sql .= " WHERE t.fk_accounting_category = ".$cat_id;
877
			$sql .= " AND t.entity = " . $conf->entity;
878
			$sql .= " ORDER BY t.account_number";
879
		}
880
		else
881
		{
882
			$sql = "SELECT t.rowid, t.account_number, t.label as account_label";
883
			$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as t";
884
			$sql .= " WHERE ".$predefinedgroupwhere;
885
			$sql .= " AND t.entity = " . $conf->entity;
886
			$sql .= " ORDER BY t.account_number";
887
		}
888
		//echo $sql;
889
890
		$resql = $this->db->query($sql);
891
		if ($resql) {
892
			$i = 0;
893
			$obj = '';
894
			$num = $this->db->num_rows($resql);
895
			$data = array();
896
			if ($num) {
897
				while ($obj = $this->db->fetch_object($resql))
898
				{
899
					$data[] = array (
900
							'id' => $obj->rowid,
901
							'account_number' => $obj->account_number,
902
							'account_label' => $obj->account_label,
903
					);
904
					$i++;
905
				}
906
			}
907
			return $data;
908
		} else {
909
			$this->error = "Error " . $this->db->lasterror();
910
			dol_syslog(__METHOD__ . " " . $this->error, LOG_ERR);
911
912
			return -1;
913
		}
914
	}
915
}
916