dolibarr 25.0.0-alpha
assetdepreciationoptions.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2021 Open-Dsi <support@open-dsi.fr>
3 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
4 * Copyright (C) 2024 Jose <jose.martinez@pichinov.com>
5 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
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
27require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
28
33{
37 public $table_element = '';
38
72 public $fields = array();
73
78 public $deprecation_options_fields = array(
79 'economic' => array(
80 'label' => 'AssetDepreciationOptionEconomic',
81 'table' => 'asset_depreciation_options_economic',
82 'fields' => array(
83 '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,),
84 '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'),
85 'duration' => array('type' => 'integer', 'label' => 'AssetDepreciationOptionDuration', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
86 '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,),
87 '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")',),
88 'accelerated_depreciation_option' => array('type' => 'boolean', 'label' => 'AssetDepreciationOptionAcceleratedDepreciation', 'enabled' => 1, 'position' => 60, 'column_break' => true, 'notnull' => 0, 'default' => '0', 'visible' => 1, 'validate' => 1,),
89 'amount_base_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDepreciationHT', 'enabled' => 1, '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,),
90 'amount_base_deductible_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDeductibleHT', 'enabled' => 1, 'only_on_asset' => 1, 'position' => 100, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
91 'total_amount_last_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionTotalAmountLastDepreciationHT', 'enabled' => 1, 'only_on_asset' => 1, 'position' => 110, 'noteditable' => 1, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
92 ),
93 ),
94 'accelerated_depreciation' => array(
95 'label' => 'AssetDepreciationOptionAcceleratedDepreciation',
96 'table' => 'asset_depreciation_options_fiscal',
97 'enabled_field' => 'economic:accelerated_depreciation_option:1',
98 'fields' => array(
99 '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,),
100 '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'),
101 'duration' => array('type' => 'integer', 'label' => 'AssetDepreciationOptionDuration', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
102 '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,),
103 '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")',),
104 'amount_base_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDepreciationHT', 'enabled' => 1, '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,),
105 'amount_base_deductible_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionAmountBaseDeductibleHT', 'enabled' => 1, 'only_on_asset' => 1, 'position' => 90, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
106 'total_amount_last_depreciation_ht' => array('type' => 'price', 'label' => 'AssetDepreciationOptionTotalAmountLastDepreciationHT', 'enabled' => 1, 'only_on_asset' => 1, 'position' => 100, 'noteditable' => 1, 'notnull' => 0, 'visible' => 1, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
107 ),
108 ),
109 );
113 public $fk_asset;
117 public $fk_asset_model;
121 public $fk_user_modif;
122
126 public $deprecation_options = array();
127
131 public $depreciation_type;
135 public $degressive_coefficient;
139 public $duration;
143 public $duration_type;
147 public $accelerated_depreciation_option;
151 public $rate;
155 public $amount_base_depreciation_ht;
159 public $amount_base_deductible_ht;
163 public $total_amount_last_depreciation_ht;
164
170 public function __construct(DoliDB $db)
171 {
172 global $langs;
173 $this->db = $db;
174
175 // Translate some data of arrayofkeyval
176 if (is_object($langs)) {
177 foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
178 if (!empty($mode_info['fields']) && is_array($mode_info['fields'])) {
179 foreach ($mode_info['fields'] as $field_key => $field_info) {
180 if (!empty($field_info['arrayofkeyval']) && is_array($field_info['arrayofkeyval'])) {
181 foreach ($field_info['arrayofkeyval'] as $key => $val) {
182 $this->deprecation_options_fields[$mode_key]['fields'][$field_key]['arrayofkeyval'][$key] = $langs->trans($val);
183 }
184 }
185 }
186 }
187 }
188 }
189 }
190
199 public function setInfosForMode($mode, $class_type = 0, $all_field = false)
200 {
201 // Clean parameters
202 $mode = strtolower(trim($mode));
203
204 if (!empty($this->deprecation_options_fields[$mode])) {
205 $this->table_element = $this->deprecation_options_fields[$mode]['table'];
206 $this->fields = $this->deprecation_options_fields[$mode]['fields'];
207 foreach ($this->fields as $field_key => $field_info) {
208 if ((!empty($field_info['computed']) && !$all_field) || (!empty($field_info['only_on_asset']) && !empty($class_type))) {
209 unset($this->fields[$field_key]);
210 continue;
211 }
212
213 // Unset required option (notnull) if field disabled
214 if (!empty($field_info['enabled_field'])) {
215 $info = explode(':', $field_info['enabled_field']);
216 // Use isset() + strict string compare, not empty(), because the gating value can legitimately be '0' (e.g. depreciation_type=0 for Linear)
217 if (isset($this->deprecation_options[$info[0]][$info[1]]) && (string) $this->deprecation_options[$info[0]][$info[1]] !== (string) $info[2] && isset($this->fields[$field_key]['notnull'])) {
218 unset($this->fields[$field_key]['notnull']);
219 }
220 }
221 // Set value of the field in the object (for createCommon and setDeprecationOptionsFromPost functions)
222 $this->{$field_key} = $this->deprecation_options[$mode][$field_key] ?? null;
223 }
224
225 $this->fields['rowid'] = array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => '1', 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id");
226 if (empty($class_type)) {
227 $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,);
228 } else {
229 $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,);
230 }
231 $this->fields['tms'] = array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => 0,);
232 $this->fields['fk_user_modif'] = array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => 0,);
233 }
234
235 return 1;
236 }
237
245 protected function isEnabledFieldSatisfiedFromPost($enabledfield)
246 {
247 $info = explode(':', $enabledfield);
248 if (count($info) < 3) {
249 return true;
250 }
251
252 $htmlname = $info[0] . '_' . $info[1];
253 if (!GETPOSTISSET($htmlname)) {
254 return false; // An unchecked checkbox is not submitted at all
255 }
256
257 $value = GETPOST($htmlname, 'alphanohtml');
258 if ($value === 'on') {
259 $value = '1'; // A checked checkbox may be submitted as 'on'
260 }
261
262 return ((string) $value === (string) $info[2]);
263 }
264
271 public function setDeprecationOptionsFromPost($class_type = 0)
272 {
273 global $langs;
274
275 $error = 0;
276
277 $deprecation_options = array();
278 foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
279 // A mode disabled by its enabled_field must not be validated at all. The form submits the
280 // fields of the hidden block anyway, empty, so a required field of that block (the
281 // degressive coefficient) makes the whole page fail. The block is dropped further below,
282 // but only after its fields have been validated, which is too late.
283 if (!empty($mode_info['enabled_field']) && !$this->isEnabledFieldSatisfiedFromPost($mode_info['enabled_field'])) {
284 continue;
285 }
286
287 $this->setInfosForMode($mode_key, $class_type);
288
289 foreach ($mode_info['fields'] as $field_key => $field_info) {
290 if (!empty($field_info['computed'])) {
291 continue;
292 }
293 // Same thing for a single field hidden by its own enabled_field: the degressive
294 // coefficient is required but hidden as soon as the depreciation type is not degressive
295 if (!empty($field_info['enabled_field']) && !$this->isEnabledFieldSatisfiedFromPost($field_info['enabled_field'])) {
296 continue;
297 }
298
299 $html_name = $mode_key . '_' . $field_key;
300 if ($field_info['type'] == 'duration') {
301 if (GETPOST($html_name . 'hour') == '' && GETPOST($html_name . 'min') == '') {
302 continue; // The field was not submitted to be saved
303 }
304 } else {
305 if (!GETPOSTISSET($html_name)) {
306 continue; // The field was not submitted to be saved
307 }
308 }
309 // Ignore special fields
310 if (in_array($field_key, array('rowid', 'entity', 'import_key'))) {
311 continue;
312 }
313 if (in_array($field_key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
314 if (!in_array(abs($field_info['visible']), array(1, 3))) {
315 continue; // Only 1 and 3 that are case to create
316 }
317 }
318
319 // Set value to insert
320 if (in_array($field_info['type'], array('text', 'html'))) {
321 $value = GETPOST($html_name, 'restricthtml');
322 } elseif ($field_info['type'] == 'date') {
323 $value = dol_mktime(0, 0, 0, GETPOSTINT($html_name . 'month'), GETPOSTINT($html_name . 'day'), GETPOSTINT($html_name . 'year'), 'gmt'); // for date without hour, we use gmt
324 } elseif ($field_info['type'] == 'datetime') {
325 $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');
326 } elseif ($field_info['type'] == 'duration') {
327 $value = 60 * 60 * GETPOSTINT($html_name . 'hour') + 60 * GETPOSTINT($html_name . 'min');
328 } elseif (preg_match('/^(integer|price|real|double)/', $field_info['type'])) {
329 $value = price2num(GETPOST($html_name, 'alphanohtml')); // To fix decimal separator according to lang setup
330 } elseif ($field_info['type'] == 'boolean') {
331 $value = ((GETPOST($html_name) == '1' || GETPOST($html_name) == 'on') ? 1 : 0);
332 } elseif ($field_info['type'] == 'reference') {
333 $value = GETPOST($html_name) . ',' . GETPOST($html_name . '2');
334 } else {
335 if ($field_key == 'lang') {
336 $value = GETPOST($html_name, 'aZ09') ? GETPOST($html_name, 'aZ09') : "";
337 } else {
338 $value = GETPOST($html_name, 'alphanohtml');
339 }
340 }
341 if (preg_match('/^integer:/i', $field_info['type']) && $value == '-1') {
342 $value = ''; // This is an implicit foreign key field
343 }
344 if (!empty($field_info['foreignkey']) && $value == '-1') {
345 $value = ''; // This is an explicit foreign key field
346 }
347
348 //var_dump($field_key.' '.$value.' '.$field_info['type']);
349 $field_value = $value;
350
351 if ($field_info['notnull'] > 0 && $field_value == '' && !is_null($field_info['default']) && $field_info['default'] == '(PROV)') {
352 $field_value = '(PROV)';
353 } elseif ((!empty($field_info['required']) || $field_info['notnull'] > 0) && $field_value == '' && !empty($field_info['default'])) {
354 $field_value = $field_info['default'];
355 }
356 if ($field_info['notnull'] > 0 && $field_value == '' && is_null($field_info['default'])) {
357 $error++;
358 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($field_info['label'])), null, 'errors');
359 }
360 $deprecation_options[$mode_key][$field_key] = $field_value;
361
362 // Validation of fields values
363 if (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 1 || getDolGlobalString('MAIN_ACTIVATE_VALIDATION_RESULT')) {
364 if (!$error && !empty($field_info['validate']) && is_callable(array($this, 'validateField'))) {
365 if (!$this->validateField($mode_info['fields'], $field_key, $value)) {
366 $error++;
367 }
368 }
369 }
370 }
371 }
372 // Unset not enabled modes
373 foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
374 if (!empty($mode_info['enabled_field'])) {
375 $info = explode(':', $mode_info['enabled_field']);
376 if (isset($deprecation_options[$info[0]][$info[1]]) && $deprecation_options[$info[0]][$info[1]] != $info[2]) {
377 unset($deprecation_options[$mode_key]);
378 }
379 }
380 }
381 $this->deprecation_options = $deprecation_options;
382
383 if ($error) {
384 return -1;
385 } else {
386 return 1;
387 }
388 }
389
397 public function fetchDeprecationOptions($asset_id = 0, $asset_model_id = 0)
398 {
399 global $langs, $hookmanager;
400 dol_syslog(__METHOD__ . " asset_id=$asset_id, asset_model_id=$asset_model_id");
401
402 $error = 0;
403 $this->errors = array();
404 $this->deprecation_options = array();
405
406 // Clean parameters
407 $asset_id = $asset_id > 0 ? $asset_id : 0;
408 $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
409
410 $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
411 $parameters = array('asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
412 $reshook = $hookmanager->executeHooks('fetchDepreciationOptions', $parameters, $this); // Note that $action and $object may have been modified by some hooks
413 if (!empty($reshook)) {
414 return $reshook;
415 }
416
417 // Check parameters
418 if (empty($asset_id) && empty($asset_model_id)) {
419 $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
420 $error++;
421 }
422 if ($error) {
423 dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
424 return -1;
425 }
426
427 $class_type = $asset_id > 0 ? 0 : 1;
428 $deprecation_options = array();
429 foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
430 $this->setInfosForMode($mode_key, $class_type);
431
432 $result = $this->fetchCommon(0, '', " AND " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id));
433 if ($result < 0) {
434 $this->errors = array_merge(array($langs->trans('AssetErrorFetchDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
435 $error++;
436 } elseif ($result > 0) {
437 foreach ($this->fields as $field_key => $field_info) {
438 if (in_array($field_key, array('rowid', 'fk_asset', 'fk_asset_model', 'tms', 'fk_user_modif'))) {
439 continue;
440 }
441 $deprecation_options[$mode_key][$field_key] = $this->{$field_key};
442 }
443 }
444 }
445 // Unset not enabled modes
446 foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
447 if (!empty($mode_info['enabled_field'])) {
448 $info = explode(':', $mode_info['enabled_field']);
449 // Use isset() + strict string compare, not empty(), because the gating value can legitimately be '0' (e.g. accelerated_depreciation_option=0)
450 if (isset($deprecation_options[$info[0]][$info[1]]) && (string) $deprecation_options[$info[0]][$info[1]] !== (string) $info[2]) {
451 unset($deprecation_options[$mode_key]);
452 }
453 }
454 }
455
456 if ($error) {
457 dol_syslog(__METHOD__ . " Error fetch accountancy codes: " . $this->errorsToString(), LOG_ERR);
458 return -1;
459 } else {
460 $this->deprecation_options = $deprecation_options;
461 return 1;
462 }
463 }
464
472 {
473 global $hookmanager;
474 dol_syslog(__METHOD__ . " mode=$mode");
475
476 $this->errors = array();
477
478 // Clean parameters
479 $mode = strtolower(trim($mode));
480
481 $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
482 $parameters = array('mode' => $mode);
483 $reshook = $hookmanager->executeHooks('getGeneralDepreciationInfoForMode', $parameters, $this); // Note that $action and $object may have been modified by some hooks
484 if ($reshook < 0) {
485 return $reshook;
486 } elseif ($reshook > 0) {
487 return $hookmanager->resArray;
488 }
489
490 $duration_type_list = $this->deprecation_options_fields[$mode]['fields']['duration_type']['arrayofkeyval'];
491
492 $mode_opts = $this->deprecation_options[$mode] ?? array();
493 $duration_type_idx = $mode_opts['duration_type'] ?? null;
494 $duration_type_label = $duration_type_list[$duration_type_idx] ?? '';
495
496 return array(
497 'base_depreciation_ht' => $mode_opts['amount_base_depreciation_ht'] ?? 0,
498 'duration' => $mode_opts['duration'] ?? 0,
499 'duration_type' => $duration_type_label,
500 'rate' => $this->getRate($mode),
501 );
502 }
503
513 public function updateDeprecationOptions($user, $asset_id = 0, $asset_model_id = 0, $notrigger = 0)
514 {
515 global $langs, $hookmanager;
516 dol_syslog(__METHOD__ . " user_id=".$user->id.", asset_id=".$asset_id.", asset_model_id=".$asset_model_id.", notrigger=".$notrigger);
517
518 $error = 0;
519 $this->errors = array();
520
521 // Clean parameters
522 $asset_id = $asset_id > 0 ? $asset_id : 0;
523 $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
524
525 $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
526 $parameters = array('user' => $user, 'asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
527 $reshook = $hookmanager->executeHooks('updateDepreciationOptions', $parameters, $this); // Note that $action and $object may have been modified by some hooks
528 if (!empty($reshook)) {
529 return $reshook;
530 }
531
532 // Check parameters
533 if (empty($asset_id) && empty($asset_model_id)) {
534 $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
535 $error++;
536 }
537 if ($error) {
538 dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
539 return -1;
540 }
541
542 $this->db->begin();
543
544 if ($asset_id > 0) {
545 $this->fk_asset = $asset_id;
546 $class_type = 0;
547 } else {
548 $this->fk_asset_model = $asset_model_id;
549 $class_type = 1;
550 }
551 $this->tms = dol_now();
552 $this->fk_user_modif = $user->id;
553
554 foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
555 // Delete old accountancy codes
556 $sql = "DELETE FROM " . MAIN_DB_PREFIX . $mode_info['table']; // From safe table @phan-suppress-current-line SqlInjection
557 $sql .= " WHERE " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id);
558 $resql = $this->db->query($sql);
559 if (!$resql) {
560 $this->errors[] = $langs->trans('AssetErrorDeleteDepreciationOptionsForMode', $mode_key) . ': ' . $this->db->lasterror();
561 $error++;
562 }
563
564 if (!$error && !empty($this->deprecation_options[$mode_key])) {
565 if (!empty($mode_info['enabled_field'])) {
566 list($ref_mode, $ref_field, $required) = explode(':', $mode_info['enabled_field']);
567 $flag = $this->deprecation_options[$ref_mode][$ref_field] ?? null;
568 if ((string) $flag !== (string) $required) {
569 continue;
570 }
571 }
572
573 $this->setInfosForMode($mode_key, $class_type);
574
575 $result = $this->createCommon($user, 1);
576 if ($result < 0) {
577 $this->errors = array_merge(array($langs->trans('AssetErrorInsertDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
578 $error++;
579 }
580 }
581 }
582
583 if (!$error && $this->fk_asset > 0) {
584 // Calculation of depreciation lines (reversal and future)
585 require_once DOL_DOCUMENT_ROOT . '/asset/class/asset.class.php';
586 $asset = new Asset($this->db);
587 $result = $asset->fetch($this->fk_asset);
588 if ($result > 0) {
589 $result = $asset->calculationDepreciation();
590 }
591 if ($result < 0) {
592 $this->errors[] = $langs->trans('AssetErrorCalculationDepreciationLines');
593 $this->errors[] = $asset->errorsToString();
594 $error++;
595 }
596 }
597
598 if (!$error && !$notrigger) {
599 // Call trigger
600 $result = $this->call_trigger('ASSET_DEPRECIATION_OPTIONS_MODIFY', $user);
601 if ($result < 0) {
602 $error++;
603 }
604 // End call triggers
605 }
606
607 if ($error) {
608 $this->db->rollback();
609 return -1;
610 } else {
611 $this->db->commit();
612 return 1;
613 }
614 }
615
622 public function getRate($mode)
623 {
624 $duration = (isset($this->deprecation_options[$mode]["duration"]) && $this->deprecation_options[$mode]["duration"] > 0) ? $this->deprecation_options[$mode]["duration"] : 0;
625 $duration_type = (isset($this->deprecation_options[$mode]["duration_type"]) && $this->deprecation_options[$mode]["duration_type"] > 0) ? $this->deprecation_options[$mode]["duration_type"] : 0;
626
627 return price(price2num($duration > 0 ? (100 * ($duration_type == 1 ? 12 : 1) / $duration) : 0, 2));
628 }
629}
Class for AssetDepreciationOptions.
updateDeprecationOptions($user, $asset_id=0, $asset_model_id=0, $notrigger=0)
Update deprecation options of a asset or a asset model.
getGeneralDepreciationInfoForMode($mode)
get general depreciation info for a mode (used in depreciation card)
setDeprecationOptionsFromPost($class_type=0)
Fill deprecation_options property of object (using for data sent by forms)
isEnabledFieldSatisfiedFromPost($enabledfield)
Return whether an 'enabled_field' condition ("mode_key:field_key:value") is satisfied by the data of ...
setInfosForMode($mode, $class_type=0, $all_field=false)
Set object infos for a mode.
fetchDeprecationOptions($asset_id=0, $asset_model_id=0)
Load deprecation options of a asset or a asset model.
Class for Asset.
validateField($fields, $fieldKey, $fieldValue)
Return validation test result for a field.
createCommon(User $user, $notrigger=0)
Create object in the database.
errorsToString()
Method to output saved errors.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
Class to manage Dolibarr database access.
dol_now($mode='gmt')
Return date for now.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.