Passed
Pull Request — dev (#6)
by Rafael
79:24 queued 24:08
created

updateDeprecationOptions()   F

Complexity

Conditions 24
Paths 12012

Size

Total Lines 98
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

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

469
        /** @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...
470
        $this->fk_user_modif = $user->id;
471
472
        foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
473
            // Delete old accountancy codes
474
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . $mode_info['table'];
475
            $sql .= " WHERE " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id);
476
            $resql = $this->db->query($sql);
477
            if (!$resql) {
478
                $this->errors[] = $langs->trans('AssetErrorDeleteDepreciationOptionsForMode', $mode_key) . ': ' . $this->db->lasterror();
479
                $error++;
480
            }
481
482
            if (!$error && !empty($this->deprecation_options[$mode_key])) {
483
                if (!empty($mode_info['enabled_field'])) {
484
                    $info = explode(':', $mode_info['enabled_field']);
485
                    if ($this->deprecation_options[$info[0]][$info[1]] != $info[2]) {
486
                        continue;
487
                    }
488
                }
489
490
                $this->setInfosForMode($mode_key, $class_type);
491
492
                $result = $this->createCommon($user, 1);
493
                if ($result < 0) {
494
                    $this->errors = array_merge(array($langs->trans('AssetErrorInsertDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
495
                    $error++;
496
                }
497
            }
498
        }
499
500
        if (!$error && $this->fk_asset > 0) {
501
            // Calculation of depreciation lines (reversal and future)
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