Completed
Branch develop (59ab9a)
by
unknown
27:43
created

FormAccounting::select_journal()   C

Complexity

Conditions 10
Paths 4

Size

Total Lines 67
Code Lines 37

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 10
eloc 37
nc 4
nop 9
dl 0
loc 67
rs 6.1506
c 0
b 0
f 0

How to fix   Long Method    Complexity    Many Parameters   

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:

Many Parameters

Methods with many parameters are not only hard to understand, but their parameters also often become inconsistent when you need more, or different data.

There are several approaches to avoid long parameter lists:

1
<?php
2
/* Copyright (C) 2013-2016 Florian Henry        <[email protected]>
3
 * Copyright (C) 2013-2014 Olivier Geffroy      <[email protected]>
4
 * Copyright (C) 2015      Ari Elbaz (elarifr)  <[email protected]>
5
 * Copyright (C) 2016      Marcos García        <[email protected]>
6
 * Copyright (C) 2016-2017 Alexandre Spangaro   <[email protected]>
7
 *
8
 * This program is free software; you can redistribute it and/or modify
9
 * it under the terms of the GNU General Public License as published by
10
 * the Free Software Foundation; either version 3 of the License, or
11
 * (at your option) any later version.
12
 *
13
 * This program is distributed in the hope that it will be useful,
14
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16
 * GNU General Public License for more details.
17
 *
18
 * You should have received a copy of the GNU General Public License
19
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
20
 */
21
22
/**
23
 *	\file       htdocs/core/class/html.formaccounting.class.php
24
 *  \ingroup    Advanced accountancy
25
 *	\brief      File of class with all html predefined components
26
 */
27
28
29
/**
30
 *	Class to manage generation of HTML components for accounting management
31
 */
32
class FormAccounting extends Form
33
{
34
35
	private $options_cache = array();
36
37
	var $db;
38
	var $error;
39
40
	/**
41
	* Constructor
42
	*
43
	* @param		DoliDB		$db      Database handler
44
	*/
45
	public function __construct($db)
46
	{
47
	    $this->db = $db;
48
	}
49
50
	/**
51
	 * Return list of journals with label by nature
52
	 *
53
	 * @param	string	$selectid	Preselected pcg_type
54
	 * @param	string	$htmlname	Name of field in html form
55
	 * @param	int		$nature		Limit the list to a particular type of journals (1:various operations / 2:sale / 3:purchase / 4:bank / 9: has-new)
56
	 * @param	int		$showempty	Add an empty field
57
	 * @param	array	$event		Event options
58
	 * @param	int		$select_in	0=selectid value is the journal rowid (default) or 1=selectid is journal code
59
	 * @param	int		$select_out	Set value returned by select. 0=rowid (default), 1=code
60
	 * @param	string	$morecss	More css non HTML object
61
	 * @param	string	$usecache	Key to use to store result into a cache. Next call with same key will reuse the cache.
62
	 *
63
	 * @return	string				String with HTML select
64
	 */
65
	function select_journal($selectid, $htmlname = 'journal', $nature=0, $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='')
66
	{
67
		global $conf;
68
69
		$out = '';
70
71
    	$options = array();
72
		if ($usecache && ! empty($this->options_cache[$usecache]))
73
		{
74
		    $options = $this->options_cache[$usecache];
75
		    $selected=$selectid;
76
		}
77
		else
78
		{
79
			$sql = "SELECT rowid, code, label, nature, entity, active";
80
			$sql.= " FROM " . MAIN_DB_PREFIX . "accounting_journal";
81
			$sql.= " WHERE active = 1";
82
			$sql.= " AND entity = ".$conf->entity;
83
			//if ($nature && is_numeric($nature))   $sql .= " AND nature = ".$nature;
84
			$sql.= " ORDER BY code";
85
86
			dol_syslog(get_class($this) . "::select_journal", LOG_DEBUG);
87
			$resql = $this->db->query($sql);
88
89
			if (!$resql) {
90
				$this->error = "Error ".$this->db->lasterror();
91
				dol_syslog(get_class($this)."::select_journal ".$this->error, LOG_ERR);
92
				return -1;
93
			}
94
95
			$out = ajax_combobox($htmlname, $event);
96
97
    		$selected = 0;
98
			while ($obj = $this->db->fetch_object($resql))
99
			{
100
				$label = $obj->code . ' - ' . $obj->label;
101
102
    			$select_value_in = $obj->rowid;
103
				$select_value_out = $obj->rowid;
104
105
				// Try to guess if we have found default value
106
    			if ($select_in == 1) {
107
    				$select_value_in = $obj->code;
108
    			}
109
    			if ($select_out == 1) {
110
    				$select_value_out = $obj->code;
111
    			}
112
    			// Remember guy's we store in database llx_accounting_bookkeeping the code of accounting_journal and not the rowid
113
    			if ($selectid != '' && $selectid == $select_value_in) {
114
    			    //var_dump("Found ".$selectid." ".$select_value_in);
115
    				$selected = $select_value_out;
116
    			}
117
118
				$options[$select_value_out] = $label;
119
			}
120
			$this->db->free($resql);
121
122
			if ($usecache)
123
			{
124
				$this->options_cache[$usecache] = $options;
125
			}
126
		}
127
128
		$out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1);
129
130
		return $out;
131
	}
132
133
    /**
134
     *	Return list of accounting category.
135
     * 	Use mysoc->country_id or mysoc->country_code so they must be defined.
136
     *
137
     *	@param	string	$selected       Preselected type
138
     *	@param  string	$htmlname       Name of field in form
139
     * 	@param	int		$useempty		Set to 1 if we want an empty value
140
     * 	@param	int		$maxlen			Max length of text in combo box
141
     * 	@param	int		$help			Add or not the admin help picto
142
     *  @param  int     $allcountries   All countries
143
     * 	@return	void
144
     */
145
    function select_accounting_category($selected='',$htmlname='account_category', $useempty=0, $maxlen=0, $help=1, $allcountries=0)
146
    {
147
        global $db,$langs,$user,$mysoc;
148
149
        if (empty($mysoc->country_id) && empty($mysoc->country_code) && empty($allcountries))
150
        {
151
            dol_print_error('','Call to select_accounting_account with mysoc country not yet defined');
152
            exit;
153
        }
154
155
        if (! empty($mysoc->country_id))
156
        {
157
            $sql = "SELECT c.rowid, c.label as type, c.range_account";
158
            $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c";
159
            $sql.= " WHERE c.active = 1";
160
			$sql.= " AND c.category_type = 0";
161
            if (empty($allcountries)) $sql.= " AND c.fk_country = ".$mysoc->country_id;
162
            $sql.= " ORDER BY c.label ASC";
163
        }
164
        else
165
        {
166
            $sql = "SELECT c.rowid, c.label as type, c.range_account";
167
            $sql.= " FROM ".MAIN_DB_PREFIX."c_accounting_category as c, ".MAIN_DB_PREFIX."c_country as co";
168
            $sql.= " WHERE c.active = 1";
169
			$sql.= " AND c.category_type = 0";
170
			$sql.= " AND c.fk_country = co.rowid";
171
            if (empty($allcountries)) $sql.= " AND co.code = '".$mysoc->country_code."'";
172
            $sql.= " ORDER BY c.label ASC";
173
        }
174
175
        dol_syslog(get_class($this).'::'.__METHOD__, LOG_DEBUG);
176
        $resql=$db->query($sql);
177
        if ($resql)
178
        {
179
            $num = $db->num_rows($resql);
180
            if ($num)
181
            {
182
                $out = '<select class="flat minwidth200" id="'.$htmlname.'" name="'.$htmlname.'">';
183
                $i = 0;
184
185
                if ($useempty) $out.= '<option value="0">&nbsp;</option>';
186
                while ($i < $num)
187
                {
188
                    $obj = $db->fetch_object($resql);
189
                    $out .= '<option value="'.$obj->rowid.'"';
190
                    if ($obj->rowid == $selected) $out .= ' selected';
191
                    $out .= '>'.($maxlen ? dol_trunc($obj->type,$maxlen) : $obj->type);
192
					$out .= ' ('.$obj->range_account.')';
193
                    $i++;
194
                }
195
                $out .=  '</select>';
196
                //if ($user->admin && $help) $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFromDictionarySetup"),1);
197
            }
198
            else
199
            {
200
                $out .= $langs->trans("ErrorNoAccountingCategoryForThisCountry",$mysoc->country_code);
0 ignored issues
show
Bug introduced by
The variable $out seems only to be defined at a later point. Did you maybe move this code here without moving the variable definition?

This error can happen if you refactor code and forget to move the variable initialization.

Let’s take a look at a simple example:

function someFunction() {
    $x = 5;
    echo $x;
}

The above code is perfectly fine. Now imagine that we re-order the statements:

function someFunction() {
    echo $x;
    $x = 5;
}

In that case, $x would be read before it is initialized. This was a very basic example, however the principle is the same for the found issue.

Loading history...
201
            }
202
        }
203
        else
204
        {
205
            dol_print_error($db,$db->lasterror());
206
        }
207
        
208
        $out .= ajax_combobox($htmlname, $event);
0 ignored issues
show
Bug introduced by
The variable $out does not seem to be defined for all execution paths leading up to this point.

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

Let’s take a look at an example:

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

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

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

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

Available Fixes

  1. Check for existence of the variable explicitly:

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

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

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $event does not exist. Did you forget to declare it?

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

Loading history...
209
        
210
        print $out;
211
    }
212
213
	/**
214
	 * Return select filter with date of transaction
215
	 *
216
	 * @param string $htmlname Name of select field
217
	 * @param string $selectedkey Value
218
	 * @return string HTML edit field
219
	 */
220
	function select_bookkeeping_importkey($htmlname = 'importkey', $selectedkey = '') {
221
		$options = array();
222
223
		$sql = 'SELECT DISTINCT import_key from ' . MAIN_DB_PREFIX . 'accounting_bookkeeping';
224
	    $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")";
225
		$sql .= ' ORDER BY import_key DESC';
226
227
		dol_syslog(get_class($this) . "::select_bookkeeping_importkey", LOG_DEBUG);
228
		$resql = $this->db->query($sql);
229
230
		if (!$resql) {
231
			$this->error = "Error " . $this->db->lasterror();
232
			dol_syslog(get_class($this) . "::select_bookkeeping_importkey " . $this->error, LOG_ERR);
233
			return - 1;
234
		}
235
236
		while ($obj = $this->db->fetch_object($resql)) {
237
			$options[$obj->import_key] = dol_print_date($obj->import_key, 'dayhourtext');
238
		}
239
240
		return Form::selectarray($htmlname, $options, $selectedkey);
241
	}
242
243
	/**
244
	 * Return list of accounts with label by chart of accounts
245
	 *
246
	 * @param string   $selectid           Preselected id or code of accounting accounts (depends on $select_in)
247
	 * @param string   $htmlname           Name of field in html form
248
	 * @param int      $showempty          Add an empty field
249
	 * @param array    $event              Event options
250
	 * @param int      $select_in          0=selectid value is a aa.rowid (default) or 1=selectid is aa.account_number
251
	 * @param int      $select_out         Set value returned by select. 0=rowid (default), 1=account_number
252
	 * @param string   $morecss            More css non HTML object
253
	 * @param string   $usecache           Key to use to store result into a cache. Next call with same key will reuse the cache.
254
	 * @return string                      String with HTML select
255
	 */
256
	function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $morecss='maxwidth300 maxwidthonsmartphone', $usecache='')
257
	{
258
		global $conf;
259
260
		require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
261
262
		$out = '';
263
		
264
    	$options = array();
265
		if ($usecache && ! empty($this->options_cache[$usecache]))
266
		{
267
		    $options = $this->options_cache[$usecache];
268
		    $selected=$selectid;
269
		}
270
		else
271
		{
272
    		$trunclength = defined('ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT') ? $conf->global->ACCOUNTING_LENGTH_DESCRIPTION_ACCOUNT : 50;
273
274
    		$sql = "SELECT DISTINCT aa.account_number, aa.label, aa.rowid, aa.fk_pcg_version";
275
    		$sql .= " FROM " . MAIN_DB_PREFIX . "accounting_account as aa";
276
    		$sql .= " INNER JOIN " . MAIN_DB_PREFIX . "accounting_system as asy ON aa.fk_pcg_version = asy.pcg_version";
277
    		$sql .= " AND asy.rowid = " . $conf->global->CHARTOFACCOUNTS;
278
    		$sql .= " AND aa.active = 1";
279
    		$sql .= " ORDER BY aa.account_number";
280
281
    		dol_syslog(get_class($this) . "::select_account", LOG_DEBUG);
282
    		$resql = $this->db->query($sql);
283
284
    		if (!$resql) {
285
    			$this->error = "Error " . $this->db->lasterror();
286
    			dol_syslog(get_class($this) . "::select_account " . $this->error, LOG_ERR);
287
    			return -1;
288
    		}
289
290
    		$out .= ajax_combobox($htmlname, $event);
291
292
    		$selected = 0;
293
    		while ($obj = $this->db->fetch_object($resql))
294
    		{
295
    			$label = length_accountg($obj->account_number) . ' - ' . $obj->label;
296
    			$label = dol_trunc($label, $trunclength);
297
298
    			$select_value_in = $obj->rowid;
299
    			$select_value_out = $obj->rowid;
300
301
    			// Try to guess if we have found default value
302
    			if ($select_in == 1) {
303
    				$select_value_in = $obj->account_number;
304
    			}
305
    			if ($select_out == 1) {
306
    				$select_value_out = $obj->account_number;
307
    			}
308
    			// Remember guy's we store in database llx_facturedet the rowid of accounting_account and not the account_number
309
    			// Because same account_number can be share between different accounting_system and do have the same meaning
310
    			if ($selectid != '' && $selectid == $select_value_in) {
311
    			    //var_dump("Found ".$selectid." ".$select_value_in);
312
    				$selected = $select_value_out;
313
    			}
314
315
    			$options[$select_value_out] = $label;
316
    		}
317
    		$this->db->free($resql);
318
319
    		if ($usecache)
320
    		{
321
                $this->options_cache[$usecache] = $options;
322
    		}
323
		}
324
325
		$out .= Form::selectarray($htmlname, $options, $selected, $showempty, 0, 0, '', 0, 0, 0, '', $morecss, 1);
326
327
		return $out;
328
	}
329
330
	/**
331
	 * Return list of auxilary thirdparty accounts
332
	 *
333
	 * @param string $selectid Preselected pcg_type
334
	 * @param string $htmlname Name of field in html form
335
	 * @param int $showempty Add an empty field
336
	 * @param array $event Event options
337
	 *
338
	 * @return string String with HTML select
339
	 */
340
	function select_auxaccount($selectid, $htmlname = 'account_num_aux', $showempty = 0, $event = array()) {
341
342
		$aux_account = array();
343
344
		// Auxiliary customer account
345
		$sql = "SELECT DISTINCT code_compta, nom ";
346
		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
347
	    $sql .= " WHERE entity IN (" . getEntity("societe", 1) . ")";
348
		$sql .= " ORDER BY code_compta";
349
		dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
350
		$resql = $this->db->query($sql);
351
		if ($resql) {
352
			while ($obj = $this->db->fetch_object($resql)) {
353
				if (!empty($obj->code_compta)) {
354
					$aux_account[$obj->code_compta] = $obj->code_compta.' ('.$obj->nom.')';
355
				}
356
			}
357
		} else {
358
			$this->error = "Error ".$this->db->lasterror();
359
			dol_syslog(get_class($this)."::select_pcgsubtype ".$this->error, LOG_ERR);
360
			return -1;
361
		}
362
		$this->db->free($resql);
363
364
		// Auxiliary supplier account
365
		$sql = "SELECT DISTINCT code_compta_fournisseur, nom ";
366
		$sql .= " FROM ".MAIN_DB_PREFIX."societe";
367
		$sql .= " WHERE entity IN (" . getEntity("societe", 1) . ")";
368
		$sql .= " ORDER BY code_compta_fournisseur";
369
		dol_syslog(get_class($this)."::select_auxaccount", LOG_DEBUG);
370
		$resql = $this->db->query($sql);
371
		if ($resql) {
372
			while ($obj = $this->db->fetch_object($resql)) {
373
				if (!empty($obj->code_compta_fournisseur)) {
374
					$aux_account[$obj->code_compta_fournisseur] = $obj->code_compta_fournisseur.' ('.$obj->nom.')';
375
				}
376
			}
377
		} else {
378
			$this->error = "Error ".$this->db->lasterror();
379
			dol_syslog(get_class($this)."::select_pcgsubtype ".$this->error, LOG_ERR);
380
			return -1;
381
		}
382
		$this->db->free($resql);
383
384
		// Build select
385
		$out = ajax_combobox($htmlname, $event);
386
		$out .= Form::selectarray($htmlname, $aux_account, $selectid, $showempty, 0, 0, '', 0, 0, 0, '', 'maxwidth300');
387
388
		return $out;
389
	}
390
391
	/**
392
	 * Return HTML combo list of years existing into book keepping
393
	 *
394
	 * @param string $selected Preselected value
395
	 * @param string $htmlname Name of HTML select object
396
	 * @param int $useempty Affiche valeur vide dans liste
397
	 * @param string $output_format (html/opton (for option html only)/array (to return options arrays
398
	 * @return string/array
399
	 */
400
	function selectyear_accountancy_bookkepping($selected = '', $htmlname = 'yearid', $useempty = 0, $output_format = 'html')
401
	{
402
	    global $conf;
403
404
		$out_array = array();
405
406
		$sql = "SELECT DISTINCT date_format(doc_date,'%Y') as dtyear";
407
		$sql .= " FROM ".MAIN_DB_PREFIX."accounting_bookkeeping";
408
	    $sql .= " WHERE entity IN (" . getEntity("accountancy", 1) . ")";
409
		$sql .= " ORDER BY date_format(doc_date,'%Y')";
410
		dol_syslog(get_class($this)."::".__METHOD__, LOG_DEBUG);
411
		$resql = $this->db->query($sql);
412
413
		if (!$resql) {
414
			$this->error = "Error ".$this->db->lasterror();
415
			dol_syslog(get_class($this)."::".__METHOD__.$this->error, LOG_ERR);
416
			return -1;
417
		}
418
		while ($obj = $this->db->fetch_object($resql)) {
419
			$out_array[$obj->dtyear] = $obj->dtyear;
420
		}
421
		$this->db->free($resql);
422
423
		if ($output_format == 'html') {
424
			return Form::selectarray($htmlname, $out_array, $selected, $useempty, 0, 0, 'placeholder="aa"');
425
		} else {
426
			return $out_array;
427
		}
428
	}
429
}
430
431