dolibarr 25.0.0-alpha
asset.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2018-2025 Alexandre Spangaro <alexandre@inovea-conseil.com>
4 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024 Jose MARTINEZ <jose.martinez@pichinov.com>
7 * Copyright (C) 2026 Joachim Kueter <git-jk@bloxera.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
29require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/asset.lib.php';
31
35class Asset extends CommonObject
36{
40 public $module = 'asset';
41
45 public $element = 'asset';
46
50 public $table_element = 'asset';
51
55 public $picto = 'asset';
56
61 public $fk_element = 'fk_asset';
62
69 protected $childtablesoncascade = array(
70 '@AssetAccountancyCodes:/asset/class/assetaccountancycodes.class.php:fk_asset',
71 '@AssetAccountancyCodesFiscal:/asset/class/assetaccountancycodesfiscal.class.php:fk_asset'
72 );
73
74
75 const STATUS_DRAFT = 0; // Draft
76 const STATUS_VALIDATED = 1; // In progress
77 const STATUS_DISPOSED = 9; // Disposed
78
110 public $fields = array(
111 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'position' => 1, 'notnull' => 1, 'visible' => 0, 'noteditable' => 1, 'index' => 1, 'css' => 'left', 'comment' => "Id"),
112 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'default' => '1', 'index' => 1, 'position' => 5),
113 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'position' => 20, 'notnull' => 1, 'visible' => 4, 'noteditable' => 0, 'default' => '(PROV)', 'index' => 1, 'searchall' => 1, 'showoncombobox' => 1, 'validate' => 1, 'comment' => "Reference of object", "css" => "maxwidth150"),
114 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'position' => 30, 'notnull' => 1, 'visible' => 1, 'searchall' => 1, 'csslist' => 'tdoverflowmax125', 'css' => 'minwidth300', 'cssview' => 'wordbreak', 'showoncombobox' => 2, 'validate' => 1,),
115 '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' => 40, 'notnull' => 0, 'visible' => 1, 'index' => 1, 'validate' => 1, 'csslist' => 'tdoverflowmax75', 'css' => 'maxwidth300'),
116 'qty' => array('type' => 'real', 'label' => 'Qty', 'enabled' => 1, 'position' => 50, 'notnull' => 1, 'visible' => 0, 'default' => '1', 'isameasure' => 1, 'css' => 'maxwidth75imp', 'validate' => 1,),
117 'acquisition_type' => array('type' => 'smallint', 'label' => 'AssetAcquisitionType', 'enabled' => 1, 'position' => 60, 'notnull' => 1, 'visible' => 1, 'arrayofkeyval' => array(0 => 'AssetAcquisitionTypeNew', 1 => 'AssetAcquisitionTypeOccasion'), 'validate' => 1, 'csslist' => 'tdoverflowmax75'),
118 'asset_type' => array('type' => 'smallint', 'label' => 'AssetType', 'enabled' => 1, 'position' => 70, 'notnull' => 1, 'visible' => 1, 'arrayofkeyval' => array(0 => 'AssetTypeIntangible', 1 => 'AssetTypeTangible', 2 => 'AssetTypeInProgress', 3 => 'AssetTypeFinancial'), 'validate' => 1, 'csslist' => 'tdoverflowmax75'),
119 'not_depreciated' => array('type' => 'boolean', 'label' => 'AssetNotDepreciated', 'enabled' => 1, 'position' => 80, 'notnull' => 0, 'default' => '0', 'visible' => 1, 'validate' => 1, 'csslist' => 'maxwidth50 tdoverflowmax50', 'css' => 'maxwidth50imp'),
120 'date_acquisition' => array('type' => 'date', 'label' => 'AssetDateAcquisition', 'enabled' => 1, 'position' => 90, 'notnull' => 1, 'visible' => 1,),
121 'date_start' => array('type' => 'date', 'label' => 'AssetDateStart', 'enabled' => 1, 'position' => 100, 'notnull' => 0, 'visible' => -1,),
122 'acquisition_value_ht' => array('type' => 'price', 'label' => 'AssetAcquisitionValueHT', 'enabled' => 1, 'position' => 110, 'notnull' => 1, 'visible' => 1, 'isameasure' => 1, 'validate' => 1,),
123 'recovered_vat' => array('type' => 'price', 'label' => 'AssetRecoveredVAT', 'enabled' => 1, 'position' => 120, 'notnull' => 0, 'visible' => 1, 'isameasure' => 1, 'validate' => 1,),
124 'reversal_date' => array('type' => 'date', 'label' => 'AssetReversalDate', 'enabled' => 1, 'position' => 130, 'notnull' => 0, 'visible' => 1,),
125 'reversal_amount_ht' => array('type' => 'price', 'label' => 'AssetReversalAmountHT', 'enabled' => 1, 'position' => 140, 'notnull' => 0, 'visible' => 1, 'isameasure' => 1, 'validate' => 1, 'csslist' => 'maxwidth50'),
126 'disposal_date' => array('type' => 'date', 'label' => 'AssetDisposalDate', 'enabled' => 1, 'position' => 200, 'notnull' => 0, 'visible' => -2,),
127 'disposal_amount_ht' => array('type' => 'price', 'label' => 'AssetDisposalAmount', 'enabled' => 1, 'position' => 210, 'notnull' => 0, 'visible' => -2, 'default' => '0', 'isameasure' => 1, 'validate' => 1,),
128 'fk_disposal_type' => array('type' => 'sellist:c_asset_disposal_type:label:rowid::active=1', 'label' => 'AssetDisposalType', 'enabled' => 1, 'position' => 220, 'notnull' => 0, 'visible' => -2, 'index' => 1, 'validate' => 1,),
129 'disposal_depreciated' => array('type' => 'boolean', 'label' => 'AssetDisposalDepreciated', 'enabled' => 1, 'position' => 230, 'notnull' => 0, 'default' => '0', 'visible' => -2, 'validate' => 1,),
130 'disposal_subject_to_vat' => array('type' => 'boolean', 'label' => 'AssetDisposalSubjectToVat', 'enabled' => 1, 'position' => 240, 'notnull' => 0, 'default' => '0', 'visible' => -2, 'validate' => 1,),
131 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'position' => 300, 'notnull' => 0, 'visible' => 0, 'validate' => 1,),
132 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'position' => 301, 'notnull' => 0, 'visible' => 0, 'validate' => 1,),
133 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'position' => 500, 'notnull' => 1, 'visible' => -2,),
134 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'position' => 501, 'notnull' => 0, 'visible' => -2,),
135 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -2, 'position' => 502, 'notnull' => 0,),
136 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'position' => 510, 'notnull' => 1, 'visible' => -2, 'foreignkey' => 'user.rowid',),
137 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'position' => 511, 'notnull' => -1, 'visible' => -2,),
138 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'picto' => 'user', 'enabled' => 1, 'visible' => -2, 'position' => 512, 'notnull' => 0, 'csslist' => 'tdoverflowmax100'),
139 'last_main_doc' => array('type' => 'varchar(255)', 'label' => 'LastMainDoc', 'enabled' => 1, 'position' => 600, 'notnull' => 0, 'visible' => 0,),
140 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'position' => 1000, 'notnull' => -1, 'visible' => -2,),
141 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'position' => 1010, 'notnull' => -1, 'visible' => 0,),
142 'status' => array('type' => 'smallint', 'label' => 'Status', 'enabled' => 1, 'position' => 1000, 'notnull' => 1, 'default' => '0', 'visible' => 2, 'index' => 1, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Validated', 9 => 'Canceled'), 'validate' => 1,),
143 );
144
148 public $rowid;
152 public $ref;
156 public $label;
160 public $fk_asset_model;
164 public $reversal_amount_ht;
168 public $acquisition_value_ht;
172 public $recovered_vat;
176 public $reversal_date;
180 public $date_acquisition;
184 public $date_start;
188 public $qty;
192 public $acquisition_type;
196 public $asset_type;
200 public $not_depreciated;
204 public $disposal_date;
208 public $disposal_amount_ht;
212 public $fk_disposal_type;
216 public $disposal_depreciated;
220 public $disposal_subject_to_vat;
224 public $supplier_invoice_id;
228 public $note_public;
232 public $note_private;
236 public $date_valid;
240 public $fk_user_creat;
244 public $fk_user_modif;
248 public $fk_user_valid;
252 public $last_main_doc;
253
257 public $import_key;
261 public $model_pdf;
262
266 public $status;
267
271 public $asset_depreciation_options;
272
276 public $asset_accountancy_codes;
277
281 public $depreciation_lines = array();
282
283
289 public function __construct(DoliDB $db)
290 {
291 global $langs;
292
293 $this->db = $db;
294
295 $this->ismultientitymanaged = 1;
296 $this->isextrafieldmanaged = 1;
297
298 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
299 $this->fields['rowid']['visible'] = 0;
300 }
301 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
302 $this->fields['entity']['enabled'] = 0;
303 }
304
305 // Unset fields that are disabled
306 foreach ($this->fields as $key => $val) {
307 if (isset($val['enabled']) && empty($val['enabled'])) {
308 unset($this->fields[$key]);
309 }
310 }
311
312 // Translate some data of arrayofkeyval
313 if (is_object($langs)) {
314 foreach ($this->fields as $key => $val) {
315 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
316 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
317 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
318 }
319 }
320 }
321 }
322 }
323
331 public function create(User $user, $notrigger = 0)
332 {
333 if (!isset($this->date_start) || $this->date_start === "") {
334 $this->date_start = $this->date_acquisition;
335 }
336
337 $this->db->begin();
338
339 $result = $result_create = $this->createCommon($user, $notrigger);
340 if ($result > 0 && $this->fk_asset_model > 0) {
341 $result = $this->setDataFromAssetModel($user, $notrigger);
342 }
343 if ($result > 0) {
344 if ($this->supplier_invoice_id > 0) {
345 $this->add_object_linked('invoice_supplier', $this->supplier_invoice_id);
346 }
347 }
348
349 if ($result < 0) {
350 $this->db->rollback();
351 } else {
352 $this->db->commit();
353 }
354
355 return $result > 0 ? $result_create : $result;
356 }
357
365 public function createFromClone(User $user, $fromid)
366 {
367 //global $langs, $extrafields;
368 //$error = 0;
369
370 dol_syslog(__METHOD__, LOG_DEBUG);
371
372 // $object = new self($this->db);
373 //
374 // $this->db->begin();
375 //
376 // // Load source object
377 // $result = $object->fetchCommon($fromid);
378 //
379 //
380 // // Reset some properties
381 // unset($object->id);
382 // unset($object->fk_user_creat);
383 // unset($object->import_key);
384 //
385 // // Clear fields
386 // if (property_exists($object, 'ref')) {
387 // $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
388 // }
389 // if (property_exists($object, 'label')) {
390 // $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
391 // }
392 // if (property_exists($object, 'status')) {
393 // $object->status = self::STATUS_DRAFT;
394 // }
395 // if (property_exists($object, 'date_creation')) {
396 // $object->date_creation = dol_now();
397 // }
398 // if (property_exists($object, 'date_modification')) {
399 // $object->date_modification = null;
400 // }
401 // // ...
402 // // Clear extrafields that are unique
403 // if (is_array($object->array_options) && count($object->array_options) > 0) {
404 // $extrafields->fetch_name_optionals_label($this->table_element);
405 // foreach ($object->array_options as $key => $option) {
406 // $shortkey = preg_replace('/options_/', '', $key);
407 // if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
408 // //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
409 // unset($object->array_options[$key]);
410 // }
411 // }
412 // }
413 //
414 // // Create clone
415 // $object->context['createfromclone'] = 'createfromclone';
416 // $result = $object->createCommon($user);
417 // if ($result < 0) {
418 // $error++;
419 // $this->error = $object->error;
420 // $this->errors = $object->errors;
421 // }
422 //
423 // if (!$error) {
424 // // copy internal contacts
425 // if ($this->copy_linked_contact($object, 'internal') < 0) {
426 // $error++;
427 // }
428 // }
429 //
430 // if (!$error) {
431 // // copy external contacts if same company
432 // if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
433 // if ($this->copy_linked_contact($object, 'external') < 0) {
434 // $error++;
435 // }
436 // }
437 // }
438 //
439 // unset($object->context['createfromclone']);
440 //
441 // // End
442 // if (!$error) {
443 // $this->db->commit();
444 // return $object;
445 // } else {
446 // $this->db->rollback();
447 // return -1;
448 // }
449
450 return -1;
451 }
452
460 public function fetch($id, $ref = null)
461 {
462 $result = $this->fetchCommon($id, $ref);
463 if ($result > 0) {
464 $res = $this->hasDepreciationLinesInBookkeeping();
465 if ($res < 0) {
466 return -1;
467 } elseif ($res > 0) {
468 $this->fields['date_acquisition']['noteditable'] = 1;
469 $this->fields['date_start']['noteditable'] = 1;
470 $this->fields['acquisition_value_ht']['noteditable'] = 1;
471 $this->fields['recovered_vat']['noteditable'] = 1;
472 $this->fields['reversal_date']['noteditable'] = 1;
473 $this->fields['reversal_amount_ht']['noteditable'] = 1;
474 }
475 }
476
477 return $result;
478 }
479
480
493 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
494 {
495 dol_syslog(__METHOD__, LOG_DEBUG);
496
497 $records = array();
498
499 $sql = "SELECT ";
500 $sql .= $this->getFieldList('t');
501 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
502 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
503 $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
504 } else {
505 $sql .= " WHERE 1 = 1";
506 }
507
508 // Manage filter
509 $errormessage = '';
510 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
511 if ($errormessage) {
512 $this->errors[] = $errormessage;
513 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
514
515 return -1;
516 }
517
518 if (!empty($sortfield)) {
519 $sql .= $this->db->order($sortfield, $sortorder);
520 }
521 if (!empty($limit)) {
522 $sql .= $this->db->plimit($limit, $offset);
523 }
524
525 $resql = $this->db->query($sql);
526 if ($resql) {
527 $num = $this->db->num_rows($resql);
528 $i = 0;
529 while ($i < ($limit ? min($limit, $num) : $num)) {
530 $obj = $this->db->fetch_object($resql);
531
532 $record = new self($this->db);
533 $record->setVarsFromFetchObj($obj);
534
535 $records[$record->id] = $record;
536
537 $i++;
538 }
539 $this->db->free($resql);
540
541 return $records;
542 } else {
543 $this->errors[] = 'Error '.$this->db->lasterror();
544 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
545
546 return -1;
547 }
548 }
549
557 public function update(User $user, $notrigger = 0)
558 {
559 if (!isset($this->date_start) || $this->date_start === "") {
560 $this->date_start = $this->date_acquisition;
561 }
562
563 $this->db->begin();
564
565 $result = $this->updateCommon($user, $notrigger);
566 if ($result > 0 && $this->fk_asset_model > 0 && $this->fk_asset_model != $this->oldcopy->fk_asset_model) {
567 $result = $this->setDataFromAssetModel($user, $notrigger);
568 }
569 if ($result > 0 && is_object($this->oldcopy) && (
570 $this->date_start != $this->oldcopy->date_start ||
571 $this->acquisition_value_ht != $this->oldcopy->acquisition_value_ht ||
572 $this->reversal_date != $this->oldcopy->reversal_date ||
573 $this->reversal_amount_ht != $this->oldcopy->reversal_amount_ht ||
574 ($this->fk_asset_model > 0 && $this->fk_asset_model != $this->oldcopy->fk_asset_model)
575 )) {
576 $result = $this->calculationDepreciation();
577 }
578
579 if ($result < 0) {
580 $this->db->rollback();
581 } else {
582 $this->db->commit();
583 }
584
585 return $result;
586 }
587
595 public function delete(User $user, $notrigger = 0)
596 {
597 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'asset_depreciation_codes_economic WHERE fk_asset = '.((int) $this->id);
598 $this->db->query($sql);
599
600 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'asset_depreciation_codes_fiscal WHERE fk_asset = '.((int) $this->id);
601 $this->db->query($sql);
602
603 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'asset_depreciation_options_fiscal WHERE fk_asset = '.((int) $this->id);
604 $this->db->query($sql);
605
606 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'asset_depreciation_options_economic WHERE fk_asset = '.((int) $this->id);
607 $this->db->query($sql);
608
609 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'asset_depreciation WHERE fk_asset = '.((int) $this->id);
610 $this->db->query($sql);
611
612 return $this->deleteCommon($user, $notrigger);
613 //return $this->deleteCommon($user, $notrigger, 1);
614 }
615
623 public function setDataFromAssetModel(User $user, $notrigger = 0)
624 {
625 global $langs;
626 $langs->load('assets');
627
628 // Clean parameters
629 $this->id = $this->id > 0 ? $this->id : 0;
630 $this->fk_asset_model = $this->fk_asset_model > 0 ? $this->fk_asset_model : 0;
631
632 // Check parameters
633 $error = 0;
634 if (empty($this->id)) {
635 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
636 $error++;
637 }
638 if (empty($this->fk_asset_model)) {
639 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AssetModel") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
640 $error++;
641 }
642 if ($error) {
643 return -1;
644 }
645
646 $this->db->begin();
647
648 // Get depreciation options
649 //---------------------------
650 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
651 $options_model = new AssetDepreciationOptions($this->db);
652 $result = $options_model->fetchDeprecationOptions(0, $this->fk_asset_model);
653 if ($result < 0) {
654 $this->error = $options_model->error;
655 $this->errors = $options_model->errors;
656 $error++;
657 } elseif ($result > 0) {
658 $options = new AssetDepreciationOptions($this->db);
659 $result = $options->fetchDeprecationOptions($this->id);
660 if ($result < 0) {
661 $this->error = $options->error;
662 $this->errors = $options->errors;
663 $error++;
664 }
665
666 if (!$error) {
667 foreach ($options_model->deprecation_options as $mode_key => $fields) {
668 foreach ($fields as $field_key => $value) {
669 $options->deprecation_options[$mode_key][$field_key] = $value;
670 }
671 // 'amount_base_depreciation_ht' only exists on the asset (not on the model, see 'only_on_asset'),
672 // so it is never part of $fields above and must be computed from the asset itself, otherwise
673 // it stays at 0 and all depreciation lines are calculated on a zero base.
674 if (!array_key_exists('amount_base_depreciation_ht', $options->deprecation_options[$mode_key])) {
675 $options->deprecation_options[$mode_key]['amount_base_depreciation_ht'] = $this->reversal_amount_ht > 0 ? $this->reversal_amount_ht : $this->acquisition_value_ht;
676 }
677 }
678
679 $result = $options->updateDeprecationOptions($user, $this->id, 0, $notrigger);
680 if ($result < 0) {
681 $this->error = $options->error;
682 $this->errors = $options->errors;
683 $error++;
684 }
685 }
686 }
687
688 // Get accountancy codes
689 //---------------------------
690 if (!$error) {
691 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetaccountancycodes.class.php';
692 $accountancy_codes_model = new AssetAccountancyCodes($this->db);
693 $result = $accountancy_codes_model->fetchAccountancyCodes(0, $this->fk_asset_model);
694 if ($result < 0) {
695 $this->error = $accountancy_codes_model->error;
696 $this->errors = $accountancy_codes_model->errors;
697 $error++;
698 } elseif ($result > 0) {
699 $accountancy_codes = new AssetAccountancyCodes($this->db);
700 $result = $accountancy_codes->fetchAccountancyCodes($this->id);
701 if ($result < 0) {
702 $this->error = $accountancy_codes->error;
703 $this->errors = $accountancy_codes->errors;
704 $error++;
705 }
706
707 if (!$error) {
708 foreach ($accountancy_codes_model->accountancy_codes as $mode_key => $fields) {
709 foreach ($fields as $field_key => $value) {
710 $accountancy_codes->accountancy_codes[$mode_key][$field_key] = $value;
711 }
712 }
713
714 $result = $accountancy_codes->updateAccountancyCodes($user, $this->id, 0, $notrigger);
715 if ($result < 0) {
716 $this->error = $accountancy_codes->error;
717 $this->errors = $accountancy_codes->errors;
718 $error++;
719 }
720 }
721 }
722 }
723
724 if ($error) {
725 $this->db->rollback();
726 return -1;
727 } else {
728 $this->db->commit();
729 return 1;
730 }
731 }
732
738 public function fetchDepreciationLines()
739 {
740 global $langs;
741 $langs->load('assets');
742 $this->depreciation_lines = array();
743
744 // Clean parameters
745 $this->id = $this->id > 0 ? $this->id : 0;
746
747 // Check parameters
748 $error = 0;
749 if (empty($this->id)) {
750 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
751 $error++;
752 }
753 if ($error) {
754 return -1;
755 }
756
757 $sql = "SELECT ad.rowid, ad.depreciation_mode, ad.ref, ad.depreciation_date, ad.depreciation_ht, ad.cumulative_depreciation_ht,";
758 if (isModEnabled('accounting')) {
759 $sql .= " " . $this->db->ifsql('EXISTS (SELECT fk_docdet FROM ' . MAIN_DB_PREFIX . 'accounting_bookkeeping as ab WHERE ab.doc_type = \'asset\' AND ab.fk_docdet = ad.rowid)', '1', '0') . " AS bookkeeping";
760 } else {
761 $sql .= " 0 AS bookkeeping";
762 }
763 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
764 $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
765 $sql .= " ORDER BY ad.depreciation_date ASC";
766
767 $resql = $this->db->query($sql);
768 if (!$resql) {
769 $this->errors[] = $langs->trans('AssetErrorFetchDepreciationLines') . ': ' . $this->db->lasterror();
770 return -1;
771 }
772
773 while ($obj = $this->db->fetch_object($resql)) {
774 if (!isset($this->depreciation_lines[$obj->depreciation_mode])) {
775 $this->depreciation_lines[$obj->depreciation_mode] = array();
776 }
777 $this->depreciation_lines[$obj->depreciation_mode][] = array(
778 'id' => $obj->rowid,
779 'ref' => $obj->ref,
780 'depreciation_date' => $this->db->jdate($obj->depreciation_date),
781 'depreciation_ht' => $obj->depreciation_ht,
782 'cumulative_depreciation_ht' => $obj->cumulative_depreciation_ht,
783 'bookkeeping' => $obj->bookkeeping,
784 );
785 }
786
787 return 1;
788 }
789
796 {
797 global $langs;
798 if (is_object($langs)) { // $langs may be null when called from a page with NOREQUIRETRAN (like viewimage.php)
799 $langs->load('assets');
800 }
801
802 // Clean parameters
803 $this->id = $this->id > 0 ? $this->id : 0;
804
805 // Check parameters
806 $error = 0;
807 if (empty($this->id)) {
808 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
809 $error++;
810 }
811 if ($error) {
812 return -1;
813 }
814 if (!isModEnabled('accounting')) {
815 return 0;
816 }
817
818 // Old request with 'WITH'
819 /*
820 $sql = "WITH in_accounting_bookkeeping(fk_docdet) AS (";
821 $sql .= " SELECT DISTINCT fk_docdet";
822 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping";
823 $sql .= " WHERE doc_type = 'asset'";
824 $sql .= ")";
825 $sql .= "SELECT COUNT(*) AS has_bookkeeping";
826 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
827 $sql .= " LEFT JOIN in_accounting_bookkeeping as iab ON iab.fk_docdet = ad.rowid";
828 $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
829 $sql .= " AND iab.fk_docdet IS NOT NULL";
830 */
831
832 $sql = "SELECT COUNT(*) AS has_bookkeeping";
833 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
834 $sql .= " LEFT JOIN (SELECT DISTINCT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE doc_type = 'asset') AS iab ON iab.fk_docdet = ad.rowid";
835 $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
836 $sql .= " AND iab.fk_docdet IS NOT NULL";
837
838 $resql = $this->db->query($sql);
839 if (!$resql) {
840 $this->errors[] = $langs->trans('AssetErrorFetchDepreciationLines') . ': ' . $this->db->lasterror();
841 return -1;
842 }
843
844 if ($obj = $this->db->fetch_object($resql)) {
845 return $obj->has_bookkeeping > 0 ? 1 : 0;
846 }
847
848 return 0;
849 }
850
863 public function addDepreciationLine($mode, $ref, $depreciation_date, $depreciation_ht, $cumulative_depreciation_ht, $accountancy_code_debit, $accountancy_code_credit)
864 {
865 global $langs;
866 $langs->load('assets');
867
868 // Clean parameters
869 $this->id = $this->id > 0 ? $this->id : 0;
870 $mode = strtolower(trim($mode));
871 $ref = trim($ref);
872 $accountancy_code_debit = trim($accountancy_code_debit);
873 $accountancy_code_credit = trim($accountancy_code_credit);
874
875 // Check parameters
876 $error = 0;
877 if (empty($this->id)) {
878 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
879 $error++;
880 }
881 if ($error) {
882 return -1;
883 }
884
885 $sql = "INSERT INTO " . MAIN_DB_PREFIX . "asset_depreciation(fk_asset, depreciation_mode, ref, depreciation_date, depreciation_ht, cumulative_depreciation_ht, accountancy_code_debit, accountancy_code_credit)";
886 $sql .= " VALUES ( ";
887 $sql .= " " . (int) $this->id;
888 $sql .= ", '" . $this->db->escape($mode) . "'";
889 $sql .= ", '" . $this->db->escape($ref) . "'";
890 $sql .= ", '" . $this->db->idate($depreciation_date) . "'";
891 $sql .= ", " . (float) $depreciation_ht;
892 $sql .= ", " . (float) $cumulative_depreciation_ht;
893 $sql .= ", '" . $this->db->escape($accountancy_code_debit) . "'";
894 $sql .= ", '" . $this->db->escape($accountancy_code_credit) . "'";
895 $sql .= ")";
896
897 $resql = $this->db->query($sql);
898 if (!$resql) {
899 $this->errors[] = $langs->trans('AssetErrorAddDepreciationLine') . ': ' . $this->db->lasterror();
900 return -1;
901 }
902
903 return 1;
904 }
905
911 public function calculationDepreciation()
912 {
913 global $conf, $langs;
914 $langs->load('assets');
915
916 // Clean parameters
917 $this->id = $this->id > 0 ? $this->id : 0;
918
919 // Check parameters
920 $error = 0;
921 if (empty($this->id)) {
922 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
923 $error++;
924 }
925 if ($error) {
926 return -1;
927 }
928
929 if (! empty($this->not_depreciated)) {
930 return 1;
931 }
932
933 // Get depreciation options
934 //---------------------------
935 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
936 $options = new AssetDepreciationOptions($this->db);
937 $result = $options->fetchDeprecationOptions($this->id);
938 if ($result < 0) {
939 $this->error = $options->error;
940 $this->errors = $options->errors;
941 return -1;
942 }
943
944 // Get accountancy codes
945 //---------------------------
946 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetaccountancycodes.class.php';
947 $accountancy_codes = new AssetAccountancyCodes($this->db);
948 $result = $accountancy_codes->fetchAccountancyCodes($this->id);
949 if ($result < 0) {
950 $this->error = $accountancy_codes->error;
951 $this->errors = $accountancy_codes->errors;
952 return -1;
953 }
954
955 $this->db->begin();
956
957 // Delete old lines
958 $modes = array();
959 foreach ($options->deprecation_options as $mode_key => $fields) {
960 $modes[$mode_key] = $this->db->escape($mode_key);
961 }
962 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "asset_depreciation";
963 $sql .= " WHERE fk_asset = " . (int) $this->id;
964 $sql .= " AND depreciation_mode NOT IN ('" . $this->db->sanitize(implode("', '", $modes)) . "')";
965
966 $resql = $this->db->query($sql);
967 if (!$resql) {
968 $this->errors[] = $langs->trans('AssetErrorClearDepreciationLines') . ': ' . $this->db->lasterror();
969 $error++;
970 }
971
972 if (!$error) {
973 // Get fiscal period
974 require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
975 require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
976
977 // @FIXME getCurrentPeriodOfFiscalYear return the first period found. What if there is several ? And what if not closed ? And what if end date not yet defined.
978 $dates = getCurrentPeriodOfFiscalYear($this->db, $conf, $this->date_start > $this->date_acquisition ? $this->date_start : $this->date_acquisition);
979 $init_fiscal_period_start = $dates['date_start'];
980 $init_fiscal_period_end = $dates['date_end'];
981 /*
982 if (empty($init_fiscal_period_start) || empty($init_fiscal_period_end)) {
983 $pastmonthyear = $dates['pastmonthyear'];
984 $pastmonth = $dates['pastmonth'];
985 $init_fiscal_period_start = dol_get_first_day((int) $pastmonthyear, (int) $pastmonth, false);
986 $init_fiscal_period_end = dol_get_last_day((int) $pastmonthyear, (int) $pastmonth, false);
987 }
988 */
989
990 foreach ($options->deprecation_options as $mode_key => $fields) {
991 // Get last depreciation lines save in bookkeeping
992 //-----------------------------------------------------
993
994 // Old request with 'WITH'
995 /*
996 $sql = "WITH in_accounting_bookkeeping(fk_docdet) AS (";
997 $sql .= " SELECT fk_docdet";
998 $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping";
999 $sql .= " WHERE doc_type = 'asset'";
1000 $sql .= ")";
1001 $sql .= "SELECT ad.depreciation_date, ad.cumulative_depreciation_ht";
1002 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
1003 $sql .= " LEFT JOIN in_accounting_bookkeeping as iab ON iab.fk_docdet = ad.rowid";
1004 $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
1005 $sql .= " AND ad.depreciation_mode = '" . $this->db->escape($mode_key) . "'";
1006 $sql .= " AND iab.fk_docdet IS NOT NULL";
1007 $sql .= " ORDER BY ad.depreciation_date DESC";
1008 $sql .= " LIMIT 1";
1009 */
1010
1011 $last_depreciation_date = '';
1012 $last_cumulative_depreciation_ht = $this->reversal_amount_ht;
1013 if (isModEnabled('accounting')) {
1014 $sql = "SELECT ad.depreciation_date, ad.cumulative_depreciation_ht";
1015 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
1016 $sql .= " LEFT JOIN (SELECT DISTINCT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE doc_type = 'asset') AS iab ON iab.fk_docdet = ad.rowid";
1017 $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
1018 $sql .= " AND ad.depreciation_mode = '" . $this->db->escape($mode_key) . "'";
1019 $sql .= " AND iab.fk_docdet IS NOT NULL";
1020 $sql .= " ORDER BY ad.depreciation_date DESC";
1021 $sql .= " LIMIT 1";
1022
1023 $resql = $this->db->query($sql);
1024 if (!$resql) {
1025 $this->errors[] = $langs->trans('AssetErrorFetchMaxDepreciationDateForMode', $mode_key) . ': ' . $this->db->lasterror();
1026 $error++;
1027 break;
1028 }
1029 if ($obj = $this->db->fetch_object($resql)) {
1030 $last_depreciation_date = $this->db->jdate($obj->depreciation_date);
1031 $last_cumulative_depreciation_ht = $obj->cumulative_depreciation_ht;
1032 }
1033 }
1034
1035 // Set last cumulative depreciation
1036 $sql = "UPDATE " . MAIN_DB_PREFIX . $this->db->sanitize($options->deprecation_options_fields[$mode_key]['table']);
1037 $sql .= " SET total_amount_last_depreciation_ht = " . ((float) (empty($last_cumulative_depreciation_ht) ? 0 : $last_cumulative_depreciation_ht));
1038 $sql .= " WHERE fk_asset = " . (int) $this->id;
1039 $resql = $this->db->query($sql);
1040 if (!$resql) {
1041 $this->errors[] = $langs->trans('AssetErrorSetLastCumulativeDepreciation') . ': ' . $this->db->lasterror();
1042 $error++;
1043 break;
1044 }
1045
1046 // Delete old lines
1047 $sql = "DELETE FROM " . MAIN_DB_PREFIX . "asset_depreciation";
1048 $sql .= " WHERE fk_asset = " . (int) $this->id;
1049 $sql .= " AND depreciation_mode = '" . $this->db->escape($mode_key) . "'";
1050 if (isModEnabled('accounting')) {
1051 $sql .= " AND NOT EXISTS (SELECT fk_docdet FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping WHERE doc_type = 'asset' AND fk_docdet = " . MAIN_DB_PREFIX . "asset_depreciation.rowid)";
1052 }
1053 if ($last_depreciation_date !== "") {
1054 $sql .= " AND ref <> ''";
1055 }
1056 $resql = $this->db->query($sql);
1057 if (!$resql) {
1058 $this->errors[] = $langs->trans('AssetErrorClearDepreciationLines') . ': ' . $this->db->lasterror();
1059 $error++;
1060 break;
1061 }
1062
1063 // Get depreciation period
1064 $depreciation_date_start = $this->date_start > $this->date_acquisition ? $this->date_start : $this->date_acquisition;
1065 $depreciation_date_end = dol_time_plus_duree(dol_time_plus_duree((int) $depreciation_date_start, (float) $fields['duration'], $fields['duration_type'] == 1 ? 'm' : ($fields['duration_type'] == 2 ? 'd' : 'y')), -1, 'd');
1066 $depreciation_amount = $fields['amount_base_depreciation_ht'];
1067 if ($fields['duration_type'] == 2) { // Daily
1068 $fiscal_period_start = $depreciation_date_start;
1069 $fiscal_period_end = $depreciation_date_start;
1070 } elseif ($fields['duration_type'] == 1) { // Monthly
1071 $date_temp = dol_getdate((int) $depreciation_date_start);
1072 $fiscal_period_start = dol_get_first_day($date_temp['year'], $date_temp['mon'], false);
1073 $fiscal_period_end = dol_get_last_day($date_temp['year'], $date_temp['mon'], false);
1074 } else { // Annually
1075 $fiscal_period_start = $init_fiscal_period_start;
1076 $fiscal_period_end = $init_fiscal_period_end;
1077 }
1078 $cumulative_depreciation_ht = (float) $last_cumulative_depreciation_ht;
1079 $depreciation_period_amount = $depreciation_amount - (float) $this->reversal_amount_ht;
1080 $start_date = $depreciation_date_start;
1081 $disposal_date = isset($this->disposal_date) && $this->disposal_date !== "" ? $this->disposal_date : "";
1082 $finish_date = $disposal_date !== "" ? $disposal_date : $depreciation_date_end;
1083 $accountancy_code_depreciation_debit_key = $accountancy_codes->accountancy_codes_fields[$mode_key]['depreciation_debit'];
1084 $accountancy_code_depreciation_debit = $accountancy_codes->accountancy_codes[$mode_key][$accountancy_code_depreciation_debit_key] ?? '';
1085 $accountancy_code_depreciation_credit_key = $accountancy_codes->accountancy_codes_fields[$mode_key]['depreciation_credit'];
1086 $accountancy_code_credit = $accountancy_codes->accountancy_codes[$mode_key][$accountancy_code_depreciation_credit_key] ?? '';
1087
1088 // Reversal depreciation line
1089 //-----------------------------------------------------
1090 if ($last_depreciation_date === "" && ($depreciation_date_start < $fiscal_period_start || is_numeric($this->reversal_date))) {
1091 if (is_numeric($this->reversal_date)) {
1092 if ($this->reversal_date < $fiscal_period_start) {
1093 $this->errors[] = $langs->trans('AssetErrorReversalDateNotGreaterThanCurrentBeginFiscalDateForMode', $mode_key);
1094 $error++;
1095 break;
1096 }
1097
1098 if (empty($this->reversal_amount_ht)) {
1099 $this->errors[] = $langs->trans('AssetErrorReversalAmountNotProvidedForMode', $mode_key);
1100 $error++;
1101 break;
1102 }
1103
1104 $start_date = $this->reversal_date;
1105 $result = $this->addDepreciationLine($mode_key, '', $start_date, (float) $this->reversal_amount_ht, (float) $this->reversal_amount_ht, $accountancy_code_depreciation_debit, $accountancy_code_credit);
1106 if ($result < 0) {
1107 $error++;
1108 break;
1109 }
1110 } else {
1111 $this->errors[] = $langs->trans('AssetErrorReversalDateNotProvidedForMode', $mode_key);
1112 $error++;
1113 break;
1114 }
1115 }
1116
1117 // futures depreciation lines
1118 //-----------------------------------------------------
1119 $day_count_convention = getAssetDepreciationDayCountConvention();
1120 $period_amount = (float) ($fields['duration'] > 0 ? price2num($depreciation_period_amount / $fields['duration'], 'MT') : 0);
1121 $first_period_found = false;
1122
1123 // Degressive depreciation: the yearly rate is the coefficient times the straight line rate, applied on
1124 // the remaining value at the beginning of each fiscal year. As soon as the straight line depreciation of
1125 // the remaining value on the remaining duration gives more, this one is used.
1126 $is_degressive = ($fields['depreciation_type'] == 1 && (float) $fields['degressive_coefficient'] > 0 && $fields['duration'] > 0);
1127 if ($is_degressive && $fields['duration_type'] == 2) {
1128 $this->errors[] = $langs->trans('AssetErrorDegressiveDailyDurationForMode', $mode_key);
1129 $error++;
1130 break;
1131 }
1132 $degressive_rate = $is_degressive ? (float) $fields['degressive_coefficient'] * ($fields['duration_type'] == 1 ? 12 : 1) / $fields['duration'] : 0;
1133 $degressive_year_end = null;
1134 $degressive_year_rate = 0;
1135 $degressive_year_base = 0;
1136
1137 //$first_period_date = isset($begin_period) && $begin_period > $fiscal_period_start ? $begin_period : $fiscal_period_start;
1138 $first_period_date = $fiscal_period_start;
1139
1140 $ref_date_format = "%Y" . ($fields['duration_type'] == 1 || $fields['duration_type'] == 2 ? '-%m' : '') . ($fields['duration_type'] == 2 ? '-%d' : '');
1141
1142 // Loop security
1143 $idx_loop = 0;
1144 $max_loop = $fields['duration'] + 2;
1145 do {
1146 // Loop security
1147 $idx_loop++;
1148 if ($idx_loop > $max_loop) {
1149 break;
1150 }
1151
1152 if ($last_depreciation_date < $fiscal_period_end && ($first_period_date <= $start_date || $first_period_found)) {
1153 // Disposal not depreciated
1154 if ($fiscal_period_start <= $disposal_date && $disposal_date <= $fiscal_period_end && empty($this->disposal_depreciated)) {
1155 break;
1156 }
1157
1158 $first_period_found = true;
1159
1160 $period_begin = dol_print_date($fiscal_period_start, $ref_date_format);
1161 $period_end = dol_print_date($fiscal_period_end, $ref_date_format);
1162 $ref = $period_begin . ($period_begin != $period_end ? ' - ' . $period_end : '');
1163 if ($fiscal_period_start <= $disposal_date && $disposal_date <= $fiscal_period_end) {
1164 $ref .= ' - ' . $langs->transnoentitiesnoconv('AssetDisposal');
1165 }
1166
1167 $begin_date = $fiscal_period_start < $start_date && $start_date <= $fiscal_period_end ? $start_date : $fiscal_period_start;
1168 $end_date = $fiscal_period_start < $finish_date && $finish_date <= $fiscal_period_end ? $finish_date : $fiscal_period_end;
1169 if ($fields['duration_type'] == 2) { // Daily
1170 $depreciation_ht = $period_amount;
1171 } elseif ($fields['duration_type'] == 1) { // Monthly
1172 // Same rule as the annual branch: the count of the days and the length of a full
1173 // month must come from the same day count convention. Counting the real calendar
1174 // days then dividing them by a conventional month of 30 made the depreciation of a
1175 // partial month depend on the length of that month, and required a special case to
1176 // give a full February a whole monthly amount.
1177 $period_fraction = getAssetDepreciationMonthFraction($begin_date, $end_date, $day_count_convention, 'gmt');
1178 if ($is_degressive) {
1179 // The yearly amount is fixed at the beginning of each fiscal year, then spread on its months
1180 if ($degressive_year_end === null || $fiscal_period_start > $degressive_year_end) {
1181 $degressive_year_end = ($degressive_year_end === null ? $init_fiscal_period_end : $degressive_year_end);
1182 while ($fiscal_period_start > $degressive_year_end) {
1183 $next_fy = getNextFiscalYear($this->db, $degressive_year_end, 'gmt');
1184 $degressive_year_end = ($next_fy !== null ? $next_fy['date_end'] : dol_time_plus_duree($degressive_year_end, 1, 'y'));
1185 }
1186 $remaining_years = getAssetDepreciationPeriodFraction($begin_date, $depreciation_date_end, $day_count_convention, 'gmt');
1187 $degressive_year_rate = max($degressive_rate, $remaining_years > 0 ? 1 / $remaining_years : 1);
1188 $degressive_year_base = $depreciation_amount - (float) $cumulative_depreciation_ht;
1189 }
1190 $depreciation_ht = (float) price2num(min($depreciation_amount - (float) $cumulative_depreciation_ht, $degressive_year_base * $degressive_year_rate / 12 * $period_fraction), 'MT');
1191 } else {
1192 $depreciation_ht = (float) price2num($period_amount * $period_fraction, 'MT');
1193 }
1194 } else { // Annually, taking care for adjustments to shortened or extended periods (e.g., fiscal years of 9 or 15 months)
1195 // A standard fiscal year lasts 365 days, or 366 when it covers a leap day. Anything else
1196 // is a shortened or an extended fiscal year (e.g. 9 or 15 months), whose depreciation is
1197 // prorated with no upper limit.
1198 $nb_days_fiscal_period = num_between_day($fiscal_period_start, $fiscal_period_end, 1);
1199 $is_standard_fiscal_period = ($nb_days_fiscal_period >= 365 && $nb_days_fiscal_period <= 366);
1200
1201 if ($is_standard_fiscal_period && $begin_date <= $fiscal_period_start && $end_date >= $fiscal_period_end) {
1202 // The asset is depreciated over the whole fiscal year: full annuity, whatever the
1203 // convention. Computing a prorata here would give slightly less than a full annuity
1204 // with THIRTY_360 when the fiscal year ends in February (a 30/360 count ending on
1205 // Feb 28th or 29th is 358 or 359 days instead of 360).
1206 $period_fraction = 1;
1207 } else {
1208 // The count of the days and the number of days of a full year must always come from
1209 // the same day count convention, otherwise every partial period (so the first and the
1210 // last year of every asset) is over or under evaluated. Counting the real calendar
1211 // days then dividing them by 360 overestimated every prorata by about 1.39% (365/360).
1212 // The bounds are anchored on GMT midnight, so the calendar decomposition of
1213 // THIRTY_360 and ACT_ACT must be read in GMT too, otherwise a partial period is
1214 // prorated on a day shifted by the UTC offset of the server.
1215 $period_fraction = getAssetDepreciationPeriodFraction($begin_date, $end_date, $day_count_convention, 'gmt');
1216 if ($is_standard_fiscal_period) {
1217 // Never more than a full annuity on a standard fiscal year
1218 $period_fraction = min(1, $period_fraction);
1219 }
1220 }
1221 if ($is_degressive) {
1222 $remaining_value = $depreciation_amount - (float) $cumulative_depreciation_ht;
1223 $remaining_years = getAssetDepreciationPeriodFraction($begin_date, $depreciation_date_end, $day_count_convention, 'gmt');
1224 $year_rate = max($degressive_rate, $remaining_years > 0 ? 1 / $remaining_years : 1);
1225 $depreciation_ht = (float) price2num(min($remaining_value, $remaining_value * $year_rate * $period_fraction), 'MT');
1226 } else {
1227 $depreciation_ht = (float) price2num($period_amount * $period_fraction, 'MT');
1228 }
1229 }
1230 if (getDolGlobalInt('ASSET_ROUND_INTEGER_NUMBER_UPWARDS') == 1) {
1231 if ($idx_loop < $max_loop) { // avoid last depreciation value
1232 $depreciation_ht = ceil($depreciation_ht);
1233 }
1234 }
1235
1236 if ($fiscal_period_start <= $depreciation_date_end && $depreciation_date_end <= $fiscal_period_end) { // last period
1237 $depreciation_ht = (float) price2num($depreciation_amount - (float) $cumulative_depreciation_ht, 'MT');
1238 $cumulative_depreciation_ht = $depreciation_amount;
1239 } else {
1240 $cumulative_depreciation_ht += $depreciation_ht;
1241 }
1242
1243 $result = $this->addDepreciationLine($mode_key, $ref, $fiscal_period_end, $depreciation_ht, (float) $cumulative_depreciation_ht, $accountancy_code_depreciation_debit, $accountancy_code_credit);
1244 if ($result < 0) {
1245 $error++;
1246 break;
1247 }
1248 }
1249
1250 // Next fiscal period (+1 day/month/year)
1251 $fiscal_period_start = dol_time_plus_duree($fiscal_period_end, 1, 'd');
1252
1253 if ($fields['duration_type'] == 0) { // Annually - use fiscal year-end
1254 // Search for the NEXT fiscal year
1255 $next_fy = getNextFiscalYear($this->db, $fiscal_period_end, 'gmt');
1256
1257 if ($next_fy !== null) {
1258 // Exercise found in database
1259 $fiscal_period_start = $next_fy['date_start'];
1260 $fiscal_period_end = $next_fy['date_end'];
1261 } else {
1262 // If there is no subsequent fiscal year in the database, a one-year fiscal year is automatically generated.
1263 // based on the structure of the current fiscal year
1264 $current_fy_start_parts = dol_getdate($fiscal_period_start);
1265
1266 // Calculate the end: 1 year minus 1 day from the start
1267 $fiscal_period_end = dol_time_plus_duree(dol_time_plus_duree($fiscal_period_start, 1, 'y'), -1, 'd');
1268
1269 // If the amortization end date is exceeded, there is no need to continue after that.
1270 // The loop will end naturally with the while condition.
1271 }
1272 } elseif ($fields['duration_type'] == 1) { // Monthly
1273 $fiscal_period_end = dol_time_plus_duree(dol_time_plus_duree($fiscal_period_start, 1, 'm'), -1, 'd');
1274 } else { // Daily
1275 $fiscal_period_end = $fiscal_period_start;
1276 }
1277 $last_period_date = $disposal_date !== "" && $disposal_date < $depreciation_date_end ? $disposal_date : $depreciation_date_end;
1278 } while ($fiscal_period_start < $last_period_date);
1279
1280 if ($error) {
1281 break;
1282 }
1283 }
1284 }
1285
1286 if ($error) {
1287 $this->db->rollback();
1288 return -1;
1289 } else {
1290 $this->db->commit();
1291 return 1;
1292 }
1293 }
1294
1301 public function setLastCumulativeDepreciation($asset_depreciation_id)
1302 {
1303 global $langs;
1304 $langs->load('assets');
1305
1306 // Clean parameters
1307 $asset_depreciation_id = $asset_depreciation_id > 0 ? $asset_depreciation_id : 0;
1308
1309 // Check parameters
1310 $error = 0;
1311 if (empty($asset_depreciation_id)) {
1312 $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AssetDepreciation") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
1313 $error++;
1314 }
1315 if ($error) {
1316 return -1;
1317 }
1318
1319 $this->db->begin();
1320
1321 require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
1322 $options = new AssetDepreciationOptions($this->db);
1323
1324 // Get last depreciation lines save in bookkeeping
1325 //-----------------------------------------------------
1326 $sql = "SELECT fk_asset, depreciation_mode, cumulative_depreciation_ht";
1327 $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation";
1328 $sql .= " WHERE rowid = " . (int) $asset_depreciation_id;
1329 $resql = $this->db->query($sql);
1330 if (!$resql) {
1331 $this->errors[] = $langs->trans('AssetErrorFetchCumulativeDepreciation') . ': ' . $this->db->lasterror();
1332 $error++;
1333 } else {
1334 if ($obj = $this->db->fetch_object($resql)) {
1335 $mode_key = $obj->depreciation_mode;
1336 if (!empty($options->deprecation_options_fields[$mode_key])) {
1337 $sql = "UPDATE " . MAIN_DB_PREFIX . $this->db->sanitize($options->deprecation_options_fields[$mode_key]['table']);
1338 $sql .= " SET total_amount_last_depreciation_ht = " . ((float) $obj->cumulative_depreciation_ht);
1339 $sql .= " WHERE fk_asset = " . (int) $obj->fk_asset;
1340 $resql = $this->db->query($sql);
1341 if (!$resql) {
1342 $this->errors[] = $langs->trans('AssetErrorSetLastCumulativeDepreciation') . ': ' . $this->db->lasterror();
1343 $error++;
1344 }
1345 }
1346 }
1347 }
1348
1349 if ($error) {
1350 $this->db->rollback();
1351 return -1;
1352 } else {
1353 $this->db->commit();
1354 return 1;
1355 }
1356 }
1357
1366 public function dispose($user, $disposal_invoice_id, $notrigger = 0)
1367 {
1368 global $conf, $langs;
1369
1370 // Protection
1371 if ($this->status == self::STATUS_DISPOSED) {
1372 return 0;
1373 }
1374
1375 $this->db->begin();
1376
1377 $required_fields = array('disposal_date', 'disposal_date', 'fk_disposal_type');
1378 foreach ($required_fields as $field) {
1379 $this->fields[$field]['notnull'] = 1;
1380 }
1381 $result = $this->update($user, 1);
1382 foreach ($required_fields as $field) {
1383 $this->fields[$field]['notnull'] = 0;
1384 }
1385 if ($result > 0) {
1386 if ($disposal_invoice_id > 0) {
1387 $this->add_object_linked('facture', $disposal_invoice_id);
1388 }
1389 $result = $this->setStatusCommon($user, self::STATUS_DISPOSED, $notrigger, 'ASSET_DISPOSED');
1390 }
1391 if ($result > 0) {
1392 $result = $this->calculationDepreciation();
1393 }
1394
1395 if ($result < 0) {
1396 $this->db->rollback();
1397 } else {
1398 $this->db->commit();
1399 }
1400
1401 // Define output language
1402 if ($result > 0 && !getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1403 if (method_exists($this, 'generateDocument')) {
1404 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1405 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1406 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1407 $outputlangs = $langs;
1408 $newlang = '';
1409 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1410 $newlang = GETPOST('lang_id', 'aZ09');
1411 }
1412 if (!empty($newlang)) {
1413 $outputlangs = new Translate("", $conf);
1414 $outputlangs->setDefaultLang($newlang);
1415 }
1416 $model = $this->model_pdf;
1417 $ret = $this->fetch($this->id); // Reload to get new records
1418
1419 $this->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1420 }
1421 }
1422
1423 return $result;
1424 }
1425
1433 public function reopen($user, $notrigger = 0)
1434 {
1435 global $conf, $langs;
1436
1437 // Protection
1438 if ($this->status != self::STATUS_DISPOSED) {
1439 return 0;
1440 }
1441
1442
1443 $this->db->begin();
1444
1445 $this->disposal_date = null;
1446 $this->disposal_amount_ht = null;
1447 $this->fk_disposal_type = null;
1448 $this->disposal_depreciated = 0;
1449 $this->disposal_subject_to_vat = 0;
1450 $result = $this->update($user, 1);
1451 if ($result > 0) {
1452 $this->deleteObjectLinked(null, 'facture');
1453 $result = $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'ASSET_REOPEN');
1454 }
1455 if ($result > 0) {
1456 $result = $this->calculationDepreciation();
1457 }
1458
1459 if ($result < 0) {
1460 $this->db->rollback();
1461 } else {
1462 $this->db->commit();
1463 }
1464
1465 // Define output language
1466 if ($result > 0 && !getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) {
1467 if (method_exists($this, 'generateDocument')) {
1468 $hidedetails = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0);
1469 $hidedesc = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0);
1470 $hideref = (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0);
1471 $outputlangs = $langs;
1472 $newlang = '';
1473 if (getDolGlobalInt('MAIN_MULTILANGS') /* && empty($newlang) */ && GETPOST('lang_id', 'aZ09')) {
1474 $newlang = GETPOST('lang_id', 'aZ09');
1475 }
1476 if (!empty($newlang)) {
1477 $outputlangs = new Translate("", $conf);
1478 $outputlangs->setDefaultLang($newlang);
1479 }
1480 $model = $this->model_pdf;
1481 $ret = $this->fetch($this->id); // Reload to get new records
1482
1483 $this->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
1484 }
1485 }
1486
1487 return $result;
1488 }
1489
1501 public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1502 {
1503 global $db, $conf, $langs, $hookmanager;
1504 global $dolibarr_main_authentication, $dolibarr_main_demo;
1505 global $menumanager;
1506
1507 if (!empty($conf->dol_no_mouse_hover)) {
1508 $notooltip = 1; // Force disable tooltips
1509 }
1510
1511 $result = '';
1512
1513 $label = img_picto('', $this->picto).' <u>'.$langs->trans("Asset").'</u>';
1514 if (isset($this->status)) {
1515 $label .= ' '.$this->getLibStatut(5);
1516 }
1517 $label .= '<br>';
1518 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
1519
1520 $url = dol_buildpath('/asset/card.php', 1).'?id='.$this->id;
1521
1522 if ($option != 'nolink') {
1523 // Add param to save lastsearch_values or not
1524 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1525 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1526 $add_save_lastsearch_values = 1;
1527 }
1528 if ($add_save_lastsearch_values) {
1529 $url .= '&save_lastsearch_values=1';
1530 }
1531 }
1532
1533 $linkclose = '';
1534 if (empty($notooltip)) {
1535 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1536 $label = $langs->trans("ShowAsset");
1537 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1538 }
1539 $linkclose .= ' title="'.dolPrintHTMLForAttribute($label).'"';
1540 $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1541 } else {
1542 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1543 }
1544
1545 if ($option == 'nolink') {
1546 $linkstart = '<span';
1547 } else {
1548 $linkstart = '<a href="'.$url.'"';
1549 }
1550 $linkstart .= $linkclose.'>';
1551 if ($option == 'nolink') {
1552 $linkend = '</span>';
1553 } else {
1554 $linkend = '</a>';
1555 }
1556
1557 $result .= $linkstart;
1558
1559 if (empty($this->showphoto_on_popup)) {
1560 if ($withpicto) {
1561 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1562 }
1563 } else {
1564 if ($withpicto) {
1565 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1566
1567 list($class, $module) = explode('@', $this->picto);
1568 $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
1569 $filearray = dol_dir_list($upload_dir, "files");
1570 $filename = $filearray[0]['name'];
1571 if (!empty($filename)) {
1572 $pospoint = strpos($filearray[0]['name'], '.');
1573
1574 $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.dol_substr($filename, 0, $pospoint).'_mini'.dol_substr($filename, $pospoint);
1575 if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
1576 $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
1577 } else {
1578 $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
1579 }
1580
1581 $result .= '</div>';
1582 } else {
1583 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
1584 }
1585 }
1586 }
1587
1588 if ($withpicto != 2) {
1589 $name = $this->ref;
1590 if ($option == 'label') {
1591 $name = $this->label;
1592 } elseif ($option == 'with_label') {
1593 $name .= ' - ' . $this->label;
1594 }
1595 $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
1596 }
1597
1598 $result .= $linkend;
1599 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1600
1601 global $action;
1602 $hookmanager->initHooks(array($this->element . 'dao'));
1603 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1604 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1605 if ($reshook > 0) {
1606 $result = $hookmanager->resPrint;
1607 } else {
1608 $result .= $hookmanager->resPrint;
1609 }
1610 return $result;
1611 }
1612
1619 public function getLabelStatus($mode = 0)
1620 {
1621 return $this->LibStatut((int) $this->status, $mode);
1622 }
1623
1630 public function getLibStatut($mode = 0)
1631 {
1632 return $this->LibStatut((int) $this->status, $mode);
1633 }
1634
1635 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1643 public function LibStatut($status, $mode = 0)
1644 {
1645 // phpcs:enable
1646 if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
1647 global $langs;
1648 //$langs->load("assets");
1649 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('AssetInDraft');
1650 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('AssetInProgress');
1651 $this->labelStatus[self::STATUS_DISPOSED] = $langs->transnoentitiesnoconv('AssetDisposed');
1652 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('AssetInDraft');
1653 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('AssetInProgress');
1654 $this->labelStatusShort[self::STATUS_DISPOSED] = $langs->transnoentitiesnoconv('AssetDisposed');
1655 }
1656
1657 $statusType = 'status'.$status;
1658 if ($status == self::STATUS_VALIDATED) {
1659 $statusType = 'status4';
1660 }
1661 if ($status == self::STATUS_DISPOSED) {
1662 $statusType = 'status6';
1663 }
1664
1665 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1666 }
1667
1674 public function info($id)
1675 {
1676 $sql = "SELECT rowid, date_creation as datec, tms as datem, date_valid as datev,";
1677 $sql .= " fk_user_creat, fk_user_modif, fk_user_valid";
1678 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
1679 $sql .= " WHERE t.rowid = ".((int) $id);
1680
1681 $result = $this->db->query($sql);
1682 if ($result) {
1683 if ($this->db->num_rows($result)) {
1684 $obj = $this->db->fetch_object($result);
1685 $this->id = $obj->rowid;
1686
1687 $this->user_creation_id = $obj->fk_user_creat;
1688 $this->user_modification_id = $obj->fk_user_modif;
1689 $this->user_validation_id = $obj->fk_user_valid;
1690 $this->date_creation = $this->db->jdate($obj->datec);
1691 $this->date_modification = $this->db->jdate($obj->datem);
1692 $this->date_validation = $this->db->jdate($obj->datev);
1693 }
1694
1695 $this->db->free($result);
1696 } else {
1697 dol_print_error($this->db);
1698 }
1699 }
1700
1707 public function initAsSpecimen()
1708 {
1709 // Set here init that are not commonf fields
1710 // $this->property1 = ...
1711 // $this->property2 = ...
1712
1713 return $this->initAsSpecimenCommon();
1714 }
1715
1727 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1728 {
1729 global $langs;
1730
1731 $langs->load("assets");
1732
1733 if (!dol_strlen($modele)) {
1734 $modele = 'standard_asset';
1735
1736 if ($this->model_pdf) {
1737 $modele = $this->model_pdf;
1738 } elseif (getDolGlobalString('ASSET_ASSET_ADDON_PDF')) {
1739 $modele = getDolGlobalString('ASSET_ASSET_ADDON_PDF');
1740 }
1741 }
1742
1743 $modelpath = "core/modules/asset/doc/";
1744
1745 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1746 }
1747
1753 public function getNextNumRef()
1754 {
1755 global $langs, $conf;
1756 $langs->load("assets");
1757
1758 if (!getDolGlobalString('ASSET_ASSET_ADDON')) {
1759 $conf->global->ASSET_ASSET_ADDON = 'mod_asset_standard';
1760 }
1761
1762 if (getDolGlobalString('ASSET_ASSET_ADDON')) {
1763 $mybool = false;
1764
1765 $file = getDolGlobalString('ASSET_ASSET_ADDON') . ".php";
1766 $classname = getDolGlobalString('ASSET_ASSET_ADDON');
1767
1768 // Include file with class
1769 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1770 foreach ($dirmodels as $reldir) {
1771 $dir = dol_buildpath($reldir."core/modules/asset/");
1772
1773 // Load file with numbering class (if found)
1774 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1775 }
1776
1777 if (!$mybool) {
1778 dol_print_error(null, "Failed to include file ".$file);
1779 return '';
1780 }
1781
1782 if (class_exists($classname)) {
1783 $obj = new $classname();
1784
1785 '@phan-var-force ModeleNumRefAsset $obj';
1788 $numref = $obj->getNextValue($this);
1789
1790 if ($numref != '' && $numref != '-1') {
1791 return $numref;
1792 } else {
1793 $this->error = $obj->error;
1794 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1795 return "";
1796 }
1797 } else {
1798 print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
1799 return "";
1800 }
1801 } else {
1802 print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
1803 return "";
1804 }
1805 }
1806
1814 public function validate($user, $notrigger = 0)
1815 {
1816 global $conf;
1817
1818 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1819
1820 $error = 0;
1821
1822 // Protection
1823 if ($this->status == self::STATUS_VALIDATED) {
1824 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
1825 return 0;
1826 }
1827
1828 $now = dol_now();
1829
1830 $this->db->begin();
1831
1832 // Define new ref
1833 if (/* !$error && */ (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
1834 $num = $this->getNextNumRef();
1835 } else {
1836 $num = (string) $this->ref;
1837 }
1838 $this->newref = dol_sanitizeFileName($num);
1839
1840 // Validate
1841 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1842 $sql .= " SET ref = '".$this->db->escape($num)."',";
1843 $sql .= " status = ".self::STATUS_VALIDATED.",";
1844 $sql .= " date_valid='".$this->db->idate($now)."',";
1845 $sql .= " fk_user_valid = ".((int) $user->id);
1846 $sql .= " WHERE rowid = ".((int) $this->id);
1847
1848 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
1849 $resql = $this->db->query($sql);
1850 if (!$resql) {
1851 dol_print_error($this->db);
1852 $this->error = $this->db->lasterror();
1853 $error++;
1854 }
1855
1856 if (!$error && !$notrigger) {
1857 // Call trigger
1858 $result = $this->call_trigger('ASSET_VALIDATE', $user);
1859 if ($result < 0) {
1860 $error++;
1861 }
1862 // End call triggers
1863 }
1864
1865 if (!$error) {
1866 $this->oldref = $this->ref;
1867
1868 // Rename directory if dir was a temporary ref
1869 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1870 // Now we rename also files into index
1871 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'asset/".$this->db->escape($this->newref)."'";
1872 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'asset/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1873 $resql = $this->db->query($sql);
1874 if (!$resql) {
1875 $error++;
1876 $this->error = $this->db->lasterror();
1877 }
1878 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'asset/".$this->db->escape($this->newref)."'";
1879 $sql .= " WHERE filepath = 'asset/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1880 $resql = $this->db->query($sql);
1881 if (!$resql) {
1882 $error++;
1883 $this->error = $this->db->lasterror();
1884 }
1885
1886 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1887 $oldref = dol_sanitizeFileName($this->ref);
1888 $newref = dol_sanitizeFileName($num);
1889 $dirsource = $conf->asset->dir_output.'/'.$oldref;
1890 $dirdest = $conf->asset->dir_output.'/'.$newref;
1891 if (!$error && file_exists($dirsource)) {
1892 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
1893
1894 if (@rename($dirsource, $dirdest)) {
1895 dol_syslog("Rename ok");
1896 // Rename docs starting with $oldref with $newref
1897 $listoffiles = dol_dir_list($conf->asset->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1898 foreach ($listoffiles as $fileentry) {
1899 $dirsource = $fileentry['name'];
1900 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1901 $dirsource = $fileentry['path'].'/'.$dirsource;
1902 $dirdest = $fileentry['path'].'/'.$dirdest;
1903 @rename($dirsource, $dirdest);
1904 }
1905 }
1906 }
1907 }
1908 }
1909
1910 // Set new ref and current status
1911 if (!$error) {
1912 $this->ref = $num;
1913 $this->status = self::STATUS_VALIDATED;
1914 }
1915
1916 if (!$error) {
1917 $this->db->commit();
1918 return 1;
1919 } else {
1920 $this->db->rollback();
1921 return -1;
1922 }
1923 }
1924
1932 public function setDraft($user, $notrigger = 0)
1933 {
1934 // Protection
1935 if ($this->status <= self::STATUS_DRAFT) {
1936 return 0;
1937 }
1938
1939 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ASSET_UNVALIDATE');
1940 }
1941}
getCurrentPeriodOfFiscalYear($db, $conf, $from_time=null, $gm='tzserver', $withenddateonly=1)
Get current period of fiscal year?
getNextFiscalYear($db, $after_date, $gm='tzserver')
Get next fiscal year period after a given date.
getAssetDepreciationPeriodFraction($timestampStart, $timestampEnd, $convention='', $forcetimezone='')
Return the fraction of a year (the prorata temporis) between two dates, for a given day count convent...
getAssetDepreciationDayCountConvention()
Return the day count convention to use to compute the prorata temporis of a depreciation.
getAssetDepreciationMonthFraction($timestampStart, $timestampEnd, $convention='', $forcetimezone='')
Return the fraction of a month covered by a period, for the given day count convention.
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class for AssetAccountancyCodes.
Class for AssetDepreciationOptions.
Class for Asset.
getNomUrl($withpicto=0, $option='', $maxlen=0, $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
hasDepreciationLinesInBookkeeping()
If has depreciation lines in bookkeeping.
setDraft($user, $notrigger=0)
Set draft status.
dispose($user, $disposal_invoice_id, $notrigger=0)
Set dispose status.
validate($user, $notrigger=0)
Validate asset.
createFromClone(User $user, $fromid)
Clone an object into another one.
calculationDepreciation()
Calculation depreciation lines (reversal and future) for each mode.
__construct(DoliDB $db)
Constructor.
create(User $user, $notrigger=0)
Create object into database.
info($id)
Load the info information in the object.
getLabelStatus($mode=0)
Return the label of the status.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load list of objects in memory from the database.
fetch($id, $ref=null)
Load object in memory from the database.
LibStatut($status, $mode=0)
Return the status.
reopen($user, $notrigger=0)
Set back to validated status if disposed status.
getLibStatut($mode=0)
Return the label of the status.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
addDepreciationLine($mode, $ref, $depreciation_date, $depreciation_ht, $cumulative_depreciation_ht, $accountancy_code_debit, $accountancy_code_credit)
Add depreciation line for a mode.
fetchDepreciationLines()
Fetch depreciation lines for each mode in $this->depreciation_lines (sort by depreciation date)
setLastCumulativeDepreciation($asset_depreciation_id)
Set last cumulative depreciation for each mode.
update(User $user, $notrigger=0)
Update object into database.
setDataFromAssetModel(User $user, $notrigger=0)
Set asset model.
add_object_linked($origin=null, $origin_id=null, $f_user=null, $notrigger=0)
Add an object link into llx_element_element.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
deleteObjectLinked($sourceid=null, $sourcetype='', $targetid=null, $targettype='', $rowid=0, $f_user=null, $notrigger=0)
Delete all links between an object $this.
createCommon(User $user, $notrigger=0)
Create object in the database.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
updateCommon(User $user, $notrigger=0)
Update object into database.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
Class to manage Dolibarr database access.
Class to manage translations.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
dol_get_first_day($year, $month=1, $gm=false)
Return GMT time for first day of a month or year.
Definition date.lib.php:626
num_between_day($timestampStart, $timestampEnd, $lastday=0)
Function to return number of days between two dates (date must be UTC date !) Example: 2012-01-01 201...
dol_get_last_day($year, $month=12, $gm=false)
Return GMT time for last day of a month or year.
Definition date.lib.php:645
dol_time_plus_duree($time, $duration_value, $duration_unit, $ruleforendofmonth=0, $tz='')
Add a delay to a date.
Definition date.lib.php:127
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:66
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_substr($string, $start, $length=null, $stringencoding='', $trunconbytes=0)
Make a substring.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
dol_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183