asset.class.php 62 KB

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