Passed
Pull Request — dev (#8)
by Rafael
58:47
created

AssetAccountancyCodes::updateAccountancyCodes()   F

Complexity

Conditions 25
Paths > 20000

Size

Total Lines 94
Code Lines 61

Duplication

Lines 0
Ratio 0 %

Importance

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