Passed
Push — EXTRACT_CLASSES ( 231cec...0382f2 )
by Rafael
65:54 queued 05:18
created

fetchDeprecationOptions()   F

Complexity

Conditions 19
Paths 780

Size

Total Lines 64
Code Lines 42

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 19
eloc 42
nc 780
nop 2
dl 0
loc 64
rs 0.6555
c 0
b 0
f 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
3
/* Copyright (C) 2021       Open-Dsi                    <[email protected]>
4
 * Copyright (C) 2024		MDW							<[email protected]>
5
 * Copyright (C) 2024       Rafael San José             <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19
 */
20
21
namespace Dolibarr\Code\Asset\Classes;
22
23
/**
24
 * \file        asset/class/assetdepreciationoptions.class.php
25
 * \ingroup     asset
26
 * \brief       This file is a class file for AssetDepreciationOptions
27
 */
28
29
use Dolibarr\Core\Base\CommonObject;
30
31
/**
32
 * Class for AssetDepreciationOptions
33
 */
34
class AssetDepreciationOptions extends CommonObject
35
{
36
    /**
37
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
38
     */
39
    public $table_element = '';
40
41
    /**
42
     *  'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
43
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
44
     *  'label' the translation key.
45
     *  'picto' is code of a picto to show before value in forms
46
     *  'enabled' is a condition when the field must be managed (Example: 1 or 'getDolGlobalString("MY_SETUP_PARAM")'
47
     *  'position' is the sort order of field.
48
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
49
     *  '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)
50
     *  'noteditable' says if field is not editable (1 or 0)
51
     *  '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.
52
     *  'index' if we want an index in database.
53
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommended to name the field fk_...).
54
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
55
     *  'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
56
     *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
57
     *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
58
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
59
     *  '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.
60
     *  'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
61
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
62
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
63
     *  'validate' is 1 if need to validate with $this->validateField()
64
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
65
     *  'enabled_field' if the mode block or a field is enabled if another field equal a value (="mode_key:field_key:value")
66
     *  'only_on_asset' is 1 if only a field on a asset
67
     *
68
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
69
     */
70
71
    /**
72
     * @var array<string,array{type:string,label:string,enabled:int<0,2>|string,position:int,notnull?:int,visible:int,noteditable?:int,default?:string,index?:int,foreignkey?:string,searchall?:int,isameasure?:int,css?:string,csslist?:string,help?:string,showoncombobox?:int,disabled?:int,arrayofkeyval?:array<int,string>,comment?:string}>  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
0 ignored issues
show
Documentation Bug introduced by
The doc comment array<string,array{type:...ring>,comment?:string}> at position 16 could not be parsed: Expected '}' at position 16, but found 'int'.
Loading history...
73
     */
74
    public $fields = array();
75
76
    /**
77
     * @var array  Array with all deprecation options info by mode.
78
     *  Note : economic mode is mandatory and is the primary options
79
     */
80
    public $deprecation_options_fields = array(
81
        'economic' => array(
82
            'label' => 'AssetDepreciationOptionEconomic',
83
            'table' => 'asset_depreciation_options_economic',
84
            'fields' => array(
85
                'depreciation_type' => array('type' => 'smallint', 'label' => 'AssetDepreciationOptionDepreciationType', 'enabled' => '1', 'position' => 10, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'arrayofkeyval' => array('0' => 'AssetDepreciationOptionDepreciationTypeLinear', '1' => 'AssetDepreciationOptionDepreciationTypeDegressive', '2' => 'AssetDepreciationOptionDepreciationTypeExceptional'), 'validate' => '1',),
86
                'degressive_coefficient' => array('type' => 'double(24,8)', 'label' => 'AssetDepreciationOptionDegressiveRate', 'enabled' => '1', 'position' => 20, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1','enabled_field' => 'economic:depreciation_type:1'),
87
                'duration' => array('type' => 'integer', 'label' => 'AssetDepreciationOptionDuration', 'enabled' => '1', 'position' => 30, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1',),
88
                'duration_type' => array('type' => 'smallint', 'label' => 'AssetDepreciationOptionDurationType', 'enabled' => '1', 'position' => 40, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'arrayofkeyval' => array('0' => 'AssetDepreciationOptionDurationTypeAnnual', '1' => 'AssetDepreciationOptionDurationTypeMonthly'/*, '2'=>'AssetDepreciationOptionDurationTypeDaily'*/), 'validate' => '1',),
89
                'rate' => array('type' => 'double(24,8)', 'label' => 'AssetDepreciationOptionRate', 'enabled' => '1', 'position' => 50, 'visible' => 3, 'default' => '0', 'isameasure' => '1', 'validate' => '1', 'computed' => '$object->asset_depreciation_options->getRate("economic")',),
90
                'accelerated_depreciation_option' => array('type' => 'boolean', 'label' => 'AssetDepreciationOptionAcceleratedDepreciation', 'enabled' => '1', 'position' => 60, 'column_break' => true, 'notnull' => 0, 'default' => '0', 'visible' => 1, 'validate' => '1',),
91
                'amount_base_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDepreciationHT', 'enabled' => 'isset($object)&&get_class($object)=="Asset"', 'only_on_asset' => 1, 'position' => 90, 'notnull' => 0, 'required' => 1, 'visible' => 1, 'default' => '$object->reversal_amount_ht > 0 ? $object->reversal_amount_ht : $object->acquisition_value_ht', 'isameasure' => '1', 'validate' => '1',),
92
                'amount_base_deductible_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDeductibleHT', 'enabled' => 'isset($object)&&get_class($object)=="Asset"', 'only_on_asset' => 1, 'position' => 100, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1',),
93
                'total_amount_last_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionTotalAmountLastDepreciationHT', 'enabled' => 'isset($object)&&get_class($object)=="Asset"', 'only_on_asset' => 1, 'position' => 110, 'noteditable' => 1, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1',),
94
            ),
95
        ),
96
        'accelerated_depreciation' => array(
97
            'label' => 'AssetDepreciationOptionAcceleratedDepreciation',
98
            'table' => 'asset_depreciation_options_fiscal',
99
            'enabled_field' => 'economic:accelerated_depreciation_option:1',
100
            'fields' => array(
101
                'depreciation_type' => array('type' => 'smallint', 'label' => 'AssetDepreciationOptionDepreciationType', 'enabled' => '1', 'position' => 10, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'arrayofkeyval' => array('0' => 'AssetDepreciationOptionDepreciationTypeLinear', '1' => 'AssetDepreciationOptionDepreciationTypeDegressive', '2' => 'AssetDepreciationOptionDepreciationTypeExceptional'), 'validate' => '1',),
102
                'degressive_coefficient' => array('type' => 'double(24,8)', 'label' => 'AssetDepreciationOptionDegressiveRate', 'enabled' => '1', 'position' => 20, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1','enabled_field' => 'accelerated_depreciation:depreciation_type:1'),
103
                'duration' => array('type' => 'integer', 'label' => 'AssetDepreciationOptionDuration', 'enabled' => '1', 'position' => 30, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1',),
104
                'duration_type' => array('type' => 'smallint', 'label' => 'AssetDepreciationOptionDurationType', 'enabled' => '1', 'position' => 40, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'arrayofkeyval' => array('0' => 'AssetDepreciationOptionDurationTypeAnnual', '1' => 'AssetDepreciationOptionDurationTypeMonthly'/*, '2'=>'AssetDepreciationOptionDurationTypeDaily'*/), 'validate' => '1',),
105
                'rate' => array('type' => 'double(24,8)', 'label' => 'AssetDepreciationOptionRate', 'enabled' => '1', 'position' => 50, 'visible' => 3, 'default' => '0', 'isameasure' => '1', 'validate' => '1', 'computed' => '$object->asset_depreciation_options->getRate("accelerated_depreciation")',),
106
                'amount_base_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDepreciationHT', 'enabled' => 'isset($object)&&get_class($object)=="Asset"', 'only_on_asset' => 1, 'position' => 80, 'column_break' => true, 'notnull' => 0, 'required' => 1, 'visible' => 1, 'default' => '$object->reversal_amount_ht > 0 ? $object->reversal_amount_ht : $object->acquisition_value_ht', 'isameasure' => '1', 'validate' => '1',),
107
                'amount_base_deductible_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDeductibleHT', 'enabled' => 'isset($object)&&get_class($object)=="Asset"', 'only_on_asset' => 1, 'position' => 90, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1',),
108
                'total_amount_last_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionTotalAmountLastDepreciationHT', 'enabled' => 'isset($object)&&get_class($object)=="Asset"', 'only_on_asset' => 1, 'position' => 100, 'noteditable' => 1, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => '1', 'validate' => '1',),
109
            ),
110
        ),
111
    );
112
    public $fk_asset;
113
    public $fk_asset_model;
114
    public $fk_user_modif;
115
116
    /**
117
     * @var array  Array with all deprecation options by mode.
118
     */
119
    public $deprecation_options = array();
120
121
    public $depreciation_type;
122
    public $degressive_coefficient;
123
    public $duration;
124
    public $duration_type;
125
    public $accelerated_depreciation_option;
126
127
    /**
128
     * Constructor
129
     *
130
     * @param DoliDB $db Database handler
131
     */
132
    public function __construct(DoliDB $db)
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Asset\Classes\DoliDB was not found. Did you mean DoliDB? If so, make sure to prefix the type with \.
Loading history...
133
    {
134
        global $langs;
135
        $this->db = $db;
136
137
        // Translate some data of arrayofkeyval
138
        if (is_object($langs)) {
139
            foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
140
                if (!empty($mode_info['fields']) && is_array($mode_info['fields'])) {
141
                    foreach ($mode_info['fields'] as $field_key => $field_info) {
142
                        if (!empty($field_info['arrayofkeyval']) && is_array($field_info['arrayofkeyval'])) {
143
                            foreach ($field_info['arrayofkeyval'] as $key => $val) {
144
                                $this->deprecation_options_fields[$mode_key]['fields'][$field_key]['arrayofkeyval'][$key] = $langs->trans($val);
145
                            }
146
                        }
147
                    }
148
                }
149
            }
150
        }
151
    }
152
153
    /**
154
     *  Set object infos for a mode
155
     *
156
     * @param   string      $mode           Depreciation mode (economic, accelerated_depreciation, ...)
157
     * @param   int         $class_type     Type (0:asset, 1:asset model)
158
     * @param   bool        $all_field      Get all fields
159
     * @return  int                         Return integer <0 if KO, >0 if OK
160
     */
161
    public function setInfosForMode($mode, $class_type = 0, $all_field = false)
162
    {
163
        // Clean parameters
164
        $mode = strtolower(trim($mode));
165
166
        if (!empty($this->deprecation_options_fields[$mode])) {
167
            $this->table_element = $this->deprecation_options_fields[$mode]['table'];
168
            $this->fields = $this->deprecation_options_fields[$mode]['fields'];
169
            foreach ($this->fields as $field_key => $field_info) {
170
                if ((!empty($field_info['computed']) && !$all_field) || (!empty($field_info['only_on_asset']) && !empty($class_type))) {
171
                    unset($this->fields[$field_key]);
172
                    continue;
173
                }
174
175
                // Unset required option (notnull) if field disabled
176
                if (!empty($field_info['enabled_field'])) {
177
                    $info = explode(':', $field_info['enabled_field']);
178
                    if (!empty($this->deprecation_options[$info[0]][$info[1]]) && $this->deprecation_options[$info[0]][$info[1]] != $info[2] && isset($this->fields[$field_key]['notnull'])) {
179
                        unset($this->fields[$field_key]['notnull']);
180
                    }
181
                }
182
                // Set value of the field in the object (for createCommon and setDeprecationOptionsFromPost functions)
183
                $this->{$field_key} = $this->deprecation_options[$mode][$field_key] ?? null;
184
            }
185
186
            $this->fields['rowid'] = array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => '1', 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => '1', 'index' => 1, 'css' => 'left', 'comment' => "Id");
187
            if (empty($class_type)) {
188
                $this->fields['fk_asset'] = array('type' => 'integer:Asset:asset/class/asset.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__)', 'label' => 'Asset', 'enabled' => '1', 'position' => 0, 'notnull' => 0, 'visible' => 0, 'index' => 1, 'validate' => '1',);
189
            } else {
190
                $this->fields['fk_asset_model'] = array('type' => 'integer:AssetModel:asset/class/assetmodel.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__)', 'label' => 'AssetModel', 'enabled' => '1', 'position' => 0, 'notnull' => 0, 'visible' => 0, 'index' => 1, 'validate' => '1',);
191
            }
192
            $this->fields['tms'] = array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => '1', 'position' => 501, 'notnull' => 0, 'visible' => 0,);
193
            $this->fields['fk_user_modif'] = array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => '1', 'position' => 511, 'notnull' => -1, 'visible' => 0,);
194
        }
195
196
        return 1;
197
    }
198
199
    /**
200
     *  Fill deprecation_options property of object (using for data sent by forms)
201
     *
202
     * @param   int     $class_type     Type (0:asset, 1:asset model)
203
     * @return  int                     Return integer <0 if KO, >0 if OK
204
     */
205
    public function setDeprecationOptionsFromPost($class_type = 0)
206
    {
207
        global $conf, $langs;
208
209
        $error = 0;
210
211
        $deprecation_options = array();
212
        foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
213
            $this->setInfosForMode($mode_key, $class_type);
214
215
            foreach ($mode_info['fields'] as $field_key => $field_info) {
216
                if (!empty($field_info['computed'])) {
217
                    continue;
218
                }
219
220
                $html_name = $mode_key . '_' . $field_key;
221
                if ($field_info['type'] == 'duration') {
222
                    if (GETPOST($html_name . 'hour') == '' && GETPOST($html_name . 'min') == '') {
223
                        continue; // The field was not submitted to be saved
224
                    }
225
                } else {
226
                    if (!GETPOSTISSET($html_name)) {
227
                        continue; // The field was not submitted to be saved
228
                    }
229
                }
230
                // Ignore special fields
231
                if (in_array($field_key, array('rowid', 'entity', 'import_key'))) {
232
                    continue;
233
                }
234
                if (in_array($field_key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
235
                    if (!in_array(abs($field_info['visible']), array(1, 3))) {
236
                        continue; // Only 1 and 3 that are case to create
237
                    }
238
                }
239
240
                // Set value to insert
241
                if (in_array($field_info['type'], array('text', 'html'))) {
242
                    $value = GETPOST($html_name, 'restricthtml');
243
                } elseif ($field_info['type'] == 'date') {
244
                    $value = dol_mktime(12, 0, 0, GETPOSTINT($html_name . 'month'), GETPOSTINT($html_name . 'day'), GETPOSTINT($html_name . 'year')); // for date without hour, we use gmt
245
                } elseif ($field_info['type'] == 'datetime') {
246
                    $value = dol_mktime(GETPOSTINT($html_name . 'hour'), GETPOSTINT($html_name . 'min'), GETPOSTINT($html_name . 'sec'), GETPOSTINT($html_name . 'month'), GETPOSTINT($html_name . 'day'), GETPOSTINT($html_name . 'year'), 'tzuserrel');
247
                } elseif ($field_info['type'] == 'duration') {
248
                    $value = 60 * 60 * GETPOSTINT($html_name . 'hour') + 60 * GETPOSTINT($html_name . 'min');
249
                } elseif (preg_match('/^(integer|price|real|double)/', $field_info['type'])) {
250
                    $value = price2num(GETPOST($html_name, 'alphanohtml')); // To fix decimal separator according to lang setup
251
                } elseif ($field_info['type'] == 'boolean') {
252
                    $value = ((GETPOST($html_name) == '1' || GETPOST($html_name) == 'on') ? 1 : 0);
253
                } elseif ($field_info['type'] == 'reference') {
254
                    // todo to check
255
                    $tmparraykey = array(); //array_keys($object->param_list);
256
                    $value = $tmparraykey[GETPOST($html_name)] . ',' . GETPOST($html_name . '2');
257
                } else {
258
                    if ($field_key == 'lang') {
259
                        $value = GETPOST($html_name, 'aZ09') ? GETPOST($html_name, 'aZ09') : "";
260
                    } else {
261
                        $value = GETPOST($html_name, 'alphanohtml');
262
                    }
263
                }
264
                if (preg_match('/^integer:/i', $field_info['type']) && $value == '-1') {
265
                    $value = ''; // This is an implicit foreign key field
266
                }
267
                if (!empty($field_info['foreignkey']) && $value == '-1') {
268
                    $value = ''; // This is an explicit foreign key field
269
                }
270
271
                //var_dump($field_key.' '.$value.' '.$field_info['type']);
272
                $field_value = $value;
273
                if ($field_info['notnull'] > 0 && $field_value == '' && !is_null($field_info['default']) && $field_info['default'] == '(PROV)') {
274
                    $field_value = '(PROV)';
275
                } elseif ((!empty($field_info['required']) || $field_info['notnull'] > 0) && $field_value == '' && !empty($field_info['default'])) {
276
                    $field_value = $field_info['default'];
277
                }
278
                if ($field_info['notnull'] > 0 && $field_value == '' && is_null($field_info['default'])) {
279
                    $error++;
280
                    setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($field_info['label'])), null, 'errors');
281
                }
282
                $deprecation_options[$mode_key][$field_key] = $field_value;
283
284
                // Validation of fields values
285
                if (getDolGlobalInt('MAIN_FEATURE_LEVEL') >= 1 || getDolGlobalString('MAIN_ACTIVATE_VALIDATION_RESULT')) {
286
                    if (!$error && !empty($field_info['validate']) && is_callable(array($this, 'validateField'))) {
287
                        if (!$this->validateField($mode_info['fields'], $field_key, $value)) {
288
                            $error++;
289
                        }
290
                    }
291
                }
292
            }
293
        }
294
        // Unset not enabled modes
295
        foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
296
            if (!empty($mode_info['enabled_field'])) {
297
                $info = explode(':', $mode_info['enabled_field']);
298
                if ($deprecation_options[$info[0]][$info[1]] != $info[2]) {
299
                    unset($deprecation_options[$info[0]][$info[1]]);
300
                }
301
            }
302
        }
303
        $this->deprecation_options = $deprecation_options;
304
305
        if ($error) {
306
            return -1;
307
        } else {
308
            return 1;
309
        }
310
    }
311
312
    /**
313
     *  Load deprecation options of a asset or a asset model
314
     *
315
     * @param   int     $asset_id           Asset ID to set
316
     * @param   int     $asset_model_id     Asset model ID to set
317
     * @return  int                         Return integer <0 if KO, >0 if OK
318
     */
319
    public function fetchDeprecationOptions($asset_id = 0, $asset_model_id = 0)
320
    {
321
        global $langs, $hookmanager;
322
        dol_syslog(__METHOD__ . " asset_id=$asset_id, asset_model_id=$asset_model_id");
323
324
        $error = 0;
325
        $this->errors = array();
326
        $this->deprecation_options = array();
327
328
        // Clean parameters
329
        $asset_id = $asset_id > 0 ? $asset_id : 0;
330
        $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
331
332
        $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
333
        $parameters = array('asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
334
        $reshook = $hookmanager->executeHooks('fetchDepreciationOptions', $parameters, $this); // Note that $action and $object may have been modified by some hooks
335
        if (!empty($reshook)) {
336
            return $reshook;
337
        }
338
339
        // Check parameters
340
        if (empty($asset_id) && empty($asset_model_id)) {
341
            $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
342
            $error++;
343
        }
344
        if ($error) {
345
            dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
346
            return -1;
347
        }
348
349
        $class_type = $asset_id > 0 ? 0 : 1;
350
        $deprecation_options = array();
351
        foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
352
            $this->setInfosForMode($mode_key, $class_type);
353
354
            $result = $this->fetchCommon(0, '', " AND " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id));
355
            if ($result < 0) {
356
                $this->errors = array_merge(array($langs->trans('AssetErrorFetchDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
357
                $error++;
358
            } elseif ($result > 0) {
359
                foreach ($this->fields as $field_key => $field_info) {
360
                    if (in_array($field_key, array('rowid', 'fk_asset', 'fk_asset_model', 'tms', 'fk_user_modif'))) {
361
                        continue;
362
                    }
363
                    $deprecation_options[$mode_key][$field_key] = $this->{$field_key};
364
                }
365
            }
366
        }
367
        // Unset not enabled modes
368
        foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
369
            if (!empty($mode_info['enabled_field'])) {
370
                $info = explode(':', $mode_info['enabled_field']);
371
                if (isset($deprecation_options[$info[0]][$info[1]]) && $deprecation_options[$info[0]][$info[1]] != $info[2]) {
372
                    unset($deprecation_options[$info[0]][$info[1]]);
373
                }
374
            }
375
        }
376
377
        if ($error) {
378
            dol_syslog(__METHOD__ . " Error fetch accountancy codes: " . $this->errorsToString(), LOG_ERR);
379
            return -1;
380
        } else {
381
            $this->deprecation_options = $deprecation_options;
382
            return 1;
383
        }
384
    }
385
386
    /**
387
     *  get general depreciation info for a mode (used in depreciation card)
388
     *
389
     * @param   string          $mode       Depreciation mode (economic, accelerated_depreciation, ...)
390
     * @return  array|int                   Return integer <0 if KO otherwise array with general depreciation info
391
     */
392
    public function getGeneralDepreciationInfoForMode($mode)
393
    {
394
        global $hookmanager;
395
        dol_syslog(__METHOD__ . " mode=$mode");
396
397
        $this->errors = array();
398
399
        // Clean parameters
400
        $mode = strtolower(trim($mode));
401
402
        $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
403
        $parameters = array('mode' => $mode);
404
        $reshook = $hookmanager->executeHooks('getGeneralDepreciationInfoForMode', $parameters, $this); // Note that $action and $object may have been modified by some hooks
405
        if ($reshook < 0) {
406
            return $reshook;
407
        } elseif ($reshook > 0) {
408
            return $hookmanager->resArray;
409
        }
410
411
        $duration_type_list = $this->deprecation_options_fields[$mode]['fields']['duration_type']['arrayofkeyval'];
412
413
        return array(
414
            'base_depreciation_ht' => $this->deprecation_options[$mode]['amount_base_depreciation_ht'],
415
            'duration' => $this->deprecation_options[$mode]['duration'],
416
            'duration_type' => $duration_type_list[$this->deprecation_options[$mode]['duration_type']],
417
            'rate' => $this->getRate($mode),
418
        );
419
    }
420
421
    /**
422
     *  Update deprecation options of a asset or a asset model
423
     *
424
     * @param   User    $user               User making update
0 ignored issues
show
Bug introduced by
The type Dolibarr\Code\Asset\Classes\User was not found. Did you mean User? If so, make sure to prefix the type with \.
Loading history...
425
     * @param   int     $asset_id           Asset ID to set
426
     * @param   int     $asset_model_id     Asset model ID to set
427
     * @param   int     $notrigger          1=disable trigger UPDATE (when called by create)
428
     * @return  int                         Return integer <0 if KO, >0 if OK
429
     */
430
    public function updateDeprecationOptions($user, $asset_id = 0, $asset_model_id = 0, $notrigger = 0)
431
    {
432
        global $langs, $hookmanager;
433
        dol_syslog(__METHOD__ . " user_id=" . $user->id . ", asset_id=" . $asset_id . ", asset_model_id=" . $asset_model_id . ", notrigger=" . $notrigger);
434
435
        $error = 0;
436
        $this->errors = array();
437
438
        // Clean parameters
439
        $asset_id = $asset_id > 0 ? $asset_id : 0;
440
        $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
441
442
        $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
443
        $parameters = array('user' => $user, 'asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
444
        $reshook = $hookmanager->executeHooks('updateDepreciationOptions', $parameters, $this); // Note that $action and $object may have been modified by some hooks
445
        if (!empty($reshook)) {
446
            return $reshook;
447
        }
448
449
        // Check parameters
450
        if (empty($asset_id) && empty($asset_model_id)) {
451
            $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
452
            $error++;
453
        }
454
        if ($error) {
455
            dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
456
            return -1;
457
        }
458
459
        $this->db->begin();
460
461
        if ($asset_id > 0) {
462
            $this->fk_asset = $asset_id;
463
            $class_type = 0;
464
        } else {
465
            $this->fk_asset_model = $asset_model_id;
466
            $class_type = 1;
467
        }
468
        $this->tms = dol_now();
0 ignored issues
show
Deprecated Code introduced by
The property Dolibarr\Core\Base\CommonObject::$tms has been deprecated: Use $date_modification ( Ignorable by Annotation )

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

468
        /** @scrutinizer ignore-deprecated */ $this->tms = dol_now();

This property has been deprecated. The supplier of the class has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the property will be removed from the class and what other property to use instead.

Loading history...
469
        $this->fk_user_modif = $user->id;
470
471
        foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
472
            // Delete old accountancy codes
473
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . $mode_info['table'];
474
            $sql .= " WHERE " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id);
475
            $resql = $this->db->query($sql);
476
            if (!$resql) {
477
                $this->errors[] = $langs->trans('AssetErrorDeleteDepreciationOptionsForMode', $mode_key) . ': ' . $this->db->lasterror();
478
                $error++;
479
            }
480
481
            if (!$error && !empty($this->deprecation_options[$mode_key])) {
482
                if (!empty($mode_info['enabled_field'])) {
483
                    $info = explode(':', $mode_info['enabled_field']);
484
                    if ($this->deprecation_options[$info[0]][$info[1]] != $info[2]) {
485
                        continue;
486
                    }
487
                }
488
489
                $this->setInfosForMode($mode_key, $class_type);
490
491
                $result = $this->createCommon($user, 1);
492
                if ($result < 0) {
493
                    $this->errors = array_merge(array($langs->trans('AssetErrorInsertDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
494
                    $error++;
495
                }
496
            }
497
        }
498
499
        if (!$error && $this->fk_asset > 0) {
500
            // Calculation of depreciation lines (reversal and future)
501
            require_once constant('DOL_DOCUMENT_ROOT') . '/asset/class/asset.class.php';
502
            $asset = new Asset($this->db);
503
            $result = $asset->fetch($this->fk_asset);
504
            if ($result > 0) {
505
                $result = $asset->calculationDepreciation();
506
            }
507
            if ($result < 0) {
508
                $this->errors[] = $langs->trans('AssetErrorCalculationDepreciationLines');
509
                $this->errors[] = $asset->errorsToString();
510
                $error++;
511
            }
512
        }
513
514
        if (!$error && !$notrigger) {
515
            // Call trigger
516
            $result = $this->call_trigger('ASSET_DEPRECIATION_OPTIONS_MODIFY', $user);
517
            if ($result < 0) {
518
                $error++;
519
            }
520
            // End call triggers
521
        }
522
523
        if ($error) {
524
            $this->db->rollback();
525
            return -1;
526
        } else {
527
            $this->db->commit();
528
            return 1;
529
        }
530
    }
531
532
    /**
533
     *  Get rate
534
     *
535
     * @param   string          $mode       Depreciation mode (economic, accelerated_depreciation, ...)
536
     * @return  string                      Rate of the provided mode option
537
     */
538
    public function getRate($mode)
539
    {
540
        $duration = (isset($this->deprecation_options[$mode]["duration"]) && $this->deprecation_options[$mode]["duration"] > 0) ? $this->deprecation_options[$mode]["duration"] : 0;
541
        $duration_type = (isset($this->deprecation_options[$mode]["duration_type"]) && $this->deprecation_options[$mode]["duration_type"] > 0) ? $this->deprecation_options[$mode]["duration_type"] : 0;
542
543
        return price(price2num($duration > 0 ? (100 * ($duration_type == 1 ? 12 : 1) / $duration) : 0, 2));
544
    }
545
}
546