assetdepreciationoptions.class.php 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546
  1. <?php
  2. /* Copyright (C) 2021 Open-Dsi <support@open-dsi.fr>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file asset/class/assetdepreciationoptions.class.php
  19. * \ingroup asset
  20. * \brief This file is a class file for AssetDepreciationOptions
  21. */
  22. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  23. /**
  24. * Class for AssetDepreciationOptions
  25. */
  26. class AssetDepreciationOptions extends CommonObject
  27. {
  28. /**
  29. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  30. */
  31. public $table_element = '';
  32. /**
  33. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  34. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  35. * 'label' the translation key.
  36. * 'picto' is code of a picto to show before value in forms
  37. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  38. * 'position' is the sort order of field.
  39. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  40. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  41. * 'noteditable' says if field is not editable (1 or 0)
  42. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  43. * 'index' if we want an index in database.
  44. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  45. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  46. * 'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
  47. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
  48. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  49. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  50. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  51. * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
  52. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  53. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  54. * 'validate' is 1 if need to validate with $this->validateField()
  55. * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
  56. * 'enabled_field' if the mode block or a field is enabled if another field equal a value (="mode_key:field_key:value")
  57. * 'only_on_asset' is 1 if only a field on a asset
  58. *
  59. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  60. */
  61. /**
  62. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  63. */
  64. public $fields = array();
  65. /**
  66. * @var array Array with all deprecation options info by mode.
  67. * Note : economic mode is mandatory and is the primary options
  68. */
  69. public $deprecation_options_fields = array(
  70. 'economic' => array(
  71. 'label' => 'AssetDepreciationOptionEconomic',
  72. 'table' => 'asset_depreciation_options_economic',
  73. 'fields' => array(
  74. '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',),
  75. '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'),
  76. 'duration' => array('type'=>'integer', 'label'=>'AssetDepreciationOptionDuration', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  77. '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',),
  78. '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")',),
  79. 'accelerated_depreciation_option' => array('type'=>'boolean', 'label'=>'AssetDepreciationOptionAcceleratedDepreciation', 'enabled'=>'1', 'position'=>60, 'column_break' => true, 'notnull'=>0, 'default'=>'0', 'visible'=>1, 'validate'=>'1',),
  80. 'amount_base_depreciation_ht' => array('type'=>'price', 'label'=>'AssetDepreciationOptionAmountBaseDepreciationHT', 'enabled'=>'isset($object)&&get_class($object)=="Asset"', 'only_on_asset'=>1, 'position'=>90, 'notnull'=>0, 'required'=>1, 'visible'=>1, 'default'=>'$object->reversal_amount_ht > 0 ? $object->reversal_amount_ht : $object->acquisition_value_ht', 'isameasure'=>'1', 'validate'=>'1',),
  81. 'amount_base_deductible_ht' => array('type'=>'price', 'label'=>'AssetDepreciationOptionAmountBaseDeductibleHT', 'enabled'=>'isset($object)&&get_class($object)=="Asset"', 'only_on_asset'=>1, 'position'=>100, 'notnull'=>0, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  82. 'total_amount_last_depreciation_ht' => array('type'=>'price', 'label'=>'AssetDepreciationOptionTotalAmountLastDepreciationHT', 'enabled'=>'isset($object)&&get_class($object)=="Asset"', 'only_on_asset'=>1, 'position'=>110, 'noteditable'=> 1, 'notnull'=>0, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  83. ),
  84. ),
  85. 'accelerated_depreciation' => array(
  86. 'label' => 'AssetDepreciationOptionAcceleratedDepreciation',
  87. 'table' => 'asset_depreciation_options_fiscal',
  88. 'enabled_field' => 'economic:accelerated_depreciation_option:1',
  89. 'fields' => array(
  90. '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',),
  91. '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'),
  92. 'duration' => array('type'=>'integer', 'label'=>'AssetDepreciationOptionDuration', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  93. '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',),
  94. '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")',),
  95. 'amount_base_depreciation_ht' => array('type'=>'price', 'label'=>'AssetDepreciationOptionAmountBaseDepreciationHT', 'enabled'=>'isset($object)&&get_class($object)=="Asset"', 'only_on_asset'=>1, 'position'=>80, 'column_break' => true, 'notnull'=>0, 'required'=>1, 'visible'=>1, 'default'=>'$object->reversal_amount_ht > 0 ? $object->reversal_amount_ht : $object->acquisition_value_ht', 'isameasure'=>'1', 'validate'=>'1',),
  96. 'amount_base_deductible_ht' => array('type'=>'price', 'label'=>'AssetDepreciationOptionAmountBaseDeductibleHT', 'enabled'=>'isset($object)&&get_class($object)=="Asset"', 'only_on_asset'=>1, 'position'=>90, 'notnull'=>0, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  97. 'total_amount_last_depreciation_ht' => array('type'=>'price', 'label'=>'AssetDepreciationOptionTotalAmountLastDepreciationHT', 'enabled'=>'isset($object)&&get_class($object)=="Asset"', 'only_on_asset'=>1, 'position'=>100, 'noteditable'=> 1, 'notnull'=>0, 'visible'=>1, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  98. ),
  99. ),
  100. );
  101. public $fk_asset;
  102. public $fk_asset_model;
  103. public $tms;
  104. public $fk_user_modif;
  105. /**
  106. * @var array Array with all deprecation options by mode.
  107. */
  108. public $deprecation_options = array();
  109. /**
  110. * Constructor
  111. *
  112. * @param DoliDb $db Database handler
  113. */
  114. public function __construct(DoliDB $db)
  115. {
  116. global $langs;
  117. $this->db = $db;
  118. // Translate some data of arrayofkeyval
  119. if (is_object($langs)) {
  120. foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
  121. if (!empty($mode_info['fields']) && is_array($mode_info['fields'])) {
  122. foreach ($mode_info['fields'] as $field_key => $field_info) {
  123. if (!empty($field_info['arrayofkeyval']) && is_array($field_info['arrayofkeyval'])) {
  124. foreach ($field_info['arrayofkeyval'] as $key => $val) {
  125. $this->deprecation_options_fields[$mode_key]['fields'][$field_key]['arrayofkeyval'][$key] = $langs->trans($val);
  126. }
  127. }
  128. }
  129. }
  130. }
  131. }
  132. }
  133. /**
  134. * Set object infos for a mode
  135. *
  136. * @param string $mode Depreciation mode (economic, accelerated_depreciation, ...)
  137. * @param int $class_type Type (0:asset, 1:asset model)
  138. * @param bool $all_field Get all fields
  139. * @return int <0 if KO, >0 if OK
  140. */
  141. public function setInfosForMode($mode, $class_type = 0, $all_field = false)
  142. {
  143. // Clean parameters
  144. $mode = strtolower(trim($mode));
  145. if (!empty($this->deprecation_options_fields[$mode])) {
  146. $this->table_element = $this->deprecation_options_fields[$mode]['table'];
  147. $this->fields = $this->deprecation_options_fields[$mode]['fields'];
  148. foreach ($this->fields as $field_key => $field_info) {
  149. if ((!empty($field_info['computed']) && !$all_field) || (!empty($field_info['only_on_asset']) && !empty($class_type))) {
  150. unset($this->fields[$field_key]);
  151. continue;
  152. }
  153. // Unset required option (notnull) if field disabled
  154. if (!empty($field_info['enabled_field'])) {
  155. $info = explode(':', $field_info['enabled_field']);
  156. if ($this->deprecation_options[$info[0]][$info[1]] != $info[2] && isset($this->fields[$field_key]['notnull'])) {
  157. unset($this->fields[$field_key]['notnull']);
  158. }
  159. }
  160. // Set value of the field in the object (for createCommon and setDeprecationOptionsFromPost functions)
  161. $this->{$field_key} = $this->deprecation_options[$mode][$field_key];
  162. }
  163. $this->fields['rowid'] = array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id");
  164. if (empty($class_type)) {
  165. $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',);
  166. } else {
  167. $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',);
  168. }
  169. $this->fields['tms'] = array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => '1', 'position' => 501, 'notnull' => 0, 'visible' => 0,);
  170. $this->fields['fk_user_modif'] = array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => '1', 'position' => 511, 'notnull' => -1, 'visible' => 0,);
  171. }
  172. return 1;
  173. }
  174. /**
  175. * Fill deprecation_options property of object (using for data sent by forms)
  176. *
  177. * @param int $class_type Type (0:asset, 1:asset model)
  178. * @return int <0 if KO, >0 if OK
  179. */
  180. public function setDeprecationOptionsFromPost($class_type = 0)
  181. {
  182. global $conf, $langs;
  183. $error = 0;
  184. $deprecation_options = array();
  185. foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
  186. $this->setInfosForMode($mode_key, $class_type);
  187. foreach ($mode_info['fields'] as $field_key => $field_info) {
  188. if (!empty($field_info['computed'])) {
  189. continue;
  190. }
  191. $html_name = $mode_key . '_' . $field_key;
  192. if ($field_info['type'] == 'duration') {
  193. if (GETPOST($html_name . 'hour') == '' && GETPOST($html_name . 'min') == '') {
  194. continue; // The field was not submited to be saved
  195. }
  196. } else {
  197. if (!GETPOSTISSET($html_name)) {
  198. continue; // The field was not submited to be saved
  199. }
  200. }
  201. // Ignore special fields
  202. if (in_array($field_key, array('rowid', 'entity', 'import_key'))) {
  203. continue;
  204. }
  205. if (in_array($field_key, array('date_creation', 'tms', 'fk_user_creat', 'fk_user_modif'))) {
  206. if (!in_array(abs($field_info['visible']), array(1, 3))) {
  207. continue; // Only 1 and 3 that are case to create
  208. }
  209. }
  210. // Set value to insert
  211. if (in_array($field_info['type'], array('text', 'html'))) {
  212. $value = GETPOST($html_name, 'restricthtml');
  213. } elseif ($field_info['type'] == 'date') {
  214. $value = dol_mktime(12, 0, 0, GETPOST($html_name . 'month', 'int'), GETPOST($html_name . 'day', 'int'), GETPOST($html_name . 'year', 'int')); // for date without hour, we use gmt
  215. } elseif ($field_info['type'] == 'datetime') {
  216. $value = dol_mktime(GETPOST($html_name . 'hour', 'int'), GETPOST($html_name . 'min', 'int'), GETPOST($html_name . 'sec', 'int'), GETPOST($html_name . 'month', 'int'), GETPOST($html_name . 'day', 'int'), GETPOST($html_name . 'year', 'int'), 'tzuserrel');
  217. } elseif ($field_info['type'] == 'duration') {
  218. $value = 60 * 60 * GETPOST($html_name . 'hour', 'int') + 60 * GETPOST($html_name . 'min', 'int');
  219. } elseif (preg_match('/^(integer|price|real|double)/', $field_info['type'])) {
  220. $value = price2num(GETPOST($html_name, 'alphanohtml')); // To fix decimal separator according to lang setup
  221. } elseif ($field_info['type'] == 'boolean') {
  222. $value = ((GETPOST($html_name) == '1' || GETPOST($html_name) == 'on') ? 1 : 0);
  223. } elseif ($field_info['type'] == 'reference') {
  224. // todo to check
  225. $tmparraykey = array(); //array_keys($object->param_list);
  226. $value = $tmparraykey[GETPOST($html_name)] . ',' . GETPOST($html_name . '2');
  227. } else {
  228. if ($field_key == 'lang') {
  229. $value = GETPOST($html_name, 'aZ09') ? GETPOST($html_name, 'aZ09') : "";
  230. } else {
  231. $value = GETPOST($html_name, 'alphanohtml');
  232. }
  233. }
  234. if (preg_match('/^integer:/i', $field_info['type']) && $value == '-1') {
  235. $value = ''; // This is an implicit foreign key field
  236. }
  237. if (!empty($field_info['foreignkey']) && $value == '-1') {
  238. $value = ''; // This is an explicit foreign key field
  239. }
  240. //var_dump($field_key.' '.$value.' '.$field_info['type']);
  241. $field_value = $value;
  242. if ($field_info['notnull'] > 0 && $field_value == '' && !is_null($field_info['default']) && $field_info['default'] == '(PROV)') {
  243. $field_value = '(PROV)';
  244. } elseif ((!empty($field_info['required']) || $field_info['notnull'] > 0) && $field_value == '' && !empty($field_info['default'])) {
  245. $field_value = dol_eval($field_info['default'], 1);
  246. }
  247. if ($field_info['notnull'] > 0 && $field_value == '' && is_null($field_info['default'])) {
  248. $error++;
  249. setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($field_info['label'])), null, 'errors');
  250. }
  251. $deprecation_options[$mode_key][$field_key] = $field_value;
  252. // Validation of fields values
  253. if ($conf->global->MAIN_FEATURE_LEVEL >= 2 || !empty($conf->global->MAIN_ACTIVATE_VALIDATION_RESULT)) {
  254. if (!$error && !empty($field_info['validate']) && is_callable(array($this, 'validateField'))) {
  255. if (!$this->validateField($mode_info['fields'], $field_key, $value)) {
  256. $error++;
  257. }
  258. }
  259. }
  260. }
  261. }
  262. // Unset not enabled modes
  263. foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
  264. if (!empty($mode_info['enabled_field'])) {
  265. $info = explode(':', $mode_info['enabled_field']);
  266. if ($deprecation_options[$info[0]][$info[1]] != $info[2]) {
  267. unset($deprecation_options[$info[0]][$info[1]]);
  268. }
  269. }
  270. }
  271. $this->deprecation_options = $deprecation_options;
  272. if ($error) {
  273. return -1;
  274. } else {
  275. return 1;
  276. }
  277. }
  278. /**
  279. * Load deprecation options of a asset or a asset model
  280. *
  281. * @param int $asset_id Asset ID to set
  282. * @param int $asset_model_id Asset model ID to set
  283. * @return int <0 if KO, >0 if OK
  284. */
  285. public function fetchDeprecationOptions($asset_id = 0, $asset_model_id = 0)
  286. {
  287. global $langs, $hookmanager;
  288. dol_syslog(__METHOD__ . " asset_id=$asset_id, asset_model_id=$asset_model_id");
  289. $error = 0;
  290. $this->errors = array();
  291. $this->deprecation_options = array();
  292. // Clean parameters
  293. $asset_id = $asset_id > 0 ? $asset_id : 0;
  294. $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
  295. if (!is_object($hookmanager)) {
  296. require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  297. $hookmanager = new HookManager($this->db);
  298. }
  299. $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
  300. $parameters = array('asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
  301. $reshook = $hookmanager->executeHooks('fetchDepreciationOptions', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  302. if (!empty($reshook)) {
  303. return $reshook;
  304. }
  305. // Check parameters
  306. if (empty($asset_id) && empty($asset_model_id)) {
  307. $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
  308. $error++;
  309. }
  310. if ($error) {
  311. dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
  312. return -1;
  313. }
  314. $class_type = $asset_id > 0 ? 0 : 1;
  315. $deprecation_options = array();
  316. foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
  317. $this->setInfosForMode($mode_key, $class_type);
  318. $result = $this->fetchCommon(0, '', " AND " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id));
  319. if ($result < 0) {
  320. $this->errors = array_merge(array($langs->trans('AssetErrorFetchDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
  321. $error++;
  322. } elseif ($result > 0) {
  323. foreach ($this->fields as $field_key => $field_info) {
  324. if (in_array($field_key, array('rowid', 'fk_asset', 'fk_asset_model', 'tms', 'fk_user_modif'))) continue;
  325. $deprecation_options[$mode_key][$field_key] = $this->{$field_key};
  326. }
  327. }
  328. }
  329. // Unset not enabled modes
  330. foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
  331. if (!empty($mode_info['enabled_field'])) {
  332. $info = explode(':', $mode_info['enabled_field']);
  333. if ($deprecation_options[$info[0]][$info[1]] != $info[2]) {
  334. unset($deprecation_options[$info[0]][$info[1]]);
  335. }
  336. }
  337. }
  338. if ($error) {
  339. dol_syslog(__METHOD__ . " Error fetch accountancy codes: " . $this->errorsToString(), LOG_ERR);
  340. return -1;
  341. } else {
  342. $this->deprecation_options = $deprecation_options;
  343. return 1;
  344. }
  345. }
  346. /**
  347. * get general depreciation info for a mode (used in depreciation card)
  348. *
  349. * @param string $mode Depreciation mode (economic, accelerated_depreciation, ...)
  350. * @return array|int <0 if KO otherwise array with general depreciation info
  351. */
  352. public function getGeneralDepreciationInfoForMode($mode)
  353. {
  354. global $hookmanager;
  355. dol_syslog(__METHOD__ . " mode=$mode");
  356. $this->errors = array();
  357. // Clean parameters
  358. $mode = strtolower(trim($mode));
  359. if (!is_object($hookmanager)) {
  360. require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  361. $hookmanager = new HookManager($this->db);
  362. }
  363. $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
  364. $parameters = array('mode' => $mode);
  365. $reshook = $hookmanager->executeHooks('getGeneralDepreciationInfoForMode', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  366. if ($reshook < 0) {
  367. return $reshook;
  368. } elseif ($reshook > 0) {
  369. return $hookmanager->resArray;
  370. }
  371. $duration_type_list = $this->deprecation_options_fields[$mode]['fields']['duration_type']['arrayofkeyval'];
  372. return array(
  373. 'base_depreciation_ht' => $this->deprecation_options[$mode]['amount_base_depreciation_ht'],
  374. 'duration' => $this->deprecation_options[$mode]['duration'],
  375. 'duration_type' => $duration_type_list[$this->deprecation_options[$mode]['duration_type']],
  376. 'rate' => $this->getRate($mode),
  377. );
  378. }
  379. /**
  380. * Update deprecation options of a asset or a asset model
  381. *
  382. * @param User $user User making update
  383. * @param int $asset_id Asset ID to set
  384. * @param int $asset_model_id Asset model ID to set
  385. * @param int $notrigger 1=disable trigger UPDATE (when called by create)
  386. * @return int <0 if KO, >0 if OK
  387. */
  388. public function updateDeprecationOptions($user, $asset_id = 0, $asset_model_id = 0, $notrigger = 0)
  389. {
  390. global $langs, $hookmanager;
  391. dol_syslog(__METHOD__ . " user_id={$user->id}, asset_id=$asset_id, asset_model_id=$asset_model_id, notrigger=$notrigger");
  392. $error = 0;
  393. $this->errors = array();
  394. // Clean parameters
  395. $asset_id = $asset_id > 0 ? $asset_id : 0;
  396. $asset_model_id = $asset_model_id > 0 ? $asset_model_id : 0;
  397. if (!is_object($hookmanager)) {
  398. require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  399. $hookmanager = new HookManager($this->db);
  400. }
  401. $hookmanager->initHooks(array('assetdepreciationoptionsdao'));
  402. $parameters = array('user' => $user, 'asset_id' => $asset_id, 'asset_model_id' => $asset_model_id);
  403. $reshook = $hookmanager->executeHooks('updateDepreciationOptions', $parameters, $this); // Note that $action and $object may have been modified by some hooks
  404. if (!empty($reshook)) {
  405. return $reshook;
  406. }
  407. // Check parameters
  408. if (empty($asset_id) && empty($asset_model_id)) {
  409. $this->errors[] = $langs->trans('AssetErrorAssetOrAssetModelIDNotProvide');
  410. $error++;
  411. }
  412. if ($error) {
  413. dol_syslog(__METHOD__ . " Error check parameters: " . $this->errorsToString(), LOG_ERR);
  414. return -1;
  415. }
  416. $this->db->begin();
  417. if ($asset_id > 0) {
  418. $this->fk_asset = $asset_id;
  419. $class_type = 0;
  420. } else {
  421. $this->fk_asset_model = $asset_model_id;
  422. $class_type = 1;
  423. }
  424. $this->tms = dol_now();
  425. $this->fk_user_modif = $user->id;
  426. foreach ($this->deprecation_options_fields as $mode_key => $mode_info) {
  427. // Delete old accountancy codes
  428. $sql = "DELETE FROM " . MAIN_DB_PREFIX . $mode_info['table'];
  429. $sql .= " WHERE " . ($asset_id > 0 ? " fk_asset = " . (int) $asset_id : " fk_asset_model = " . (int) $asset_model_id);
  430. $resql = $this->db->query($sql);
  431. if (!$resql) {
  432. $this->errors[] = $langs->trans('AssetErrorDeleteDepreciationOptionsForMode', $mode_key) . ': ' . $this->db->lasterror();
  433. $error++;
  434. }
  435. if (!$error && !empty($this->deprecation_options[$mode_key])) {
  436. if (!empty($mode_info['enabled_field'])) {
  437. $info = explode(':', $mode_info['enabled_field']);
  438. if ($this->deprecation_options[$info[0]][$info[1]] != $info[2]) {
  439. continue;
  440. }
  441. }
  442. $this->setInfosForMode($mode_key, $class_type);
  443. $result = $this->createCommon($user, 1);
  444. if ($result < 0) {
  445. $this->errors = array_merge(array($langs->trans('AssetErrorInsertDepreciationOptionsForMode', $mode_key) . ':'), $this->errors);
  446. $error++;
  447. }
  448. }
  449. }
  450. if (!$error && $this->fk_asset > 0) {
  451. // Calculation of depreciation lines (reversal and future)
  452. require_once DOL_DOCUMENT_ROOT . '/asset/class/asset.class.php';
  453. $asset = new Asset($this->db);
  454. $result = $asset->fetch($this->fk_asset);
  455. if ($result > 0) $result = $asset->calculationDepreciation();
  456. if ($result < 0) {
  457. $this->errors[] = $langs->trans('AssetErrorCalculationDepreciationLines');
  458. $this->errors[] = $asset->errorsToString();
  459. $error++;
  460. }
  461. }
  462. if (!$error && !$notrigger) {
  463. // Call trigger
  464. $result = $this->call_trigger('ASSET_DEPRECIATION_OPTIONS_MODIFY', $user);
  465. if ($result < 0) {
  466. $error++;
  467. }
  468. // End call triggers
  469. }
  470. if ($error) {
  471. $this->db->rollback();
  472. return -1;
  473. } else {
  474. $this->db->commit();
  475. return 1;
  476. }
  477. }
  478. /**
  479. * Get rate
  480. *
  481. * @param string $mode Depreciation mode (economic, accelerated_depreciation, ...)
  482. * @return string Rate of the provided mode option
  483. */
  484. public function getRate($mode)
  485. {
  486. $duration = $this->deprecation_options[$mode]["duration"] > 0 ? $this->deprecation_options[$mode]["duration"] : 0;
  487. $duration_type = $this->deprecation_options[$mode]["duration_type"] > 0 ? $this->deprecation_options[$mode]["duration_type"] : 0;
  488. return price(price2num($duration > 0 ? (100 * ($duration_type == 1 ? 12 : 1) / $duration) : 0, 2));
  489. }
  490. }