asset.class.php 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2018 Alexandre Spangaro <aspangaro@open-dsi.fr>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file asset/class/asset.class.php
  20. * \ingroup asset
  21. * \brief This file is a CRUD class file for Asset (Create/Read/Update/Delete)
  22. */
  23. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  24. /**
  25. * Class for Asset
  26. */
  27. class Asset extends CommonObject
  28. {
  29. /**
  30. * @var string ID of module.
  31. */
  32. public $module = 'asset';
  33. /**
  34. * @var string ID to identify managed object.
  35. */
  36. public $element = 'asset';
  37. /**
  38. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  39. */
  40. public $table_element = 'asset';
  41. /**
  42. * @var int Does this object support multicompany module ?
  43. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  44. */
  45. public $ismultientitymanaged = 1;
  46. /**
  47. * @var int Does object support extrafields ? 0=No, 1=Yes
  48. */
  49. public $isextrafieldmanaged = 1;
  50. /**
  51. * @var string String with name of icon for asset. Must be the part after the 'object_' into object_asset.png
  52. */
  53. public $picto = 'asset';
  54. const STATUS_DRAFT = 0; // In progress
  55. const STATUS_DISPOSED = 9; // Disposed
  56. /**
  57. * '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')
  58. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  59. * 'label' the translation key.
  60. * 'picto' is code of a picto to show before value in forms
  61. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  62. * 'position' is the sort order of field.
  63. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  64. * '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)
  65. * 'noteditable' says if field is not editable (1 or 0)
  66. * '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.
  67. * 'index' if we want an index in database.
  68. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  69. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  70. * '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)
  71. * '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'
  72. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  73. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  74. * '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.
  75. * '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'
  76. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  77. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  78. * 'validate' is 1 if need to validate with $this->validateField()
  79. * 'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
  80. *
  81. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  82. */
  83. /**
  84. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  85. */
  86. public $fields=array(
  87. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  88. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>1, 'noteditable'=>'0', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'validate'=>'1', 'comment'=>"Reference of object"),
  89. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2', 'validate'=>'1',),
  90. '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',),
  91. 'qty' => array('type'=>'real', 'label'=>'Qty', 'enabled'=>'1', 'position'=>50, 'notnull'=>1, 'visible'=>0, 'default'=>'1', 'isameasure'=>'1', 'css'=>'maxwidth75imp', 'validate'=>'1',),
  92. 'acquisition_type' => array('type'=>'smallint', 'label'=>'AssetAcquisitionType', 'enabled'=>'1', 'position'=>60, 'notnull'=>1, 'visible'=>1, 'arrayofkeyval'=>array('0'=>'AssetAcquisitionTypeNew', '1'=>'AssetAcquisitionTypeOccasion'), 'validate'=>'1',),
  93. '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',),
  94. 'not_depreciated' => array('type'=>'boolean', 'label'=>'AssetNotDepreciated', 'enabled'=>'1', 'position'=>80, 'notnull'=>0, 'default'=>'0', 'visible'=>1, 'validate'=>'1',),
  95. 'date_acquisition' => array('type'=>'date', 'label'=>'AssetDateAcquisition', 'enabled'=>'1', 'position'=>90, 'notnull'=>1, 'visible'=>1,),
  96. 'date_start' => array('type'=>'date', 'label'=>'AssetDateStart', 'enabled'=>'1', 'position'=>100, 'notnull'=>0, 'visible'=>-1,),
  97. 'acquisition_value_ht' => array('type'=>'price', 'label'=>'AssetAcquisitionValueHT', 'enabled'=>'1', 'position'=>110, 'notnull'=>1, 'visible'=>1, 'isameasure'=>'1', 'validate'=>'1',),
  98. 'recovered_vat' => array('type'=>'price', 'label'=>'AssetRecoveredVAT', 'enabled'=>'1', 'position'=>120, 'notnull'=>0, 'visible'=>1, 'isameasure'=>'1', 'validate'=>'1',),
  99. 'reversal_date' => array('type'=>'date', 'label'=>'AssetReversalDate', 'enabled'=>'1', 'position'=>130, 'notnull'=>0, 'visible'=>1,),
  100. 'reversal_amount_ht' => array('type'=>'price', 'label'=>'AssetReversalAmountHT', 'enabled'=>'1', 'position'=>140, 'notnull'=>0, 'visible'=>1, 'isameasure'=>'1', 'validate'=>'1',),
  101. 'disposal_date' => array('type'=>'date', 'label'=>'AssetDisposalDate', 'enabled'=>'1', 'position'=>200, 'notnull'=>0, 'visible'=>-2,),
  102. 'disposal_amount_ht' => array('type'=>'price', 'label'=>'AssetDisposalAmount', 'enabled'=>'1', 'position'=>210, 'notnull'=>0, 'visible'=>-2, 'default'=>'0', 'isameasure'=>'1', 'validate'=>'1',),
  103. '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',),
  104. 'disposal_depreciated' => array('type'=>'boolean', 'label'=>'AssetDisposalDepreciated', 'enabled'=>'1', 'position'=>230, 'notnull'=>0, 'default'=>'0', 'visible'=>-2, 'validate'=>'1',),
  105. 'disposal_subject_to_vat' => array('type'=>'boolean', 'label'=>'AssetDisposalSubjectToVat', 'enabled'=>'1', 'position'=>240, 'notnull'=>0, 'default'=>'0', 'visible'=>-2, 'validate'=>'1',),
  106. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>300, 'notnull'=>0, 'visible'=>0, 'validate'=>'1',),
  107. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>301, 'notnull'=>0, 'visible'=>0, 'validate'=>'1',),
  108. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
  109. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
  110. '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',),
  111. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
  112. 'last_main_doc' => array('type'=>'varchar(255)', 'label'=>'LastMainDoc', 'enabled'=>'1', 'position'=>600, 'notnull'=>0, 'visible'=>0,),
  113. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
  114. 'model_pdf' => array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>'1', 'position'=>1010, 'notnull'=>-1, 'visible'=>0,),
  115. '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',),
  116. );
  117. public $rowid;
  118. public $ref;
  119. public $label;
  120. public $fk_asset_model;
  121. public $reversal_amount_ht;
  122. public $acquisition_value_ht;
  123. public $recovered_vat;
  124. public $reversal_date;
  125. public $date_acquisition;
  126. public $date_start;
  127. public $qty;
  128. public $acquisition_type;
  129. public $asset_type;
  130. public $not_depreciated;
  131. public $disposal_date;
  132. public $disposal_amount_ht;
  133. public $fk_disposal_type;
  134. public $disposal_depreciated;
  135. public $disposal_subject_to_vat;
  136. public $supplier_invoice_id;
  137. public $note_public;
  138. public $note_private;
  139. public $date_creation;
  140. public $tms;
  141. public $fk_user_creat;
  142. public $fk_user_modif;
  143. public $last_main_doc;
  144. public $import_key;
  145. public $model_pdf;
  146. public $status;
  147. public $user_cloture_id;
  148. /**
  149. * @var Asset object oldcopy
  150. */
  151. public $oldcopy;
  152. /**
  153. * @var AssetDepreciationOptions Used for computed fields of depreciation options class.
  154. */
  155. public $asset_depreciation_options;
  156. /**
  157. * @var array List of depreciation lines for each mode (sort by depreciation date).
  158. */
  159. public $depreciation_lines = array();
  160. /**
  161. * Constructor
  162. *
  163. * @param DoliDb $db Database handler
  164. */
  165. public function __construct(DoliDB $db)
  166. {
  167. global $conf, $langs;
  168. $this->db = $db;
  169. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  170. $this->fields['rowid']['visible'] = 0;
  171. }
  172. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  173. $this->fields['entity']['enabled'] = 0;
  174. }
  175. // Unset fields that are disabled
  176. foreach ($this->fields as $key => $val) {
  177. if (isset($val['enabled']) && empty($val['enabled'])) {
  178. unset($this->fields[$key]);
  179. }
  180. }
  181. // Translate some data of arrayofkeyval
  182. if (is_object($langs)) {
  183. foreach ($this->fields as $key => $val) {
  184. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  185. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  186. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  187. }
  188. }
  189. }
  190. }
  191. }
  192. /**
  193. * Create object into database
  194. *
  195. * @param User $user User that creates
  196. * @param bool $notrigger false=launch triggers after, true=disable triggers
  197. * @return int <0 if KO, Id of created object if OK
  198. */
  199. public function create(User $user, $notrigger = false)
  200. {
  201. if (!isset($this->date_start) || $this->date_start === "") $this->date_start = $this->date_acquisition;
  202. $this->db->begin();
  203. $result = $result_create = $this->createCommon($user, $notrigger);
  204. if ($result > 0 && $this->fk_asset_model > 0) $result = $this->setDataFromAssetModel($user, $notrigger);
  205. if ($result > 0) {
  206. if ($this->supplier_invoice_id > 0) $this->add_object_linked('invoice_supplier', $this->supplier_invoice_id);
  207. }
  208. if ($result < 0) {
  209. $this->db->rollback();
  210. } else {
  211. $this->db->commit();
  212. }
  213. return $result > 0 ? $result_create : $result;
  214. }
  215. /**
  216. * Clone an object into another one
  217. *
  218. * @param User $user User that creates
  219. * @param int $fromid Id of object to clone
  220. * @return mixed New object created, <0 if KO
  221. */
  222. public function createFromClone(User $user, $fromid)
  223. {
  224. global $langs, $extrafields;
  225. $error = 0;
  226. dol_syslog(__METHOD__, LOG_DEBUG);
  227. // $object = new self($this->db);
  228. //
  229. // $this->db->begin();
  230. //
  231. // // Load source object
  232. // $result = $object->fetchCommon($fromid);
  233. // if ($result > 0 && !empty($object->table_element_line)) {
  234. // $object->fetchLines();
  235. // }
  236. //
  237. // // get lines so they will be clone
  238. // //foreach($this->lines as $line)
  239. // // $line->fetch_optionals();
  240. //
  241. // // Reset some properties
  242. // unset($object->id);
  243. // unset($object->fk_user_creat);
  244. // unset($object->import_key);
  245. //
  246. // // Clear fields
  247. // if (property_exists($object, 'ref')) {
  248. // $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  249. // }
  250. // if (property_exists($object, 'label')) {
  251. // $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  252. // }
  253. // if (property_exists($object, 'status')) {
  254. // $object->status = self::STATUS_DRAFT;
  255. // }
  256. // if (property_exists($object, 'date_creation')) {
  257. // $object->date_creation = dol_now();
  258. // }
  259. // if (property_exists($object, 'date_modification')) {
  260. // $object->date_modification = null;
  261. // }
  262. // // ...
  263. // // Clear extrafields that are unique
  264. // if (is_array($object->array_options) && count($object->array_options) > 0) {
  265. // $extrafields->fetch_name_optionals_label($this->table_element);
  266. // foreach ($object->array_options as $key => $option) {
  267. // $shortkey = preg_replace('/options_/', '', $key);
  268. // if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  269. // //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  270. // unset($object->array_options[$key]);
  271. // }
  272. // }
  273. // }
  274. //
  275. // // Create clone
  276. // $object->context['createfromclone'] = 'createfromclone';
  277. // $result = $object->createCommon($user);
  278. // if ($result < 0) {
  279. // $error++;
  280. // $this->error = $object->error;
  281. // $this->errors = $object->errors;
  282. // }
  283. //
  284. // if (!$error) {
  285. // // copy internal contacts
  286. // if ($this->copy_linked_contact($object, 'internal') < 0) {
  287. // $error++;
  288. // }
  289. // }
  290. //
  291. // if (!$error) {
  292. // // copy external contacts if same company
  293. // if (property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
  294. // if ($this->copy_linked_contact($object, 'external') < 0) {
  295. // $error++;
  296. // }
  297. // }
  298. // }
  299. //
  300. // unset($object->context['createfromclone']);
  301. //
  302. // // End
  303. // if (!$error) {
  304. // $this->db->commit();
  305. // return $object;
  306. // } else {
  307. // $this->db->rollback();
  308. // return -1;
  309. // }
  310. return -1;
  311. }
  312. /**
  313. * Load object in memory from the database
  314. *
  315. * @param int $id Id object
  316. * @param string $ref Ref
  317. * @return int <0 if KO, 0 if not found, >0 if OK
  318. */
  319. public function fetch($id, $ref = null)
  320. {
  321. $result = $this->fetchCommon($id, $ref);
  322. if ($result > 0) {
  323. if (!empty($this->table_element_line)) $this->fetchLines();
  324. $res = $this->hasDepreciationLinesInBookkeeping();
  325. if ($res < 0) {
  326. return -1;
  327. } elseif ($res > 0) {
  328. $this->fields['date_acquisition']['noteditable'] = '1';
  329. $this->fields['date_start']['noteditable'] = '1';
  330. $this->fields['acquisition_value_ht']['noteditable'] = '1';
  331. $this->fields['recovered_vat']['noteditable'] = '1';
  332. $this->fields['reversal_date']['noteditable'] = '1';
  333. $this->fields['reversal_amount_ht']['noteditable'] = '1';
  334. }
  335. }
  336. return $result;
  337. }
  338. /**
  339. * Load object lines in memory from the database
  340. *
  341. * @return int <0 if KO, 0 if not found, >0 if OK
  342. */
  343. public function fetchLines()
  344. {
  345. $this->lines = array();
  346. return 1;
  347. }
  348. /**
  349. * Load list of objects in memory from the database.
  350. *
  351. * @param string $sortorder Sort Order
  352. * @param string $sortfield Sort field
  353. * @param int $limit limit
  354. * @param int $offset Offset
  355. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  356. * @param string $filtermode Filter mode (AND or OR)
  357. * @return array|int int <0 if KO, array of pages if OK
  358. */
  359. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  360. {
  361. global $conf;
  362. dol_syslog(__METHOD__, LOG_DEBUG);
  363. $records = array();
  364. $sql = "SELECT ";
  365. $sql .= $this->getFieldList('t');
  366. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  367. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  368. $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
  369. } else {
  370. $sql .= " WHERE 1 = 1";
  371. }
  372. // Manage filter
  373. $sqlwhere = array();
  374. if (count($filter) > 0) {
  375. foreach ($filter as $key => $value) {
  376. if ($key == 't.rowid') {
  377. $sqlwhere[] = $key." = ".((int) $value);
  378. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  379. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  380. } elseif ($key == 'customsql') {
  381. $sqlwhere[] = $value;
  382. } elseif (strpos($value, '%') === false) {
  383. $sqlwhere[] = $key." IN (".$this->db->sanitize($this->db->escape($value)).")";
  384. } else {
  385. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  386. }
  387. }
  388. }
  389. if (count($sqlwhere) > 0) {
  390. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  391. }
  392. if (!empty($sortfield)) {
  393. $sql .= $this->db->order($sortfield, $sortorder);
  394. }
  395. if (!empty($limit)) {
  396. $sql .= $this->db->plimit($limit, $offset);
  397. }
  398. $resql = $this->db->query($sql);
  399. if ($resql) {
  400. $num = $this->db->num_rows($resql);
  401. $i = 0;
  402. while ($i < ($limit ? min($limit, $num) : $num)) {
  403. $obj = $this->db->fetch_object($resql);
  404. $record = new self($this->db);
  405. $record->setVarsFromFetchObj($obj);
  406. $records[$record->id] = $record;
  407. $i++;
  408. }
  409. $this->db->free($resql);
  410. return $records;
  411. } else {
  412. $this->errors[] = 'Error '.$this->db->lasterror();
  413. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  414. return -1;
  415. }
  416. }
  417. /**
  418. * Update object into database
  419. *
  420. * @param User $user User that modifies
  421. * @param bool $notrigger false=launch triggers after, true=disable triggers
  422. * @return int <0 if KO, >0 if OK
  423. */
  424. public function update(User $user, $notrigger = false)
  425. {
  426. if (!isset($this->date_start) || $this->date_start === "") $this->date_start = $this->date_acquisition;
  427. $this->db->begin();
  428. $result = $this->updateCommon($user, $notrigger);
  429. if ($result > 0 && $this->fk_asset_model > 0 && $this->fk_asset_model != $this->oldcopy->fk_asset_model) {
  430. $result = $this->setDataFromAssetModel($user, $notrigger);
  431. }
  432. if ($result > 0 && (
  433. $this->date_start != $this->oldcopy->date_start ||
  434. $this->acquisition_value_ht != $this->oldcopy->acquisition_value_ht ||
  435. $this->reversal_date != $this->oldcopy->reversal_date ||
  436. $this->reversal_amount_ht != $this->oldcopy->reversal_amount_ht ||
  437. ($this->fk_asset_model > 0 && $this->fk_asset_model != $this->oldcopy->fk_asset_model)
  438. )
  439. ) {
  440. $result = $this->calculationDepreciation();
  441. }
  442. if ($result < 0) {
  443. $this->db->rollback();
  444. } else {
  445. $this->db->commit();
  446. }
  447. return $result;
  448. }
  449. /**
  450. * Delete object in database
  451. *
  452. * @param User $user User that deletes
  453. * @param bool $notrigger false=launch triggers after, true=disable triggers
  454. * @return int <0 if KO, >0 if OK
  455. */
  456. public function delete(User $user, $notrigger = false)
  457. {
  458. return $this->deleteCommon($user, $notrigger);
  459. //return $this->deleteCommon($user, $notrigger, 1);
  460. }
  461. /**
  462. * Set asset model
  463. *
  464. * @param User $user User that creates
  465. * @param bool $notrigger false=launch triggers after, true=disable triggers
  466. * @return int <0 if KO, Id of created object if OK
  467. */
  468. public function setDataFromAssetModel(User $user, $notrigger = false)
  469. {
  470. global $langs;
  471. $langs->load('assets');
  472. // Clean parameters
  473. $this->id = $this->id > 0 ? $this->id : 0;
  474. $this->fk_asset_model = $this->fk_asset_model > 0 ? $this->fk_asset_model : 0;
  475. // Check parameters
  476. $error = 0;
  477. if (empty($this->id)) {
  478. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  479. $error++;
  480. }
  481. if (empty($this->fk_asset_model)) {
  482. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AssetModel") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  483. $error++;
  484. }
  485. if ($error) {
  486. return -1;
  487. }
  488. $this->db->begin();
  489. // Get depreciation options
  490. //---------------------------
  491. require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
  492. $options_model = new AssetDepreciationOptions($this->db);
  493. $result = $options_model->fetchDeprecationOptions(0, $this->fk_asset_model);
  494. if ($result < 0) {
  495. $this->error = $options_model->error;
  496. $this->errors = $options_model->errors;
  497. $error++;
  498. } elseif ($result > 0) {
  499. $options = new AssetDepreciationOptions($this->db);
  500. $result = $options->fetchDeprecationOptions($this->id);
  501. if ($result < 0) {
  502. $this->error = $options->error;
  503. $this->errors = $options->errors;
  504. $error++;
  505. }
  506. if (!$error) {
  507. foreach ($options_model->deprecation_options as $mode_key => $fields) {
  508. foreach ($fields as $field_key => $value) {
  509. $options->deprecation_options[$mode_key][$field_key] = $value;
  510. }
  511. }
  512. $result = $options->updateDeprecationOptions($user, $this->id, 0, $notrigger);
  513. if ($result < 0) {
  514. $this->error = $options->error;
  515. $this->errors = $options->errors;
  516. $error++;
  517. }
  518. }
  519. }
  520. // Get accountancy codes
  521. //---------------------------
  522. if (!$error) {
  523. require_once DOL_DOCUMENT_ROOT . '/asset/class/assetaccountancycodes.class.php';
  524. $accountancy_codes_model = new AssetAccountancyCodes($this->db);
  525. $result = $accountancy_codes_model->fetchAccountancyCodes(0, $this->fk_asset_model);
  526. if ($result < 0) {
  527. $this->error = $accountancy_codes_model->error;
  528. $this->errors = $accountancy_codes_model->errors;
  529. $error++;
  530. } elseif ($result > 0) {
  531. $accountancy_codes = new AssetAccountancyCodes($this->db);
  532. $result = $accountancy_codes->fetchAccountancyCodes($this->id);
  533. if ($result < 0) {
  534. $this->error = $accountancy_codes->error;
  535. $this->errors = $accountancy_codes->errors;
  536. $error++;
  537. }
  538. if (!$error) {
  539. foreach ($accountancy_codes_model->accountancy_codes as $mode_key => $fields) {
  540. foreach ($fields as $field_key => $value) {
  541. $accountancy_codes->accountancy_codes[$mode_key][$field_key] = $value;
  542. }
  543. }
  544. $result = $accountancy_codes->updateAccountancyCodes($user, $this->id, 0, $notrigger);
  545. if ($result < 0) {
  546. $this->error = $accountancy_codes->error;
  547. $this->errors = $accountancy_codes->errors;
  548. $error++;
  549. }
  550. }
  551. }
  552. }
  553. if ($error) {
  554. $this->db->rollback();
  555. return -1;
  556. } else {
  557. $this->db->commit();
  558. return 1;
  559. }
  560. }
  561. /**
  562. * Fetch depreciation lines for each mode in $this->depreciation_lines (sort by depreciation date)
  563. *
  564. * @return int <0 if KO, Id of created object if OK
  565. */
  566. public function fetchDepreciationLines()
  567. {
  568. global $langs;
  569. $langs->load('assets');
  570. $this->depreciation_lines = array();
  571. // Clean parameters
  572. $this->id = $this->id > 0 ? $this->id : 0;
  573. // Check parameters
  574. $error = 0;
  575. if (empty($this->id)) {
  576. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  577. $error++;
  578. }
  579. if ($error) {
  580. return -1;
  581. }
  582. // Old request with 'WITH'
  583. /*
  584. $sql = "WITH in_accounting_bookkeeping(fk_docdet) AS (";
  585. $sql .= " SELECT DISTINCT fk_docdet";
  586. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping";
  587. $sql .= " WHERE doc_type = 'asset'";
  588. $sql .= ")";
  589. $sql .= "SELECT ad.rowid, ad.depreciation_mode, ad.ref, ad.depreciation_date, ad.depreciation_ht, ad.cumulative_depreciation_ht";
  590. $sql .= ", " . $this->db->ifsql('iab.fk_docdet IS NOT NULL', 1, 0) . " AS bookkeeping";
  591. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
  592. $sql .= " LEFT JOIN in_accounting_bookkeeping as iab ON iab.fk_docdet = ad.rowid";
  593. $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
  594. $sql .= " ORDER BY ad.depreciation_date ASC";
  595. */
  596. $sql = "SELECT ad.rowid, ad.depreciation_mode, ad.ref, ad.depreciation_date, ad.depreciation_ht, ad.cumulative_depreciation_ht";
  597. $sql .= ", " . $this->db->ifsql('iab.fk_docdet IS NOT NULL', 1, 0) . " AS bookkeeping";
  598. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
  599. $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";
  600. $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
  601. $sql .= " ORDER BY ad.depreciation_date ASC";
  602. $resql = $this->db->query($sql);
  603. if (!$resql) {
  604. $this->errors[] = $langs->trans('AssetErrorFetchDepreciationLines') . ': ' . $this->db->lasterror();
  605. return -1;
  606. }
  607. while ($obj = $this->db->fetch_object($resql)) {
  608. if (!isset($this->depreciation_lines[$obj->depreciation_mode])) $this->depreciation_lines[$obj->depreciation_mode] = array();
  609. $this->depreciation_lines[$obj->depreciation_mode][] = array(
  610. 'id' => $obj->rowid,
  611. 'ref' => $obj->ref,
  612. 'depreciation_date' => $this->db->jdate($obj->depreciation_date),
  613. 'depreciation_ht' => $obj->depreciation_ht,
  614. 'cumulative_depreciation_ht' => $obj->cumulative_depreciation_ht,
  615. 'bookkeeping' => $obj->bookkeeping,
  616. );
  617. }
  618. return 1;
  619. }
  620. /**
  621. * If has depreciation lines in bookkeeping
  622. *
  623. * @return int <0 if KO, 0 if NO, 1 if Yes
  624. */
  625. public function hasDepreciationLinesInBookkeeping()
  626. {
  627. global $langs;
  628. $langs->load('assets');
  629. // Clean parameters
  630. $this->id = $this->id > 0 ? $this->id : 0;
  631. // Check parameters
  632. $error = 0;
  633. if (empty($this->id)) {
  634. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  635. $error++;
  636. }
  637. if ($error) {
  638. return -1;
  639. }
  640. // Old request with 'WITH'
  641. /*
  642. $sql = "WITH in_accounting_bookkeeping(fk_docdet) AS (";
  643. $sql .= " SELECT DISTINCT fk_docdet";
  644. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping";
  645. $sql .= " WHERE doc_type = 'asset'";
  646. $sql .= ")";
  647. $sql .= "SELECT COUNT(*) AS has_bookkeeping";
  648. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
  649. $sql .= " LEFT JOIN in_accounting_bookkeeping as iab ON iab.fk_docdet = ad.rowid";
  650. $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
  651. $sql .= " AND iab.fk_docdet IS NOT NULL";
  652. */
  653. $sql = "SELECT COUNT(*) AS has_bookkeeping";
  654. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
  655. $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";
  656. $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
  657. $sql .= " AND iab.fk_docdet IS NOT NULL";
  658. $resql = $this->db->query($sql);
  659. if (!$resql) {
  660. $this->errors[] = $langs->trans('AssetErrorFetchDepreciationLines') . ': ' . $this->db->lasterror();
  661. return -1;
  662. }
  663. if ($obj = $this->db->fetch_object($resql)) {
  664. return $obj->has_bookkeeping > 0 ? 1 : 0;
  665. }
  666. return 0;
  667. }
  668. /**
  669. * Add depreciation line for a mode
  670. *
  671. * @param string $mode Depreciation mode (economic, accelerated_depreciation, ...)
  672. * @param string $ref Ref line
  673. * @param int $depreciation_date Depreciation date
  674. * @param double $depreciation_ht Depreciation amount HT
  675. * @param double $cumulative_depreciation_ht Depreciation cumulative amount HT
  676. * @param string $accountancy_code_debit Accountancy code Debit
  677. * @param string $accountancy_code_credit Accountancy code Credit
  678. * @return int <0 if KO, Id of created line if OK
  679. */
  680. public function addDepreciationLine($mode, $ref, $depreciation_date, $depreciation_ht, $cumulative_depreciation_ht, $accountancy_code_debit, $accountancy_code_credit)
  681. {
  682. global $langs;
  683. $langs->load('assets');
  684. // Clean parameters
  685. $this->id = $this->id > 0 ? $this->id : 0;
  686. $mode = strtolower(trim($mode));
  687. $ref = trim($ref);
  688. $accountancy_code_debit = trim($accountancy_code_debit);
  689. $accountancy_code_credit = trim($accountancy_code_credit);
  690. // Check parameters
  691. $error = 0;
  692. if (empty($this->id)) {
  693. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  694. $error++;
  695. }
  696. if ($error) {
  697. return -1;
  698. }
  699. $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)";
  700. $sql .= " VALUES ( ";
  701. $sql .= " " . (int) $this->id;
  702. $sql .= ", '" . $this->db->escape($mode) . "'";
  703. $sql .= ", '" . $this->db->escape($ref) . "'";
  704. $sql .= ", '" . $this->db->idate($depreciation_date) . "'";
  705. $sql .= ", " . (double) $depreciation_ht;
  706. $sql .= ", " . (double) $cumulative_depreciation_ht;
  707. $sql .= ", '" . $this->db->escape($accountancy_code_debit) . "'";
  708. $sql .= ", '" . $this->db->escape($accountancy_code_credit) . "'";
  709. $sql .= ")";
  710. $resql = $this->db->query($sql);
  711. if (!$resql) {
  712. $this->errors[] = $langs->trans('AssetErrorAddDepreciationLine') . ': ' . $this->db->lasterror();
  713. return -1;
  714. }
  715. return 1;
  716. }
  717. /**
  718. * Calculation depreciation lines (reversal and future) for each mode
  719. *
  720. * @return int <0 if KO, Id of created object if OK
  721. */
  722. public function calculationDepreciation()
  723. {
  724. global $conf, $langs;
  725. $langs->load('assets');
  726. // Clean parameters
  727. $this->id = $this->id > 0 ? $this->id : 0;
  728. // Check parameters
  729. $error = 0;
  730. if (empty($this->id)) {
  731. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Asset") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  732. $error++;
  733. }
  734. if ($error) {
  735. return -1;
  736. }
  737. // Get depreciation options
  738. //---------------------------
  739. require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
  740. $options = new AssetDepreciationOptions($this->db);
  741. $result = $options->fetchDeprecationOptions($this->id);
  742. if ($result < 0) {
  743. $this->error = $options->error;
  744. $this->errors = $options->errors;
  745. return -1;
  746. }
  747. // Get accountancy codes
  748. //---------------------------
  749. require_once DOL_DOCUMENT_ROOT . '/asset/class/assetaccountancycodes.class.php';
  750. $accountancy_codes = new AssetAccountancyCodes($this->db);
  751. $result = $accountancy_codes->fetchAccountancyCodes($this->id);
  752. if ($result < 0) {
  753. $this->error = $accountancy_codes->error;
  754. $this->errors = $accountancy_codes->errors;
  755. return -1;
  756. }
  757. $this->db->begin();
  758. // Delete old lines
  759. $modes = array();
  760. foreach ($options->deprecation_options as $mode_key => $fields) {
  761. $modes[$mode_key] = $this->db->escape($mode_key);
  762. }
  763. $sql = "DELETE FROM " . MAIN_DB_PREFIX . "asset_depreciation";
  764. $sql .= " WHERE fk_asset = " . (int) $this->id;
  765. $sql .= " AND depreciation_mode NOT IN ('" . $this->db->sanitize(implode("', '", $modes)) . "')";
  766. $resql = $this->db->query($sql);
  767. if (!$resql) {
  768. $this->errors[] = $langs->trans('AssetErrorClearDepreciationLines') . ': ' . $this->db->lasterror();
  769. $error++;
  770. }
  771. if (!$error) {
  772. // Get fiscal period
  773. require_once DOL_DOCUMENT_ROOT . '/core/lib/date.lib.php';
  774. require_once DOL_DOCUMENT_ROOT . '/core/lib/accounting.lib.php';
  775. $dates = getDefaultDatesForTransfer();
  776. $init_fiscal_period_start = $dates['date_start'];
  777. $init_fiscal_period_end = $dates['date_end'];
  778. if (empty($init_fiscal_period_start) || empty($init_fiscal_period_end)) {
  779. $pastmonthyear = $dates['pastmonthyear'];
  780. $pastmonth = $dates['pastmonth'];
  781. $init_fiscal_period_start = dol_get_first_day($pastmonthyear, $pastmonth, false);
  782. $init_fiscal_period_end = dol_get_last_day($pastmonthyear, $pastmonth, false);
  783. }
  784. foreach ($options->deprecation_options as $mode_key => $fields) {
  785. // Get last depreciation lines save in bookkeeping
  786. //-----------------------------------------------------
  787. // Old request with 'WITH'
  788. /*
  789. $sql = "WITH in_accounting_bookkeeping(fk_docdet) AS (";
  790. $sql .= " SELECT fk_docdet";
  791. $sql .= " FROM " . MAIN_DB_PREFIX . "accounting_bookkeeping";
  792. $sql .= " WHERE doc_type = 'asset'";
  793. $sql .= ")";
  794. $sql .= "SELECT ad.depreciation_date, ad.cumulative_depreciation_ht";
  795. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
  796. $sql .= " LEFT JOIN in_accounting_bookkeeping as iab ON iab.fk_docdet = ad.rowid";
  797. $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
  798. $sql .= " AND ad.depreciation_mode = '" . $this->db->escape($mode_key) . "'";
  799. $sql .= " AND iab.fk_docdet IS NOT NULL";
  800. $sql .= " ORDER BY ad.depreciation_date DESC";
  801. $sql .= " LIMIT 1";
  802. */
  803. $sql = "SELECT ad.depreciation_date, ad.cumulative_depreciation_ht";
  804. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation AS ad";
  805. $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";
  806. $sql .= " WHERE ad.fk_asset = " . (int) $this->id;
  807. $sql .= " AND ad.depreciation_mode = '" . $this->db->escape($mode_key) . "'";
  808. $sql .= " AND iab.fk_docdet IS NOT NULL";
  809. $sql .= " ORDER BY ad.depreciation_date DESC";
  810. $sql .= " LIMIT 1";
  811. $resql = $this->db->query($sql);
  812. if (!$resql) {
  813. $this->errors[] = $langs->trans('AssetErrorFetchMaxDepreciationDateForMode', $mode_key) . ': ' . $this->db->lasterror();
  814. $error++;
  815. break;
  816. }
  817. $last_depreciation_date = '';
  818. $last_cumulative_depreciation_ht = $this->reversal_amount_ht;
  819. if ($obj = $this->db->fetch_object($resql)) {
  820. $last_depreciation_date = $this->db->jdate($obj->depreciation_date);
  821. $last_cumulative_depreciation_ht = $obj->cumulative_depreciation_ht;
  822. }
  823. // Set last cumulative depreciation
  824. $sql = "UPDATE " . MAIN_DB_PREFIX . $options->deprecation_options_fields[$mode_key]['table'];
  825. $sql .= " SET total_amount_last_depreciation_ht = " . (empty($last_cumulative_depreciation_ht) ? 0 : $last_cumulative_depreciation_ht);
  826. $sql .= " WHERE fk_asset = " . (int) $this->id;
  827. $resql = $this->db->query($sql);
  828. if (!$resql) {
  829. $this->errors[] = $langs->trans('AssetErrorSetLastCumulativeDepreciation') . ': ' . $this->db->lasterror();
  830. $error++;
  831. break;
  832. }
  833. // Delete old lines
  834. $sql = "DELETE " . MAIN_DB_PREFIX . "asset_depreciation FROM " . MAIN_DB_PREFIX . "asset_depreciation";
  835. $sql .= " LEFT JOIN " . MAIN_DB_PREFIX . "accounting_bookkeeping as ab ON ab.doc_type = 'asset' AND ab.fk_docdet = " . MAIN_DB_PREFIX . "asset_depreciation.rowid";
  836. $sql .= " WHERE " . MAIN_DB_PREFIX . "asset_depreciation.fk_asset = " . (int) $this->id;
  837. $sql .= " AND " . MAIN_DB_PREFIX . "asset_depreciation.depreciation_mode = '" . $this->db->escape($mode_key) . "'";
  838. $sql .= " AND ab.fk_docdet IS NULL";
  839. if ($last_depreciation_date !== "") $sql .= " AND " . MAIN_DB_PREFIX . "asset_depreciation.ref != ''";
  840. $resql = $this->db->query($sql);
  841. if (!$resql) {
  842. $this->errors[] = $langs->trans('AssetErrorClearDepreciationLines') . ': ' . $this->db->lasterror();
  843. $error++;
  844. break;
  845. }
  846. // Get depreciation period
  847. $depreciation_date_start = $this->date_start > $this->date_acquisition ? $this->date_start : $this->date_acquisition;
  848. $depreciation_date_end = dol_time_plus_duree($depreciation_date_start, $fields['duration'], $fields['duration_type'] == 1 ? 'm' : ($fields['duration_type'] == 2 ? 'd' : 'y'));
  849. $depreciation_amount = $fields['amount_base_depreciation_ht'];
  850. if ($fields['duration_type'] == 2) { // Daily
  851. $fiscal_period_start = $depreciation_date_start;
  852. $fiscal_period_end = $depreciation_date_start;
  853. } elseif ($fields['duration_type'] == 1) { // Monthly
  854. $date_temp = dol_getdate($depreciation_date_start);
  855. $fiscal_period_start = dol_get_first_day($date_temp['year'], $date_temp['mon'], false);
  856. $fiscal_period_end = dol_get_last_day($date_temp['year'], $date_temp['mon'], false);
  857. } else { // Annually
  858. $fiscal_period_start = $init_fiscal_period_start;
  859. $fiscal_period_end = $init_fiscal_period_end;
  860. }
  861. $cumulative_depreciation_ht = $last_cumulative_depreciation_ht;
  862. $depreciation_period_amount = $depreciation_amount - $this->reversal_amount_ht;
  863. $start_date = $depreciation_date_start;
  864. $disposal_date = isset($this->disposal_date) && $this->disposal_date !== "" ? $this->disposal_date : "";
  865. $finish_date = $disposal_date !== "" ? $disposal_date : $depreciation_date_end;
  866. $accountancy_code_depreciation_debit_key = $accountancy_codes->accountancy_codes_fields[$mode_key]['depreciation_debit'];
  867. $accountancy_code_depreciation_debit = $accountancy_codes->accountancy_codes[$mode_key][$accountancy_code_depreciation_debit_key];
  868. $accountancy_code_depreciation_credit_key = $accountancy_codes->accountancy_codes_fields[$mode_key]['depreciation_credit'];
  869. $accountancy_code_credit = $accountancy_codes->accountancy_codes[$mode_key][$accountancy_code_depreciation_credit_key];
  870. // Reversal depreciation line
  871. //-----------------------------------------------------
  872. if ($last_depreciation_date === "" && ($depreciation_date_start < $fiscal_period_start || is_numeric($this->reversal_date))) {
  873. if (is_numeric($this->reversal_date)) {
  874. if ($this->reversal_date < $fiscal_period_start) {
  875. $this->errors[] = $langs->trans('AssetErrorReversalDateNotGreaterThanCurrentBeginFiscalDateForMode', $mode_key);
  876. $error++;
  877. break;
  878. }
  879. if (empty($this->reversal_amount_ht)) {
  880. $this->errors[] = $langs->trans('AssetErrorReversalAmountNotProvidedForMode', $mode_key);
  881. $error++;
  882. break;
  883. }
  884. $start_date = $this->reversal_date;
  885. $result = $this->addDepreciationLine($mode_key, '', $start_date, $this->reversal_amount_ht, $this->reversal_amount_ht, $accountancy_code_depreciation_debit, $accountancy_code_credit);
  886. if ($result < 0) {
  887. $error++;
  888. break;
  889. }
  890. } else {
  891. $this->errors[] = $langs->trans('AssetErrorReversalDateNotProvidedForMode', $mode_key);
  892. $error++;
  893. break;
  894. }
  895. }
  896. // futures depreciation lines
  897. //-----------------------------------------------------
  898. $nb_days_in_year = !empty($conf->global->ASSET_DEPRECIATION_DURATION_PER_YEAR) ? $conf->global->ASSET_DEPRECIATION_DURATION_PER_YEAR : 365;
  899. $nb_days_in_month = !empty($conf->global->ASSET_DEPRECIATION_DURATION_PER_MONTH) ? $conf->global->ASSET_DEPRECIATION_DURATION_PER_MONTH : 30;
  900. $period_amount = (double) price2num($depreciation_period_amount / $fields['duration'], 'MT');
  901. $first_period_found = false;
  902. $first_period_date = isset($begin_period) && $begin_period > $fiscal_period_start ? $begin_period : $fiscal_period_start;
  903. $ref_date_format = "%Y" . ($fields['duration_type'] == 1 || $fields['duration_type'] == 2 ? '-%m' : '') . ($fields['duration_type'] == 2 ? '-%d' : '');
  904. // Loop security
  905. $idx_loop = 0;
  906. $max_loop = $fields['duration'] + 2;
  907. do {
  908. // Loop security
  909. $idx_loop++;
  910. if ($idx_loop > $max_loop) break;
  911. if ($last_depreciation_date < $fiscal_period_end && ($first_period_date <= $start_date || $first_period_found)) {
  912. // Disposal not depreciated
  913. if ($fiscal_period_start <= $disposal_date && $disposal_date <= $fiscal_period_end && empty($this->disposal_depreciated)) {
  914. break;
  915. }
  916. $first_period_found = true;
  917. $period_begin = dol_print_date($fiscal_period_start, $ref_date_format);
  918. $period_end = dol_print_date($fiscal_period_end, $ref_date_format);
  919. $ref = $period_begin . ($period_begin != $period_end ? ' - ' . $period_end : '');
  920. if ($fiscal_period_start <= $disposal_date && $disposal_date <= $fiscal_period_end) {
  921. $ref .= ' - ' . $langs->transnoentitiesnoconv('AssetDisposal');
  922. }
  923. $begin_date = $fiscal_period_start < $start_date && $start_date <= $fiscal_period_end ? $start_date : $fiscal_period_start;
  924. $end_date = $fiscal_period_start < $finish_date && $finish_date <= $fiscal_period_end ? $finish_date : $fiscal_period_end;
  925. if ($fields['duration_type'] == 2) { // Daily
  926. $depreciation_ht = $period_amount;
  927. } elseif ($fields['duration_type'] == 1) { // Monthly
  928. $nb_days = min($nb_days_in_month, num_between_day($begin_date, $end_date, 1));
  929. if ($nb_days >= 28) {
  930. $date_temp = dol_getdate($begin_date);
  931. if ($date_temp['mon'] == 2) {
  932. $nb_days = 30;
  933. }
  934. }
  935. $depreciation_ht = (double) price2num($period_amount * $nb_days / $nb_days_in_month, 'MT');
  936. } else { // Annually
  937. $nb_days = min($nb_days_in_year, num_between_day($begin_date, $end_date, 1));
  938. $depreciation_ht = (double) price2num($period_amount * $nb_days / $nb_days_in_year, 'MT');
  939. }
  940. if ($fiscal_period_start <= $depreciation_date_end && $depreciation_date_end <= $fiscal_period_end) { // last period
  941. $depreciation_ht = (double) price2num($depreciation_amount - $cumulative_depreciation_ht, 'MT');
  942. $cumulative_depreciation_ht = $depreciation_amount;
  943. } else {
  944. $cumulative_depreciation_ht += $depreciation_ht;
  945. }
  946. $result = $this->addDepreciationLine($mode_key, $ref, $fiscal_period_end, $depreciation_ht, $cumulative_depreciation_ht, $accountancy_code_depreciation_debit, $accountancy_code_credit);
  947. if ($result < 0) {
  948. $error++;
  949. break;
  950. }
  951. }
  952. // Next fiscal period (+1 day/month/year)
  953. $fiscal_period_start = dol_time_plus_duree($fiscal_period_end, 1, 'd');
  954. if ($fields['duration_type'] == 2) { // Daily
  955. $fiscal_period_end = $fiscal_period_start;
  956. } elseif ($fields['duration_type'] == 1) { // Monthly
  957. $fiscal_period_end = dol_time_plus_duree(dol_time_plus_duree($fiscal_period_start, 1, 'm'), -1, 'd');
  958. } else { // Annually
  959. $fiscal_period_end = dol_time_plus_duree(dol_time_plus_duree($fiscal_period_start, 1, 'y'), -1, 'd');
  960. }
  961. $last_period_date = $disposal_date !== "" && $disposal_date < $depreciation_date_end ? $disposal_date : $depreciation_date_end;
  962. } while ($fiscal_period_start < $last_period_date);
  963. if ($error) {
  964. break;
  965. }
  966. }
  967. }
  968. if ($error) {
  969. $this->db->rollback();
  970. return -1;
  971. } else {
  972. $this->db->commit();
  973. return 1;
  974. }
  975. }
  976. /**
  977. * Set last cumulative depreciation for each mode
  978. *
  979. * @param int $asset_depreciation_id Asset depreciation line ID
  980. * @return int <0 if KO, >0 if OK
  981. */
  982. public function setLastCumulativeDepreciation($asset_depreciation_id)
  983. {
  984. global $langs;
  985. $langs->load('assets');
  986. // Clean parameters
  987. $asset_depreciation_id = $asset_depreciation_id > 0 ? $asset_depreciation_id : 0;
  988. // Check parameters
  989. $error = 0;
  990. if (empty($asset_depreciation_id)) {
  991. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("AssetDepreciation") . ' (' . $langs->transnoentitiesnoconv("TechnicalID") . ')');
  992. $error++;
  993. }
  994. if ($error) {
  995. return -1;
  996. }
  997. $this->db->begin();
  998. require_once DOL_DOCUMENT_ROOT . '/asset/class/assetdepreciationoptions.class.php';
  999. $options = new AssetDepreciationOptions($this->db);
  1000. // Get last depreciation lines save in bookkeeping
  1001. //-----------------------------------------------------
  1002. $sql = "SELECT fk_asset, depreciation_mode, cumulative_depreciation_ht";
  1003. $sql .= " FROM " . MAIN_DB_PREFIX . "asset_depreciation";
  1004. $sql .= " WHERE rowid = " . (int) $asset_depreciation_id;
  1005. $resql = $this->db->query($sql);
  1006. if (!$resql) {
  1007. $this->errors[] = $langs->trans('AssetErrorFetchCumulativeDepreciation') . ': ' . $this->db->lasterror();
  1008. $error++;
  1009. } else {
  1010. if ($obj = $this->db->fetch_object($resql)) {
  1011. $mode_key = $obj->depreciation_mode;
  1012. if (!empty($options->deprecation_options_fields[$mode_key])) {
  1013. $sql = "UPDATE " . MAIN_DB_PREFIX . $options->deprecation_options_fields[$mode_key]['table'];
  1014. $sql .= " SET total_amount_last_depreciation_ht = " . $obj->cumulative_depreciation_ht;
  1015. $sql .= " WHERE fk_asset = " . (int) $obj->fk_asset;
  1016. $resql = $this->db->query($sql);
  1017. if (!$resql) {
  1018. $this->errors[] = $langs->trans('AssetErrorSetLastCumulativeDepreciation') . ': ' . $this->db->lasterror();
  1019. $error++;
  1020. }
  1021. }
  1022. }
  1023. }
  1024. if ($error) {
  1025. $this->db->rollback();
  1026. return -1;
  1027. } else {
  1028. $this->db->commit();
  1029. return 1;
  1030. }
  1031. }
  1032. /**
  1033. * Set dispose status
  1034. *
  1035. * @param User $user Object user that dispose
  1036. * @param int $disposal_invoice_id Disposal invoice ID
  1037. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  1038. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1039. */
  1040. public function dispose($user, $disposal_invoice_id, $notrigger = 0)
  1041. {
  1042. global $conf, $langs;
  1043. // Protection
  1044. if ($this->status != self::STATUS_DRAFT || $this->status == self::STATUS_DISPOSED) {
  1045. return 0;
  1046. }
  1047. $this->db->begin();
  1048. $required_fields = array('disposal_date', 'disposal_date', 'fk_disposal_type');
  1049. foreach ($required_fields as $field) {
  1050. $this->fields[$field]['notnull'] = 1;
  1051. }
  1052. $result = $this->update($user, 1);
  1053. foreach ($required_fields as $field) {
  1054. $this->fields[$field]['notnull'] = 0;
  1055. }
  1056. if ($result > 0) {
  1057. if ($disposal_invoice_id > 0) $this->add_object_linked('facture', $disposal_invoice_id);
  1058. $result = $this->setStatusCommon($user, self::STATUS_DISPOSED, $notrigger, 'ASSET_DISPOSED');
  1059. }
  1060. if ($result > 0) $result = $this->calculationDepreciation();
  1061. if ($result < 0) {
  1062. $this->db->rollback();
  1063. } else {
  1064. $this->db->commit();
  1065. }
  1066. // Define output language
  1067. if ($result > 0 && empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1068. if (method_exists($this, 'generateDocument')) {
  1069. global $hidedetails, $hidedesc, $hideref;
  1070. $outputlangs = $langs;
  1071. $newlang = '';
  1072. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1073. $newlang = GETPOST('lang_id', 'aZ09');
  1074. }
  1075. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  1076. $newlang = $this->thirdparty->default_lang;
  1077. }
  1078. if (!empty($newlang)) {
  1079. $outputlangs = new Translate("", $conf);
  1080. $outputlangs->setDefaultLang($newlang);
  1081. }
  1082. $model = $this->model_pdf;
  1083. $ret = $this->fetch($this->id); // Reload to get new records
  1084. $this->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1085. }
  1086. }
  1087. return $result;
  1088. }
  1089. /**
  1090. * Set back to validated status
  1091. *
  1092. * @param User $user Object user that modify
  1093. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  1094. * @return int <0 if KO, 0=Nothing done, >0 if OK
  1095. */
  1096. public function reopen($user, $notrigger = 0)
  1097. {
  1098. global $conf, $langs;
  1099. // Protection
  1100. if ($this->status != self::STATUS_DISPOSED || $this->status == self::STATUS_DRAFT) {
  1101. return 0;
  1102. }
  1103. $this->db->begin();
  1104. $this->disposal_date = null;
  1105. $this->disposal_amount_ht = null;
  1106. $this->fk_disposal_type = null;
  1107. $this->disposal_depreciated = null;
  1108. $this->disposal_subject_to_vat = null;
  1109. $result = $this->update($user, 1);
  1110. if ($result > 0) {
  1111. $this->deleteObjectLinked(null, 'facture');
  1112. $result = $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'ASSET_REOPEN');
  1113. }
  1114. if ($result > 0) $result = $this->calculationDepreciation();
  1115. if ($result < 0) {
  1116. $this->db->rollback();
  1117. } else {
  1118. $this->db->commit();
  1119. }
  1120. // Define output language
  1121. if ($result > 0 && empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) {
  1122. if (method_exists($this, 'generateDocument')) {
  1123. global $hidedetails, $hidedesc, $hideref;
  1124. $outputlangs = $langs;
  1125. $newlang = '';
  1126. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang) && GETPOST('lang_id', 'aZ09')) {
  1127. $newlang = GETPOST('lang_id', 'aZ09');
  1128. }
  1129. if (getDolGlobalInt('MAIN_MULTILANGS') && empty($newlang)) {
  1130. $newlang = $this->thirdparty->default_lang;
  1131. }
  1132. if (!empty($newlang)) {
  1133. $outputlangs = new Translate("", $conf);
  1134. $outputlangs->setDefaultLang($newlang);
  1135. }
  1136. $model = $this->model_pdf;
  1137. $ret = $this->fetch($this->id); // Reload to get new records
  1138. $this->generateDocument($model, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1139. }
  1140. }
  1141. return $result;
  1142. }
  1143. /**
  1144. * Return a link to the object card (with optionaly the picto)
  1145. *
  1146. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1147. * @param string $option On what the link point to ('nolink', ...)
  1148. * @param int $maxlen Max length of name
  1149. * @param int $notooltip 1=Disable tooltip
  1150. * @param string $morecss Add more css on link
  1151. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1152. * @return string String with URL
  1153. */
  1154. public function getNomUrl($withpicto = 0, $option = '', $maxlen = 0, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1155. {
  1156. global $db, $conf, $langs, $hookmanager;
  1157. global $dolibarr_main_authentication, $dolibarr_main_demo;
  1158. global $menumanager;
  1159. if (!empty($conf->dol_no_mouse_hover)) {
  1160. $notooltip = 1; // Force disable tooltips
  1161. }
  1162. $result = '';
  1163. $label = img_picto('', $this->picto).' <u>'.$langs->trans("Asset").'</u>';
  1164. if (isset($this->status)) {
  1165. $label .= ' '.$this->getLibStatut(5);
  1166. }
  1167. $label .= '<br>';
  1168. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1169. $url = dol_buildpath('/asset/card.php', 1).'?id='.$this->id;
  1170. if ($option != 'nolink') {
  1171. // Add param to save lastsearch_values or not
  1172. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1173. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1174. $add_save_lastsearch_values = 1;
  1175. }
  1176. if ($add_save_lastsearch_values) {
  1177. $url .= '&save_lastsearch_values=1';
  1178. }
  1179. }
  1180. $linkclose = '';
  1181. if (empty($notooltip)) {
  1182. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1183. $label = $langs->trans("ShowAsset");
  1184. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1185. }
  1186. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1187. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1188. } else {
  1189. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1190. }
  1191. if ($option == 'nolink') {
  1192. $linkstart = '<span';
  1193. } else {
  1194. $linkstart = '<a href="'.$url.'"';
  1195. }
  1196. $linkstart .= $linkclose.'>';
  1197. if ($option == 'nolink') {
  1198. $linkend = '</span>';
  1199. } else {
  1200. $linkend = '</a>';
  1201. }
  1202. $result .= $linkstart;
  1203. if (empty($this->showphoto_on_popup)) {
  1204. if ($withpicto) {
  1205. $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);
  1206. }
  1207. } else {
  1208. if ($withpicto) {
  1209. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1210. list($class, $module) = explode('@', $this->picto);
  1211. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  1212. $filearray = dol_dir_list($upload_dir, "files");
  1213. $filename = $filearray[0]['name'];
  1214. if (!empty($filename)) {
  1215. $pospoint = strpos($filearray[0]['name'], '.');
  1216. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  1217. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  1218. $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>';
  1219. } else {
  1220. $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>';
  1221. }
  1222. $result .= '</div>';
  1223. } else {
  1224. $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);
  1225. }
  1226. }
  1227. }
  1228. if ($withpicto != 2) {
  1229. $name = $this->ref;
  1230. if ($option == 'label') $name = $this->label;
  1231. elseif ($option == 'with_label') $name .= ' - ' . $this->label;
  1232. $result .= dol_escape_htmltag($maxlen ? dol_trunc($name, $maxlen) : $name);
  1233. }
  1234. $result .= $linkend;
  1235. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1236. global $action;
  1237. $hookmanager->initHooks(array($this->element . 'dao'));
  1238. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1239. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1240. if ($reshook > 0) {
  1241. $result = $hookmanager->resPrint;
  1242. } else {
  1243. $result .= $hookmanager->resPrint;
  1244. }
  1245. return $result;
  1246. }
  1247. /**
  1248. * Return the label of the status
  1249. *
  1250. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1251. * @return string Label of status
  1252. */
  1253. public function getLabelStatus($mode = 0)
  1254. {
  1255. return $this->LibStatut($this->status, $mode);
  1256. }
  1257. /**
  1258. * Return the label of the status
  1259. *
  1260. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1261. * @return string Label of status
  1262. */
  1263. public function getLibStatut($mode = 0)
  1264. {
  1265. return $this->LibStatut($this->status, $mode);
  1266. }
  1267. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1268. /**
  1269. * Return the status
  1270. *
  1271. * @param int $status Id status
  1272. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
  1273. * @return string Label of status
  1274. */
  1275. public function LibStatut($status, $mode = 0)
  1276. {
  1277. // phpcs:enable
  1278. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  1279. global $langs;
  1280. //$langs->load("asset@asset");
  1281. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('AssetInProgress');
  1282. $this->labelStatus[self::STATUS_DISPOSED] = $langs->transnoentitiesnoconv('AssetDisposed');
  1283. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('AssetInProgress');
  1284. $this->labelStatusShort[self::STATUS_DISPOSED] = $langs->transnoentitiesnoconv('AssetDisposed');
  1285. }
  1286. $statusType = 'status4';
  1287. if ($status == self::STATUS_DISPOSED) {
  1288. $statusType = 'status6';
  1289. }
  1290. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  1291. }
  1292. /**
  1293. * Load the info information in the object
  1294. *
  1295. * @param int $id Id of object
  1296. * @return void
  1297. */
  1298. public function info($id)
  1299. {
  1300. $sql = "SELECT rowid, date_creation as datec, tms as datem,";
  1301. $sql .= " fk_user_creat, fk_user_modif";
  1302. $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." as t";
  1303. $sql .= " WHERE t.rowid = ".((int) $id);
  1304. $result = $this->db->query($sql);
  1305. if ($result) {
  1306. if ($this->db->num_rows($result)) {
  1307. $obj = $this->db->fetch_object($result);
  1308. $this->id = $obj->rowid;
  1309. $this->user_creation_id = $obj->fk_user_author;
  1310. $this->user_validation_id = $obj->fk_user_valid;
  1311. $this->user_cloture_id = $obj->fk_user_cloture;
  1312. $this->date_creation = $this->db->jdate($obj->datec);
  1313. $this->date_modification = $this->db->jdate($obj->datem);
  1314. $this->date_validation = $this->db->jdate($obj->datev);
  1315. }
  1316. $this->db->free($result);
  1317. } else {
  1318. dol_print_error($this->db);
  1319. }
  1320. }
  1321. /**
  1322. * Initialise object with example values
  1323. * Id must be 0 if object instance is a specimen
  1324. *
  1325. * @return void
  1326. */
  1327. public function initAsSpecimen()
  1328. {
  1329. // Set here init that are not commonf fields
  1330. // $this->property1 = ...
  1331. // $this->property2 = ...
  1332. $this->initAsSpecimenCommon();
  1333. }
  1334. /**
  1335. * Create an array of lines
  1336. *
  1337. * @return array|int array of lines if OK, <0 if KO
  1338. */
  1339. public function getLinesArray()
  1340. {
  1341. $this->lines = array();
  1342. return $this->lines;
  1343. }
  1344. /**
  1345. * Returns the reference to the following non used object depending on the active numbering module.
  1346. *
  1347. * @return string Object free reference
  1348. */
  1349. public function getNextNumRef()
  1350. {
  1351. global $langs, $conf;
  1352. $langs->load("asset@asset");
  1353. if (empty($conf->global->ASSET_ASSET_ADDON)) {
  1354. $conf->global->ASSET_ASSET_ADDON = 'mod_asset_standard';
  1355. }
  1356. if (!empty($conf->global->ASSET_ASSET_ADDON)) {
  1357. $mybool = false;
  1358. $file = $conf->global->ASSET_ASSET_ADDON.".php";
  1359. $classname = $conf->global->ASSET_ASSET_ADDON;
  1360. // Include file with class
  1361. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  1362. foreach ($dirmodels as $reldir) {
  1363. $dir = dol_buildpath($reldir."core/modules/asset/");
  1364. // Load file with numbering class (if found)
  1365. $mybool |= @include_once $dir.$file;
  1366. }
  1367. if ($mybool === false) {
  1368. dol_print_error('', "Failed to include file ".$file);
  1369. return '';
  1370. }
  1371. if (class_exists($classname)) {
  1372. $obj = new $classname();
  1373. $numref = $obj->getNextValue($this);
  1374. if ($numref != '' && $numref != '-1') {
  1375. return $numref;
  1376. } else {
  1377. $this->error = $obj->error;
  1378. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  1379. return "";
  1380. }
  1381. } else {
  1382. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  1383. return "";
  1384. }
  1385. } else {
  1386. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  1387. return "";
  1388. }
  1389. }
  1390. /**
  1391. * Create a document onto disk according to template module.
  1392. *
  1393. * @param string $modele Force template to use ('' to not force)
  1394. * @param Translate $outputlangs objet lang a utiliser pour traduction
  1395. * @param int $hidedetails Hide details of lines
  1396. * @param int $hidedesc Hide description
  1397. * @param int $hideref Hide ref
  1398. * @param null|array $moreparams Array to provide more information
  1399. * @return int 0 if KO, 1 if OK
  1400. */
  1401. // public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  1402. // {
  1403. // global $conf, $langs;
  1404. //
  1405. // $result = 0;
  1406. // $includedocgeneration = 1;
  1407. //
  1408. // $langs->load("asset@asset");
  1409. //
  1410. // if (!dol_strlen($modele)) {
  1411. // $modele = 'standard_asset';
  1412. //
  1413. // if (!empty($this->model_pdf)) {
  1414. // $modele = $this->model_pdf;
  1415. // } elseif (!empty($conf->global->ASSET_ADDON_PDF)) {
  1416. // $modele = $conf->global->ASSET_ADDON_PDF;
  1417. // }
  1418. // }
  1419. //
  1420. // $modelpath = "core/modules/asset/doc/";
  1421. //
  1422. // if ($includedocgeneration && !empty($modele)) {
  1423. // $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1424. // }
  1425. //
  1426. // return $result;
  1427. // }
  1428. }