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

AssetAccountancyCodes::updateAccountancyCodes()   F

Complexity

Conditions 25
Paths > 20000

Size

Total Lines 95
Code Lines 62

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 25
eloc 62
nc 24252
nop 4
dl 0
loc 95
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       Rafael San José             <[email protected]>
5
 *
6
 * This program is free software; you can redistribute it and/or modify
7
 * it under the terms of the GNU General Public License as published by
8
 * the Free Software Foundation; either version 3 of the License, or
9
 * (at your option) any later version.
10
 *
11
 * This program is distributed in the hope that it will be useful,
12
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14
 * GNU General Public License for more details.
15
 *
16
 * You should have received a copy of the GNU General Public License
17
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18
 */
19
20
namespace Dolibarr\Code\Asset\Classes;
21
22
/**
23
 * \file        asset/class/assetaccountancycodes.class.php
24
 * \ingroup     asset
25
 * \brief       This file is a class file for AssetAccountancyCodes
26
 */
27
28
use Dolibarr\Core\Base\CommonObject;
29
30
/**
31
 * Class for AssetAccountancyCodes
32
 */
33
class AssetAccountancyCodes extends CommonObject
34
{
35
    /**
36
     * @var array  Array with all accountancy codes info by mode.
37
     *  Note : 'economic' mode is mandatory and is the primary accountancy codes
38
     *         'depreciation_asset' and 'depreciation_expense' is mandatory and is used for write depreciation in bookkeeping
39
     */
40
    public $accountancy_codes_fields = array(
41
        'economic' => array(
42
            'label' => 'AssetAccountancyCodeDepreciationEconomic',
43
            'table' => 'asset_accountancy_codes_economic',
44
            'depreciation_debit' => 'depreciation_asset',
45
            'depreciation_credit' => 'depreciation_expense',
46
            'fields' => array(
47
                'asset' => array('label' => 'AssetAccountancyCodeAsset'),
48
                'depreciation_asset' => array('label' => 'AssetAccountancyCodeDepreciationAsset'),
49
                'depreciation_expense' => array('label' => 'AssetAccountancyCodeDepreciationExpense'),
50
                'value_asset_sold' => array('label' => 'AssetAccountancyCodeValueAssetSold'),
51
                'receivable_on_assignment' => array('label' => 'AssetAccountancyCodeReceivableOnAssignment'),
52
                'proceeds_from_sales' => array('label' => 'AssetAccountancyCodeProceedsFromSales'),
53
                'vat_collected' => array('label' => 'AssetAccountancyCodeVatCollected'),
54
                'vat_deductible' => array('label' => 'AssetAccountancyCodeVatDeductible','column_break' => true),
55
            ),
56
        ),
57
        'accelerated_depreciation' => array(
58
            'label' => 'AssetAccountancyCodeDepreciationAcceleratedDepreciation',
59
            'table' => 'asset_accountancy_codes_fiscal',
60
            'depreciation_debit' => 'accelerated_depreciation',
61
            'depreciation_credit' => 'endowment_accelerated_depreciation',
62
            'fields' => array(
63
                'accelerated_depreciation' => array('label' => 'AssetAccountancyCodeAcceleratedDepreciation'),
64
                'endowment_accelerated_depreciation' => array('label' => 'AssetAccountancyCodeEndowmentAcceleratedDepreciation'),
65
                'provision_accelerated_depreciation' => array('label' => 'AssetAccountancyCodeProvisionAcceleratedDepreciation'),
66
            ),
67
        ),
68
    );
69
70
    /**
71
     * @var array  Array with all accountancy codes by mode.
72
     */
73
    public $accountancy_codes = array();
74
75
    /**
76
     * Constructor
77
     *
78
     * @param DoliDB $db Database handler
79
     */
80
    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...
81
    {
82
        $this->db = $db;
83
    }
84
85
    /**
86
     *  Fill accountancy_codes property of object (using for data sent by forms)
87
     *
88
     *  @return array                   Array of values
89
     */
90
    public function setAccountancyCodesFromPost()
91
    {
92
        $this->accountancy_codes = array();
93
        foreach ($this->accountancy_codes_fields as $mode_key => $mode_info) {
94
            $this->accountancy_codes[$mode_key] = array();
95
            foreach ($mode_info['fields'] as $field_key => $field_info) {
96
                $accountancy_code = GETPOST($mode_key . '_' . $field_key, 'aZ09');
97
                if (empty($accountancy_code) || $accountancy_code == '-1') {
98
                    $accountancy_code = '';
99
                }
100
                $this->accountancy_codes[$mode_key][$field_key] = $accountancy_code;
101
            }
102
        }
103
        return $this->accountancy_codes;
104
    }
105
106
    /**
107
     *  Load accountancy codes of a asset or a asset model
108
     *
109
     * @param   int     $asset_id           Asset ID to set
110
     * @param   int     $asset_model_id     Asset model ID to set
111
     * @return  int                         Return integer <0 if KO, >0 if OK
112
     */
113
    public function fetchAccountancyCodes($asset_id = 0, $asset_model_id = 0)
114
    {
115
        global $langs, $hookmanager;
116
        dol_syslog(__METHOD__ . " asset_id=$asset_id, asset_model_id=$asset_model_id");
117
118
        $error = 0;
119
        $this->errors = array();
120
        $this->accountancy_codes = array();
121
122
        // Clean parameters
123
        $asset_id = $asset_id > 0 ? $asset_id : 0;
124
        $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
125
126
        $hookmanager->initHooks(array('assetaccountancycodesdao'));
127
        $parameters = array('asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
128
        $reshook = $hookmanager->executeHooks('fetchAccountancyCodes', $parameters, $this); // Note that $action and $object may have been modified by some hooks
129
        if (!empty($reshook)) {
130
            return $reshook;
131
        }
132
133
        // Check parameters
134
        if (empty($asset_id) && empty($asset_model_id)) {
135
            $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
136
            $error++;
137
        }
138
        if ($error) {
139
            dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
140
            return -1;
141
        }
142
143
        $accountancy_codes = array();
144
        foreach ($this->accountancy_codes_fields as $mode_key => $mode_info) {
145
            $sql = "SELECT " . implode(',', array_keys($mode_info['fields']));
146
            $sql .= " FROM " . MAIN_DB_PREFIX . $mode_info['table'];
147
            $sql .= " WHERE " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id);
148
149
            $resql = $this->db->query($sql);
150
            if ($resql) {
151
                if ($obj = $this->db->fetch_object($resql)) {
152
                    $accountancy_codes[$mode_key] = array();
153
                    foreach ($mode_info['fields'] as $field_key => $field_info) {
154
                        $accountancy_codes[$mode_key][$field_key] = $obj->$field_key;
155
                    }
156
                }
157
            } else {
158
                $this->errors[] = $langs->trans('AssetErrorFetchAccountancyCodesForMode', $mode_key) . ': ' . $this->db->lasterror();
159
                $error++;
160
            }
161
        }
162
163
        if ($error) {
164
            dol_syslog(__METHOD__ . " Error fetch accountancy codes: " . $this->errorsToString(), LOG_ERR);
165
            return -1;
166
        } else {
167
            $this->accountancy_codes = $accountancy_codes;
168
            return 1;
169
        }
170
    }
171
172
    /**
173
     *  Update accountancy codes of a asset or a asset model
174
     *
175
     * @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...
176
     * @param   int     $asset_id           Asset ID to set
177
     * @param   int     $asset_model_id     Asset model ID to set
178
     * @param   int     $notrigger          1=disable trigger UPDATE (when called by create)
179
     * @return  int                         Return integer <0 if KO, >0 if OK
180
     */
181
    public function updateAccountancyCodes($user, $asset_id = 0, $asset_model_id = 0, $notrigger = 0)
182
    {
183
        global $langs, $hookmanager;
184
        dol_syslog(__METHOD__ . " user_id=" . $user->id . ", asset_id=" . $asset_id . ", asset_model_id=" . $asset_model_id . ", notrigger=" . $notrigger);
185
186
        $error = 0;
187
        $this->errors = array();
188
189
        // Clean parameters
190
        $asset_id = $asset_id > 0 ? $asset_id : 0;
191
        $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
192
193
        $hookmanager->initHooks(array('assetaccountancycodesdao'));
194
        $parameters = array('user' => $user, 'asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
195
        $reshook = $hookmanager->executeHooks('updateAccountancyCodes', $parameters, $this); // Note that $action and $object may have been modified by some hooks
196
        if (!empty($reshook)) {
197
            return $reshook;
198
        }
199
200
        // Check parameters
201
        if (empty($asset_id) && empty($asset_model_id)) {
202
            $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
203
            $error++;
204
        }
205
        if ($error) {
206
            dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
207
            return -1;
208
        }
209
210
        $this->db->begin();
211
        $now = dol_now();
212
213
        foreach ($this->accountancy_codes_fields as $mode_key => $mode_info) {
214
            // Delete old accountancy codes
215
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . $mode_info['table'];
216
            $sql .= " WHERE " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id);
217
            $resql = $this->db->query($sql);
218
            if (!$resql) {
219
                $this->errors[] = $langs->trans('AssetErrorDeleteAccountancyCodesForMode', $mode_key) . ': ' . $this->db->lasterror();
220
                $error++;
221
            }
222
223
            if (!$error && !empty($this->accountancy_codes[$mode_key])) {
224
                // Insert accountancy codes
225
                $sql = "INSERT INTO " . MAIN_DB_PREFIX . $mode_info['table'] . "(";
226
                $sql .= $asset_id > 0 ? "fk_asset," : "fk_asset_model,";
227
                $sql .= implode(',', array_keys($mode_info['fields']));
228
                $sql .= ", tms, fk_user_modif";
229
                $sql .= ") VALUES(";
230
                $sql .= $asset_id > 0 ? $asset_id : $asset_model_id;
231
                foreach ($mode_info['fields'] as $field_key => $field_info) {
232
                    $sql .= ', ' . (empty($this->accountancy_codes[$mode_key][$field_key]) ? 'NULL' : "'" . $this->db->escape($this->accountancy_codes[$mode_key][$field_key]) . "'");
233
                }
234
                $sql .= ", '" . $this->db->idate($now) . "'";
235
                $sql .= ", " . $user->id;
236
                $sql .= ")";
237
238
                $resql = $this->db->query($sql);
239
                if (!$resql) {
240
                    $this->errors[] = $langs->trans('AssetErrorInsertAccountancyCodesForMode', $mode_key) . ': ' . $this->db->lasterror();
241
                    $error++;
242
                }
243
            }
244
        }
245
246
        if (!$error && $asset_id > 0) {
247
            // Calculation of depreciation lines (reversal and future)
248
            require_once constant('DOL_DOCUMENT_ROOT') . '/asset/class/asset.class.php';
249
            $asset = new Asset($this->db);
250
            $result = $asset->fetch($asset_id);
251
            if ($result > 0) {
252
                $result = $asset->calculationDepreciation();
253
            }
254
            if ($result < 0) {
255
                $this->errors[] = $langs->trans('AssetErrorCalculationDepreciationLines');
256
                $this->errors[] = $asset->errorsToString();
257
                $error++;
258
            }
259
        }
260
261
        if (!$error && !$notrigger) {
262
            // Call trigger
263
            $result = $this->call_trigger('ASSET_ACCOUNTANCY_CODES_MODIFY', $user);
264
            if ($result < 0) {
265
                $error++;
266
            }
267
            // End call triggers
268
        }
269
270
        if (!$error) {
271
            $this->db->commit();
272
            return 1;
273
        } else {
274
            $this->db->rollback();
275
            return -1;
276
        }
277
    }
278
}
279