bom.class.php 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824
  1. <?php
  2. /* Copyright (C) 2019 Laurent Destailleur <eldy@users.sourceforge.net>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file bom/class/bom.class.php
  19. * \ingroup bom
  20. * \brief This file is a CRUD class file for BOM (Create/Read/Update/Delete)
  21. */
  22. // Put here all includes required by your class file
  23. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  24. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  25. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  26. /**
  27. * Class for BOM
  28. */
  29. class BOM extends CommonObject
  30. {
  31. /**
  32. * @var string ID to identify managed object
  33. */
  34. public $element = 'bom';
  35. /**
  36. * @var string Name of table without prefix where object is stored
  37. */
  38. public $table_element = 'bom_bom';
  39. /**
  40. * @var int Does bom support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  41. */
  42. public $ismultientitymanaged = 1;
  43. /**
  44. * @var int Does object support extrafields ? 0=No, 1=Yes
  45. */
  46. public $isextrafieldmanaged = 1;
  47. /**
  48. * @var string String with name of icon for bom. Must be the part after the 'object_' into object_bom.png
  49. */
  50. public $picto = 'bom';
  51. const STATUS_DRAFT = 0;
  52. const STATUS_VALIDATED = 1;
  53. const STATUS_CANCELED = 9;
  54. /**
  55. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  56. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  57. * 'label' the translation key.
  58. * 'picto' is code of a picto to show before value in forms
  59. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  60. * 'position' is the sort order of field.
  61. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  62. * '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)
  63. * 'noteditable' says if field is not editable (1 or 0)
  64. * '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.
  65. * 'index' if we want an index in database.
  66. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  67. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  68. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  69. * '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'
  70. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  71. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  72. * '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.
  73. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  74. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  75. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  76. *
  77. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  78. */
  79. // BEGIN MODULEBUILDER PROPERTIES
  80. /**
  81. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  82. */
  83. public $fields = array(
  84. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
  85. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'notnull'=> 1, 'default'=>1, 'index'=>1, 'position'=>5),
  86. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'noteditable'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of BOM", 'showoncombobox'=>'1', 'csslist'=>'nowraponall'),
  87. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>30, 'notnull'=>1, 'searchall'=>1, 'showoncombobox'=>'2', 'autofocusoncreate'=>1, 'css'=>'minwidth300 maxwidth400', 'csslist'=>'tdoverflowmax200'),
  88. 'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing', 1=>'Disassemble'), 'css'=>'minwidth175', 'csslist'=>'minwidth175 center'),
  89. //'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'position'=>32, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing')),
  90. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1:(finished IS NULL or finished <> 0)', 'label'=>'Product', 'picto'=>'product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'help'=>'ProductBOMHelp', 'css'=>'maxwidth500', 'csslist'=>'tdoverflowmax100'),
  91. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,),
  92. 'qty' => array('type'=>'real', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'default'=>1, 'position'=>55, 'notnull'=>1, 'isameasure'=>'1', 'css'=>'maxwidth75imp'),
  93. //'efficiency' => array('type'=>'real', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>-1, 'default'=>1, 'position'=>100, 'notnull'=>0, 'css'=>'maxwidth50imp', 'help'=>'ValueOfMeansLossForProductProduced'),
  94. 'duration' => array('type'=>'duration', 'label'=>'EstimatedDuration', 'enabled'=>1, 'visible'=>-1, 'position'=>101, 'notnull'=>-1, 'css'=>'maxwidth50imp', 'help'=>'EstimatedDurationDesc'),
  95. 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'picto'=>'stock', 'enabled'=>1, 'visible'=>-1, 'position'=>102, 'css'=>'maxwidth500', 'csslist'=>'tdoverflowmax100'),
  96. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>-2, 'position'=>161, 'notnull'=>-1,),
  97. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>-2, 'position'=>162, 'notnull'=>-1,),
  98. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>300, 'notnull'=>1,),
  99. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>1,),
  100. 'date_valid' => array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-2, 'position'=>502, 'notnull'=>0,),
  101. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserCreation', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'position'=>510, 'notnull'=>1, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax100'),
  102. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1, 'csslist'=>'tdoverflowmax100'),
  103. 'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'picto'=>'user', 'enabled'=>1, 'visible'=>-2, 'position'=>512, 'notnull'=>0, 'csslist'=>'tdoverflowmax100'),
  104. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
  105. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
  106. 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>2, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Enabled', 9=>'Disabled')),
  107. );
  108. /**
  109. * @var int rowid
  110. */
  111. public $rowid;
  112. /**
  113. * @var string ref
  114. */
  115. public $ref;
  116. /**
  117. * @var string label
  118. */
  119. public $label;
  120. /**
  121. * @var int bomtype
  122. */
  123. public $bomtype;
  124. /**
  125. * @var string description
  126. */
  127. public $description;
  128. /**
  129. * @var integer|string date_creation
  130. */
  131. public $date_creation;
  132. public $tms;
  133. /**
  134. * @var int Id User creator
  135. */
  136. public $fk_user_creat;
  137. /**
  138. * @var int Id User modifying
  139. */
  140. public $fk_user_modif;
  141. /**
  142. * @var string import key
  143. */
  144. public $import_key;
  145. /**
  146. * @var int status
  147. */
  148. public $status;
  149. /**
  150. * @var int product Id
  151. */
  152. public $fk_product;
  153. public $qty;
  154. public $efficiency;
  155. // END MODULEBUILDER PROPERTIES
  156. // If this object has a subtable with lines
  157. /**
  158. * @var int Name of subtable line
  159. */
  160. public $table_element_line = 'bom_bomline';
  161. /**
  162. * @var string Fieldname with ID of parent key if this field has a parent
  163. */
  164. public $fk_element = 'fk_bom';
  165. /**
  166. * @var string Name of subtable class that manage subtable lines
  167. */
  168. public $class_element_line = 'BOMLine';
  169. // /**
  170. // * @var array List of child tables. To test if we can delete object.
  171. // */
  172. // protected $childtables=array();
  173. /**
  174. * @var array List of child tables. To know object to delete on cascade.
  175. */
  176. protected $childtablesoncascade = array('bom_bomline');
  177. /**
  178. * @var BOMLine[] Array of subtable lines
  179. */
  180. public $lines = array();
  181. /**
  182. * @var int Calculated cost for the BOM
  183. */
  184. public $total_cost = 0;
  185. /**
  186. * @var int Calculated cost for 1 unit of the product in BOM
  187. */
  188. public $unit_cost = 0;
  189. /**
  190. * Constructor
  191. *
  192. * @param DoliDb $db Database handler
  193. */
  194. public function __construct(DoliDB $db)
  195. {
  196. global $conf, $langs;
  197. $this->db = $db;
  198. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  199. $this->fields['rowid']['visible'] = 0;
  200. }
  201. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  202. $this->fields['entity']['enabled'] = 0;
  203. }
  204. // Unset fields that are disabled
  205. foreach ($this->fields as $key => $val) {
  206. if (isset($val['enabled']) && empty($val['enabled'])) {
  207. unset($this->fields[$key]);
  208. }
  209. }
  210. // Translate some data of arrayofkeyval
  211. foreach ($this->fields as $key => $val) {
  212. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  213. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  214. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  215. }
  216. }
  217. }
  218. }
  219. /**
  220. * Create object into database
  221. *
  222. * @param User $user User that creates
  223. * @param bool $notrigger false=launch triggers after, true=disable triggers
  224. * @return int <0 if KO, Id of created object if OK
  225. */
  226. public function create(User $user, $notrigger = false)
  227. {
  228. if ($this->efficiency <= 0 || $this->efficiency > 1) {
  229. $this->efficiency = 1;
  230. }
  231. return $this->createCommon($user, $notrigger);
  232. }
  233. /**
  234. * Clone an object into another one
  235. *
  236. * @param User $user User that creates
  237. * @param int $fromid Id of object to clone
  238. * @return mixed New object created, <0 if KO
  239. */
  240. public function createFromClone(User $user, $fromid)
  241. {
  242. global $langs, $hookmanager, $extrafields;
  243. $error = 0;
  244. dol_syslog(__METHOD__, LOG_DEBUG);
  245. $object = new self($this->db);
  246. $this->db->begin();
  247. // Load source object
  248. $result = $object->fetchCommon($fromid);
  249. if ($result > 0 && !empty($object->table_element_line)) {
  250. $object->fetchLines();
  251. }
  252. // Get lines so they will be clone
  253. //foreach ($object->lines as $line)
  254. // $line->fetch_optionals();
  255. // Reset some properties
  256. unset($object->id);
  257. unset($object->fk_user_creat);
  258. unset($object->import_key);
  259. // Clear fields
  260. $object->ref = empty($this->fields['ref']['default']) ? $langs->trans("copy_of_").$object->ref : $this->fields['ref']['default'];
  261. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  262. $object->status = self::STATUS_DRAFT;
  263. // ...
  264. // Clear extrafields that are unique
  265. if (is_array($object->array_options) && count($object->array_options) > 0) {
  266. $extrafields->fetch_name_optionals_label($object->table_element);
  267. foreach ($object->array_options as $key => $option) {
  268. $shortkey = preg_replace('/options_/', '', $key);
  269. if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
  270. //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
  271. unset($object->array_options[$key]);
  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. if (!$error) {
  284. // copy internal contacts
  285. if ($this->copy_linked_contact($object, 'internal') < 0) {
  286. $error++;
  287. }
  288. }
  289. if (!$error) {
  290. // copy external contacts if same company
  291. if (property_exists($this, 'socid') && $this->socid == $object->socid) {
  292. if ($this->copy_linked_contact($object, 'external') < 0) {
  293. $error++;
  294. }
  295. }
  296. }
  297. // If there is lines, create lines too
  298. unset($object->context['createfromclone']);
  299. // End
  300. if (!$error) {
  301. $this->db->commit();
  302. return $object;
  303. } else {
  304. $this->db->rollback();
  305. return -1;
  306. }
  307. }
  308. /**
  309. * Load object in memory from the database
  310. *
  311. * @param int $id Id object
  312. * @param string $ref Ref
  313. * @return int <0 if KO, 0 if not found, >0 if OK
  314. */
  315. public function fetch($id, $ref = null)
  316. {
  317. $result = $this->fetchCommon($id, $ref);
  318. if ($result > 0 && !empty($this->table_element_line)) {
  319. $this->fetchLines();
  320. }
  321. //$this->calculateCosts(); // This consume a high number of subrequests. Do not call it into fetch but when you need it.
  322. return $result;
  323. }
  324. /**
  325. * Load object lines in memory from the database
  326. *
  327. * @return int <0 if KO, 0 if not found, >0 if OK
  328. */
  329. public function fetchLines()
  330. {
  331. $this->lines = array();
  332. $result = $this->fetchLinesCommon();
  333. return $result;
  334. }
  335. /**
  336. * Load list of objects in memory from the database.
  337. *
  338. * @param string $sortorder Sort Order
  339. * @param string $sortfield Sort field
  340. * @param int $limit limit
  341. * @param int $offset Offset
  342. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  343. * @param string $filtermode Filter mode (AND or OR)
  344. * @return array|int int <0 if KO, array of pages if OK
  345. */
  346. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  347. {
  348. global $conf;
  349. dol_syslog(__METHOD__, LOG_DEBUG);
  350. $records = array();
  351. $sql = 'SELECT ';
  352. $sql .= $this->getFieldList();
  353. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  354. if ($this->ismultientitymanaged) {
  355. $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
  356. } else {
  357. $sql .= ' WHERE 1 = 1';
  358. }
  359. // Manage filter
  360. $sqlwhere = array();
  361. if (count($filter) > 0) {
  362. foreach ($filter as $key => $value) {
  363. if ($key == 't.rowid') {
  364. $sqlwhere[] = $key." = ".((int) $value);
  365. } elseif (strpos($key, 'date') !== false) {
  366. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  367. } elseif ($key == 'customsql') {
  368. $sqlwhere[] = $value;
  369. } else {
  370. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  371. }
  372. }
  373. }
  374. if (count($sqlwhere) > 0) {
  375. $sql .= " AND (".implode(" ".$filtermode." ", $sqlwhere).")";
  376. }
  377. if (!empty($sortfield)) {
  378. $sql .= $this->db->order($sortfield, $sortorder);
  379. }
  380. if (!empty($limit)) {
  381. $sql .= $this->db->plimit($limit, $offset);
  382. }
  383. $resql = $this->db->query($sql);
  384. if ($resql) {
  385. $num = $this->db->num_rows($resql);
  386. while ($obj = $this->db->fetch_object($resql)) {
  387. $record = new self($this->db);
  388. $record->setVarsFromFetchObj($obj);
  389. $records[$record->id] = $record;
  390. }
  391. $this->db->free($resql);
  392. return $records;
  393. } else {
  394. $this->errors[] = 'Error '.$this->db->lasterror();
  395. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  396. return -1;
  397. }
  398. }
  399. /**
  400. * Update object into database
  401. *
  402. * @param User $user User that modifies
  403. * @param bool $notrigger false=launch triggers after, true=disable triggers
  404. * @return int <0 if KO, >0 if OK
  405. */
  406. public function update(User $user, $notrigger = false)
  407. {
  408. if ($this->efficiency <= 0 || $this->efficiency > 1) {
  409. $this->efficiency = 1;
  410. }
  411. return $this->updateCommon($user, $notrigger);
  412. }
  413. /**
  414. * Delete object in database
  415. *
  416. * @param User $user User that deletes
  417. * @param bool $notrigger false=launch triggers after, true=disable triggers
  418. * @return int <0 if KO, >0 if OK
  419. */
  420. public function delete(User $user, $notrigger = false)
  421. {
  422. return $this->deleteCommon($user, $notrigger);
  423. //return $this->deleteCommon($user, $notrigger, 1);
  424. }
  425. /**
  426. * Add an BOM line into database (linked to BOM)
  427. *
  428. * @param int $fk_product Id of product
  429. * @param float $qty Quantity
  430. * @param int $qty_frozen Frozen quantity
  431. * @param int $disable_stock_change Disable stock change on using in MO
  432. * @param float $efficiency Efficiency in MO
  433. * @param int $position Position of BOM-Line in BOM-Lines
  434. * @param int $fk_bom_child Id of BOM Child
  435. * @param string $import_key Import Key
  436. * @return int <0 if KO, Id of created object if OK
  437. */
  438. public function addLine($fk_product, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $fk_bom_child = null, $import_key = null)
  439. {
  440. global $mysoc, $conf, $langs, $user;
  441. $logtext = "::addLine bomid=$this->id, qty=$qty, fk_product=$fk_product, qty_frozen=$qty_frozen, disable_stock_change=$disable_stock_change, efficiency=$efficiency";
  442. $logtext .= ", fk_bom_child=$fk_bom_child, import_key=$import_key";
  443. dol_syslog(get_class($this).$logtext, LOG_DEBUG);
  444. if ($this->statut == self::STATUS_DRAFT) {
  445. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  446. // Clean parameters
  447. if (empty($qty)) {
  448. $qty = 0;
  449. }
  450. if (empty($qty_frozen)) {
  451. $qty_frozen = 0;
  452. }
  453. if (empty($disable_stock_change)) {
  454. $disable_stock_change = 0;
  455. }
  456. if (empty($efficiency)) {
  457. $efficiency = 1.0;
  458. }
  459. if (empty($fk_bom_child)) {
  460. $fk_bom_child = null;
  461. }
  462. if (empty($import_key)) {
  463. $import_key = null;
  464. }
  465. if (empty($position)) {
  466. $position = -1;
  467. }
  468. $qty = price2num($qty);
  469. $efficiency = price2num($efficiency);
  470. $position = price2num($position);
  471. $this->db->begin();
  472. // Rank to use
  473. $rangMax = $this->line_max();
  474. $rankToUse = $position;
  475. if ($rankToUse <= 0 or $rankToUse > $rangMax) { // New line after existing lines
  476. $rankToUse = $rangMax + 1;
  477. } else { // New line between the existing lines
  478. foreach ($this->lines as $bl) {
  479. if ($bl->position >= $rankToUse) {
  480. $bl->position++;
  481. $bl->update($user);
  482. }
  483. }
  484. }
  485. // Insert line
  486. $this->line = new BOMLine($this->db);
  487. $this->line->context = $this->context;
  488. $this->line->fk_bom = $this->id;
  489. $this->line->fk_product = $fk_product;
  490. $this->line->qty = $qty;
  491. $this->line->qty_frozen = $qty_frozen;
  492. $this->line->disable_stock_change = $disable_stock_change;
  493. $this->line->efficiency = $efficiency;
  494. $this->line->fk_bom_child = $fk_bom_child;
  495. $this->line->import_key = $import_key;
  496. $this->line->position = $rankToUse;
  497. $result = $this->line->create($user);
  498. if ($result > 0) {
  499. $this->calculateCosts();
  500. $this->db->commit();
  501. return $result;
  502. } else {
  503. $this->error = $this->line->error;
  504. dol_syslog(get_class($this)."::addLine error=".$this->error, LOG_ERR);
  505. $this->db->rollback();
  506. return -2;
  507. }
  508. } else {
  509. dol_syslog(get_class($this)."::addLine status of BOM must be Draft to allow use of ->addLine()", LOG_ERR);
  510. return -3;
  511. }
  512. }
  513. /**
  514. * Update an BOM line into database
  515. *
  516. * @param int $rowid Id of line to update
  517. * @param float $qty Quantity
  518. * @param int $qty_frozen Frozen quantity
  519. * @param int $disable_stock_change Disable stock change on using in MO
  520. * @param float $efficiency Efficiency in MO
  521. * @param int $position Position of BOM-Line in BOM-Lines
  522. * @param int $fk_bom_child Id of BOM Child
  523. * @param string $import_key Import Key
  524. * @return int <0 if KO, Id of updated BOM-Line if OK
  525. */
  526. public function updateLine($rowid, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $import_key = null)
  527. {
  528. global $mysoc, $conf, $langs, $user;
  529. $logtext = "::updateLine bomid=$this->id, qty=$qty, qty_frozen=$qty_frozen, disable_stock_change=$disable_stock_change, efficiency=$efficiency";
  530. $logtext .= ", import_key=$import_key";
  531. dol_syslog(get_class($this).$logtext, LOG_DEBUG);
  532. if ($this->statut == self::STATUS_DRAFT) {
  533. include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
  534. // Clean parameters
  535. if (empty($qty)) {
  536. $qty = 0;
  537. }
  538. if (empty($qty_frozen)) {
  539. $qty_frozen = 0;
  540. }
  541. if (empty($disable_stock_change)) {
  542. $disable_stock_change = 0;
  543. }
  544. if (empty($efficiency)) {
  545. $efficiency = 1.0;
  546. }
  547. if (empty($import_key)) {
  548. $import_key = null;
  549. }
  550. if (empty($position)) {
  551. $position = -1;
  552. }
  553. $qty = price2num($qty);
  554. $efficiency = price2num($efficiency);
  555. $position = price2num($position);
  556. $this->db->begin();
  557. //Fetch current line from the database and then clone the object and set it in $oldline property
  558. $line = new BOMLine($this->db);
  559. $line->fetch($rowid);
  560. $line->fetch_optionals();
  561. $staticLine = clone $line;
  562. $line->oldcopy = $staticLine;
  563. $this->line = $line;
  564. $this->line->context = $this->context;
  565. // Rank to use
  566. $rankToUse = (int) $position;
  567. if ($rankToUse != $line->oldcopy->position) { // check if position have a new value
  568. foreach ($this->lines as $bl) {
  569. if ($bl->position >= $rankToUse AND $bl->position < ($line->oldcopy->position + 1)) { // move rank up
  570. $bl->position++;
  571. $bl->update($user);
  572. }
  573. if ($bl->position <= $rankToUse AND $bl->position > ($line->oldcopy->position)) { // move rank down
  574. $bl->position--;
  575. $bl->update($user);
  576. }
  577. }
  578. }
  579. $this->line->fk_bom = $this->id;
  580. $this->line->qty = $qty;
  581. $this->line->qty_frozen = $qty_frozen;
  582. $this->line->disable_stock_change = $disable_stock_change;
  583. $this->line->efficiency = $efficiency;
  584. $this->line->import_key = $import_key;
  585. $this->line->position = $rankToUse;
  586. $result = $this->line->update($user);
  587. if ($result > 0) {
  588. $this->calculateCosts();
  589. $this->db->commit();
  590. return $result;
  591. } else {
  592. $this->error = $this->line->error;
  593. dol_syslog(get_class($this)."::addLine error=".$this->error, LOG_ERR);
  594. $this->db->rollback();
  595. return -2;
  596. }
  597. } else {
  598. dol_syslog(get_class($this)."::addLine status of BOM must be Draft to allow use of ->addLine()", LOG_ERR);
  599. return -3;
  600. }
  601. }
  602. /**
  603. * Delete a line of object in database
  604. *
  605. * @param User $user User that delete
  606. * @param int $idline Id of line to delete
  607. * @param bool $notrigger false=launch triggers after, true=disable triggers
  608. * @return int >0 if OK, <0 if KO
  609. */
  610. public function deleteLine(User $user, $idline, $notrigger = false)
  611. {
  612. if ($this->status < 0) {
  613. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  614. return -2;
  615. }
  616. $this->db->begin();
  617. //Fetch current line from the database and then clone the object and set it in $oldline property
  618. $line = new BOMLine($this->db);
  619. $line->fetch($idline);
  620. $line->fetch_optionals();
  621. $staticLine = clone $line;
  622. $line->oldcopy = $staticLine;
  623. $this->line = $line;
  624. $this->line->context = $this->context;
  625. $result = $this->line->delete($user, $notrigger);
  626. //Positions (rank) reordering
  627. foreach ($this->lines as $bl) {
  628. if ($bl->position > ($line->oldcopy->position)) { // move rank down
  629. $bl->position--;
  630. $bl->update($user);
  631. }
  632. }
  633. if ($result > 0) {
  634. $this->calculateCosts();
  635. $this->db->commit();
  636. return $result;
  637. } else {
  638. $this->error = $this->line->error;
  639. dol_syslog(get_class($this)."::addLine error=".$this->error, LOG_ERR);
  640. $this->db->rollback();
  641. return -2;
  642. }
  643. }
  644. /**
  645. * Returns the reference to the following non used BOM depending on the active numbering module
  646. * defined into BOM_ADDON
  647. *
  648. * @param Product $prod Object product
  649. * @return string BOM free reference
  650. */
  651. public function getNextNumRef($prod)
  652. {
  653. global $langs, $conf;
  654. $langs->load("mrp");
  655. if (!empty($conf->global->BOM_ADDON)) {
  656. $mybool = false;
  657. $file = $conf->global->BOM_ADDON.".php";
  658. $classname = $conf->global->BOM_ADDON;
  659. // Include file with class
  660. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  661. foreach ($dirmodels as $reldir) {
  662. $dir = dol_buildpath($reldir."core/modules/bom/");
  663. // Load file with numbering class (if found)
  664. $mybool |= @include_once $dir.$file;
  665. }
  666. if ($mybool === false) {
  667. dol_print_error('', "Failed to include file ".$file);
  668. return '';
  669. }
  670. $obj = new $classname();
  671. $numref = $obj->getNextValue($prod, $this);
  672. if ($numref != "") {
  673. return $numref;
  674. } else {
  675. $this->error = $obj->error;
  676. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  677. return "";
  678. }
  679. } else {
  680. print $langs->trans("Error")." ".$langs->trans("Error_BOM_ADDON_NotDefined");
  681. return "";
  682. }
  683. }
  684. /**
  685. * Validate bom
  686. *
  687. * @param User $user User making status change
  688. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  689. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  690. */
  691. public function validate($user, $notrigger = 0)
  692. {
  693. global $conf, $langs;
  694. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  695. $error = 0;
  696. // Protection
  697. if ($this->status == self::STATUS_VALIDATED) {
  698. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  699. return 0;
  700. }
  701. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->create))
  702. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  703. {
  704. $this->error='NotEnoughPermissions';
  705. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  706. return -1;
  707. }*/
  708. $now = dol_now();
  709. $this->db->begin();
  710. // Define new ref
  711. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  712. $this->fetch_product();
  713. $num = $this->getNextNumRef($this->product);
  714. } else {
  715. $num = $this->ref;
  716. }
  717. $this->newref = dol_sanitizeFileName($num);
  718. // Validate
  719. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  720. $sql .= " SET ref = '".$this->db->escape($num)."',";
  721. $sql .= " status = ".self::STATUS_VALIDATED.",";
  722. $sql .= " date_valid='".$this->db->idate($now)."',";
  723. $sql .= " fk_user_valid = ".((int) $user->id);
  724. $sql .= " WHERE rowid = ".((int) $this->id);
  725. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  726. $resql = $this->db->query($sql);
  727. if (!$resql) {
  728. dol_print_error($this->db);
  729. $this->error = $this->db->lasterror();
  730. $error++;
  731. }
  732. if (!$error && !$notrigger) {
  733. // Call trigger
  734. $result = $this->call_trigger('BOM_VALIDATE', $user);
  735. if ($result < 0) {
  736. $error++;
  737. }
  738. // End call triggers
  739. }
  740. if (!$error) {
  741. $this->oldref = $this->ref;
  742. // Rename directory if dir was a temporary ref
  743. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  744. // Now we rename also files into index
  745. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'bom/".$this->db->escape($this->newref)."'";
  746. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  747. $resql = $this->db->query($sql);
  748. if (!$resql) {
  749. $error++; $this->error = $this->db->lasterror();
  750. }
  751. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  752. $oldref = dol_sanitizeFileName($this->ref);
  753. $newref = dol_sanitizeFileName($num);
  754. $dirsource = $conf->bom->dir_output.'/'.$oldref;
  755. $dirdest = $conf->bom->dir_output.'/'.$newref;
  756. if (!$error && file_exists($dirsource)) {
  757. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  758. if (@rename($dirsource, $dirdest)) {
  759. dol_syslog("Rename ok");
  760. // Rename docs starting with $oldref with $newref
  761. $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  762. foreach ($listoffiles as $fileentry) {
  763. $dirsource = $fileentry['name'];
  764. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  765. $dirsource = $fileentry['path'].'/'.$dirsource;
  766. $dirdest = $fileentry['path'].'/'.$dirdest;
  767. @rename($dirsource, $dirdest);
  768. }
  769. }
  770. }
  771. }
  772. }
  773. // Set new ref and current status
  774. if (!$error) {
  775. $this->ref = $num;
  776. $this->status = self::STATUS_VALIDATED;
  777. }
  778. if (!$error) {
  779. $this->db->commit();
  780. return 1;
  781. } else {
  782. $this->db->rollback();
  783. return -1;
  784. }
  785. }
  786. /**
  787. * Set draft status
  788. *
  789. * @param User $user Object user that modify
  790. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  791. * @return int <0 if KO, >0 if OK
  792. */
  793. public function setDraft($user, $notrigger = 0)
  794. {
  795. // Protection
  796. if ($this->status <= self::STATUS_DRAFT) {
  797. return 0;
  798. }
  799. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
  800. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  801. {
  802. $this->error='Permission denied';
  803. return -1;
  804. }*/
  805. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'BOM_UNVALIDATE');
  806. }
  807. /**
  808. * Set cancel status
  809. *
  810. * @param User $user Object user that modify
  811. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  812. * @return int <0 if KO, 0=Nothing done, >0 if OK
  813. */
  814. public function cancel($user, $notrigger = 0)
  815. {
  816. // Protection
  817. if ($this->status != self::STATUS_VALIDATED) {
  818. return 0;
  819. }
  820. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
  821. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  822. {
  823. $this->error='Permission denied';
  824. return -1;
  825. }*/
  826. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'BOM_CLOSE');
  827. }
  828. /**
  829. * Set cancel status
  830. *
  831. * @param User $user Object user that modify
  832. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  833. * @return int <0 if KO, 0=Nothing done, >0 if OK
  834. */
  835. public function reopen($user, $notrigger = 0)
  836. {
  837. // Protection
  838. if ($this->status != self::STATUS_CANCELED) {
  839. return 0;
  840. }
  841. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
  842. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  843. {
  844. $this->error='Permission denied';
  845. return -1;
  846. }*/
  847. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'BOM_REOPEN');
  848. }
  849. /**
  850. * Return a link to the object card (with optionaly the picto)
  851. *
  852. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  853. * @param string $option On what the link point to ('nolink', ...)
  854. * @param int $notooltip 1=Disable tooltip
  855. * @param string $morecss Add more css on link
  856. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  857. * @return string String with URL
  858. */
  859. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  860. {
  861. global $db, $conf, $langs, $hookmanager;
  862. if (!empty($conf->dol_no_mouse_hover)) {
  863. $notooltip = 1; // Force disable tooltips
  864. }
  865. $result = '';
  866. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("BillOfMaterials").'</u>';
  867. if (isset($this->status)) {
  868. $label .= ' '.$this->getLibStatut(5);
  869. }
  870. $label .= '<br>';
  871. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  872. if (isset($this->label)) {
  873. $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
  874. }
  875. if (!empty($this->fk_product) && $this->fk_product > 0) {
  876. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  877. $product = new Product($db);
  878. $resultFetch = $product->fetch($this->fk_product);
  879. if ($resultFetch > 0) {
  880. $label .= "<br><b>".$langs->trans("Product").'</b>: '.$product->ref.' - '.$product->label;
  881. }
  882. }
  883. $url = DOL_URL_ROOT.'/bom/bom_card.php?id='.$this->id;
  884. if ($option != 'nolink') {
  885. // Add param to save lastsearch_values or not
  886. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  887. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  888. $add_save_lastsearch_values = 1;
  889. }
  890. if ($add_save_lastsearch_values) {
  891. $url .= '&save_lastsearch_values=1';
  892. }
  893. }
  894. $linkclose = '';
  895. if (empty($notooltip)) {
  896. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  897. $label = $langs->trans("ShowBillOfMaterials");
  898. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  899. }
  900. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  901. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  902. } else {
  903. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  904. }
  905. $linkstart = '<a href="'.$url.'"';
  906. $linkstart .= $linkclose.'>';
  907. $linkend = '</a>';
  908. $result .= $linkstart;
  909. if ($withpicto) {
  910. $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);
  911. }
  912. if ($withpicto != 2) {
  913. $result .= $this->ref;
  914. }
  915. $result .= $linkend;
  916. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  917. global $action, $hookmanager;
  918. $hookmanager->initHooks(array('bomdao'));
  919. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  920. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  921. if ($reshook > 0) {
  922. $result = $hookmanager->resPrint;
  923. } else {
  924. $result .= $hookmanager->resPrint;
  925. }
  926. return $result;
  927. }
  928. /**
  929. * Return label of the status
  930. *
  931. * @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
  932. * @return string Label of status
  933. */
  934. public function getLibStatut($mode = 0)
  935. {
  936. return $this->LibStatut($this->status, $mode);
  937. }
  938. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  939. /**
  940. * Return the status
  941. *
  942. * @param int $status Id status
  943. * @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
  944. * @return string Label of status
  945. */
  946. public function LibStatut($status, $mode = 0)
  947. {
  948. // phpcs:enable
  949. if (empty($this->labelStatus)) {
  950. global $langs;
  951. //$langs->load("mrp");
  952. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  953. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  954. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  955. }
  956. $statusType = 'status'.$status;
  957. if ($status == self::STATUS_VALIDATED) {
  958. $statusType = 'status4';
  959. }
  960. if ($status == self::STATUS_CANCELED) {
  961. $statusType = 'status6';
  962. }
  963. return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode);
  964. }
  965. /**
  966. * Load the info information in the object
  967. *
  968. * @param int $id Id of object
  969. * @return void
  970. */
  971. public function info($id)
  972. {
  973. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  974. $sql .= ' fk_user_creat, fk_user_modif';
  975. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  976. $sql .= ' WHERE t.rowid = '.((int) $id);
  977. $result = $this->db->query($sql);
  978. if ($result) {
  979. if ($this->db->num_rows($result)) {
  980. $obj = $this->db->fetch_object($result);
  981. $this->id = $obj->rowid;
  982. $this->user_creation_id = $obj->fk_user_creat;
  983. $this->user_modification_id = $obj->fk_user_modif;
  984. $this->date_creation = $this->db->jdate($obj->datec);
  985. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  986. }
  987. $this->db->free($result);
  988. } else {
  989. dol_print_error($this->db);
  990. }
  991. }
  992. /**
  993. * Create an array of lines
  994. *
  995. * @return array|int array of lines if OK, <0 if KO
  996. */
  997. public function getLinesArray()
  998. {
  999. $this->lines = array();
  1000. $objectline = new BOMLine($this->db);
  1001. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.((int) $this->id)));
  1002. if (is_numeric($result)) {
  1003. $this->error = $objectline->error;
  1004. $this->errors = $objectline->errors;
  1005. return $result;
  1006. } else {
  1007. $this->lines = $result;
  1008. return $this->lines;
  1009. }
  1010. }
  1011. /**
  1012. * Create a document onto disk according to template module.
  1013. *
  1014. * @param string $modele Force template to use ('' to not force)
  1015. * @param Translate $outputlangs objet lang a utiliser pour traduction
  1016. * @param int $hidedetails Hide details of lines
  1017. * @param int $hidedesc Hide description
  1018. * @param int $hideref Hide ref
  1019. * @param null|array $moreparams Array to provide more information
  1020. * @return int 0 if KO, 1 if OK
  1021. */
  1022. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  1023. {
  1024. global $conf, $langs;
  1025. $langs->load("mrp");
  1026. $outputlangs->load("products");
  1027. if (!dol_strlen($modele)) {
  1028. $modele = 'standard';
  1029. if ($this->model_pdf) {
  1030. $modele = $this->model_pdf;
  1031. } elseif (!empty($conf->global->BOM_ADDON_PDF)) {
  1032. $modele = $conf->global->BOM_ADDON_PDF;
  1033. }
  1034. }
  1035. $modelpath = "core/modules/bom/doc/";
  1036. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1037. }
  1038. /**
  1039. * Initialise object with example values
  1040. * Id must be 0 if object instance is a specimen
  1041. *
  1042. * @return void
  1043. */
  1044. public function initAsSpecimen()
  1045. {
  1046. $this->initAsSpecimenCommon();
  1047. $this->ref = 'BOM-123';
  1048. $this->date = $this->date_creation;
  1049. }
  1050. /**
  1051. * Action executed by scheduler
  1052. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  1053. *
  1054. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  1055. */
  1056. public function doScheduledJob()
  1057. {
  1058. global $conf, $langs;
  1059. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  1060. $error = 0;
  1061. $this->output = '';
  1062. $this->error = '';
  1063. dol_syslog(__METHOD__, LOG_DEBUG);
  1064. $now = dol_now();
  1065. $this->db->begin();
  1066. // ...
  1067. $this->db->commit();
  1068. return $error;
  1069. }
  1070. /**
  1071. * BOM costs calculation based on cost_price or pmp of each BOM line.
  1072. * Set the property ->total_cost and ->unit_cost of BOM.
  1073. *
  1074. * @return void
  1075. */
  1076. public function calculateCosts()
  1077. {
  1078. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  1079. $this->unit_cost = 0;
  1080. $this->total_cost = 0;
  1081. if (is_array($this->lines) && count($this->lines)) {
  1082. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  1083. $productFournisseur = new ProductFournisseur($this->db);
  1084. $tmpproduct = new Product($this->db);
  1085. foreach ($this->lines as &$line) {
  1086. $tmpproduct->cost_price = 0;
  1087. $tmpproduct->pmp = 0;
  1088. if (empty($line->fk_bom_child)) {
  1089. $result = $tmpproduct->fetch($line->fk_product, '', '', '', 0, 1, 1); // We discard selling price and language loading
  1090. if ($result < 0) {
  1091. $this->error = $tmpproduct->error;
  1092. return -1;
  1093. }
  1094. $line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
  1095. if (empty($line->unit_cost)) {
  1096. if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) {
  1097. $line->unit_cost = $productFournisseur->fourn_unitprice;
  1098. }
  1099. }
  1100. $line->total_cost = price2num($line->qty * $line->unit_cost, 'MT');
  1101. $this->total_cost += $line->total_cost;
  1102. } else {
  1103. $bom_child= new BOM($this->db);
  1104. $res = $bom_child->fetch($line->fk_bom_child);
  1105. if ($res>0) {
  1106. $bom_child->calculateCosts();
  1107. $line->childBom[] = $bom_child;
  1108. $this->total_cost += $bom_child->total_cost * $line->qty;
  1109. } else {
  1110. $this->error = $bom_child->error;
  1111. return -2;
  1112. }
  1113. }
  1114. }
  1115. $this->total_cost = price2num($this->total_cost, 'MT');
  1116. if ($this->qty > 0) {
  1117. $this->unit_cost = price2num($this->total_cost / $this->qty, 'MU');
  1118. } elseif ($this->qty < 0) {
  1119. $this->unit_cost = price2num($this->total_cost * $this->qty, 'MU');
  1120. }
  1121. }
  1122. }
  1123. /**
  1124. * Function used to replace a product id with another one.
  1125. *
  1126. * @param DoliDB $db Database handler
  1127. * @param int $origin_id Old product id
  1128. * @param int $dest_id New product id
  1129. * @return bool
  1130. */
  1131. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  1132. {
  1133. $tables = array(
  1134. 'bom_bomline'
  1135. );
  1136. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  1137. }
  1138. /**
  1139. * Get Net needs by product
  1140. *
  1141. * @param array $TNetNeeds Array of ChildBom and infos linked to
  1142. * @param int $qty qty needed
  1143. * @return void
  1144. */
  1145. public function getNetNeeds(&$TNetNeeds = array(), $qty = 0)
  1146. {
  1147. if (! empty($this->lines)) {
  1148. foreach ($this->lines as $line) {
  1149. if (! empty($line->childBom)) {
  1150. foreach ($line->childBom as $childBom) $childBom->getNetNeeds($TNetNeeds, $line->qty*$qty);
  1151. } else {
  1152. if (empty($TNetNeeds[$line->fk_product])) {
  1153. $TNetNeeds[$line->fk_product] = 0;
  1154. }
  1155. $TNetNeeds[$line->fk_product] += $line->qty*$qty;
  1156. }
  1157. }
  1158. }
  1159. }
  1160. /**
  1161. * Get Net needs Tree by product or bom
  1162. *
  1163. * @param array $TNetNeeds Array of ChildBom and infos linked to
  1164. * @param int $qty qty needed
  1165. * @param int $level level of recursivity
  1166. * @return void
  1167. */
  1168. public function getNetNeedsTree(&$TNetNeeds = array(), $qty = 0, $level = 0)
  1169. {
  1170. if (! empty($this->lines)) {
  1171. foreach ($this->lines as $line) {
  1172. if (! empty($line->childBom)) {
  1173. foreach ($line->childBom as $childBom) {
  1174. $TNetNeeds[$childBom->id]['bom'] = $childBom;
  1175. $TNetNeeds[$childBom->id]['parentid'] = $this->id;
  1176. $TNetNeeds[$childBom->id]['qty'] = $line->qty*$qty;
  1177. $TNetNeeds[$childBom->id]['level'] = $level;
  1178. $childBom->getNetNeedsTree($TNetNeeds, $line->qty*$qty, $level+1);
  1179. }
  1180. } else {
  1181. $TNetNeeds[$this->id]['product'][$line->fk_product]['qty'] += $line->qty * $qty;
  1182. $TNetNeeds[$this->id]['product'][$line->fk_product]['level'] = $level;
  1183. }
  1184. }
  1185. }
  1186. }
  1187. }
  1188. /**
  1189. * Class for BOMLine
  1190. */
  1191. class BOMLine extends CommonObjectLine
  1192. {
  1193. /**
  1194. * @var string ID to identify managed object
  1195. */
  1196. public $element = 'bomline';
  1197. /**
  1198. * @var string Name of table without prefix where object is stored
  1199. */
  1200. public $table_element = 'bom_bomline';
  1201. /**
  1202. * @var int Does bomline support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  1203. */
  1204. public $ismultientitymanaged = 0;
  1205. /**
  1206. * @var int Does bomline support extrafields ? 0=No, 1=Yes
  1207. */
  1208. public $isextrafieldmanaged = 1;
  1209. /**
  1210. * @var string String with name of icon for bomline. Must be the part after the 'object_' into object_bomline.png
  1211. */
  1212. public $picto = 'bomline';
  1213. /**
  1214. * 'type' if the field format.
  1215. * 'label' the translation key.
  1216. * 'enabled' is a condition when the field must be managed.
  1217. * '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. Using a negative value means field is not shown by default on list but can be selected for viewing)
  1218. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  1219. * 'default' is a default value for creation (can still be replaced by the global setup of default values)
  1220. * 'index' if we want an index in database.
  1221. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  1222. * 'position' is the sort order of field.
  1223. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  1224. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  1225. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  1226. * 'help' is a string visible as a tooltip on field
  1227. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  1228. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  1229. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  1230. */
  1231. // BEGIN MODULEBUILDER PROPERTIES
  1232. /**
  1233. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  1234. */
  1235. public $fields = array(
  1236. 'rowid' => array('type'=>'integer', 'label'=>'LineID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
  1237. 'fk_bom' => array('type'=>'integer:BillOfMaterials:societe/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1,),
  1238. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
  1239. 'fk_bom_child' => array('type'=>'integer:BOM:bom/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>-1, 'position'=>40, 'notnull'=>-1,),
  1240. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,),
  1241. 'qty' => array('type'=>'double(24,8)', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'notnull'=>1, 'isameasure'=>'1',),
  1242. 'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
  1243. 'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
  1244. 'efficiency' => array('type'=>'double(24,8)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfEfficiencyConsumedMeans'),
  1245. 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,),
  1246. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
  1247. );
  1248. /**
  1249. * @var int rowid
  1250. */
  1251. public $rowid;
  1252. /**
  1253. * @var int fk_bom
  1254. */
  1255. public $fk_bom;
  1256. /**
  1257. * @var int Id of product
  1258. */
  1259. public $fk_product;
  1260. /**
  1261. * @var int Id of parent bom
  1262. */
  1263. public $fk_bom_child;
  1264. /**
  1265. * @var string description
  1266. */
  1267. public $description;
  1268. public $qty;
  1269. /**
  1270. * @var int qty frozen
  1271. */
  1272. public $qty_frozen;
  1273. public $disable_stock_change;
  1274. public $efficiency;
  1275. /**
  1276. * @var int position of line
  1277. */
  1278. public $position;
  1279. /**
  1280. * @var string import key
  1281. */
  1282. public $import_key;
  1283. // END MODULEBUILDER PROPERTIES
  1284. /**
  1285. * @var int Calculated cost for the BOM line
  1286. */
  1287. public $total_cost = 0;
  1288. /**
  1289. * @var int Line unit cost based on product cost price or pmp
  1290. */
  1291. public $unit_cost = 0;
  1292. /**
  1293. * @var Bom array of Bom in line
  1294. */
  1295. public $childBom = array();
  1296. /**
  1297. * Constructor
  1298. *
  1299. * @param DoliDb $db Database handler
  1300. */
  1301. public function __construct(DoliDB $db)
  1302. {
  1303. global $conf, $langs;
  1304. $this->db = $db;
  1305. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  1306. $this->fields['rowid']['visible'] = 0;
  1307. }
  1308. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  1309. $this->fields['entity']['enabled'] = 0;
  1310. }
  1311. // Unset fields that are disabled
  1312. foreach ($this->fields as $key => $val) {
  1313. if (isset($val['enabled']) && empty($val['enabled'])) {
  1314. unset($this->fields[$key]);
  1315. }
  1316. }
  1317. // Translate some data of arrayofkeyval
  1318. foreach ($this->fields as $key => $val) {
  1319. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  1320. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  1321. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  1322. }
  1323. }
  1324. }
  1325. }
  1326. /**
  1327. * Create object into database
  1328. *
  1329. * @param User $user User that creates
  1330. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1331. * @return int <0 if KO, Id of created object if OK
  1332. */
  1333. public function create(User $user, $notrigger = false)
  1334. {
  1335. if ($this->efficiency < 0 || $this->efficiency > 1) {
  1336. $this->efficiency = 1;
  1337. }
  1338. return $this->createCommon($user, $notrigger);
  1339. }
  1340. /**
  1341. * Load object in memory from the database
  1342. *
  1343. * @param int $id Id object
  1344. * @param string $ref Ref
  1345. * @return int <0 if KO, 0 if not found, >0 if OK
  1346. */
  1347. public function fetch($id, $ref = null)
  1348. {
  1349. $result = $this->fetchCommon($id, $ref);
  1350. //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
  1351. return $result;
  1352. }
  1353. /**
  1354. * Load list of objects in memory from the database.
  1355. *
  1356. * @param string $sortorder Sort Order
  1357. * @param string $sortfield Sort field
  1358. * @param int $limit limit
  1359. * @param int $offset Offset
  1360. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  1361. * @param string $filtermode Filter mode (AND or OR)
  1362. * @return array|int int <0 if KO, array of pages if OK
  1363. */
  1364. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  1365. {
  1366. global $conf;
  1367. dol_syslog(__METHOD__, LOG_DEBUG);
  1368. $records = array();
  1369. $sql = 'SELECT ';
  1370. $sql .= $this->getFieldList();
  1371. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1372. if ($this->ismultientitymanaged) {
  1373. $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
  1374. } else {
  1375. $sql .= ' WHERE 1 = 1';
  1376. }
  1377. // Manage filter
  1378. $sqlwhere = array();
  1379. if (count($filter) > 0) {
  1380. foreach ($filter as $key => $value) {
  1381. if ($key == 't.rowid') {
  1382. $sqlwhere[] = $key." = ".((int) $value);
  1383. } elseif (strpos($key, 'date') !== false) {
  1384. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  1385. } elseif ($key == 'customsql') {
  1386. $sqlwhere[] = $value;
  1387. } else {
  1388. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  1389. }
  1390. }
  1391. }
  1392. if (count($sqlwhere) > 0) {
  1393. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  1394. }
  1395. if (!empty($sortfield)) {
  1396. $sql .= $this->db->order($sortfield, $sortorder);
  1397. }
  1398. if (!empty($limit)) {
  1399. $sql .= $this->db->plimit($limit, $offset);
  1400. }
  1401. $resql = $this->db->query($sql);
  1402. if ($resql) {
  1403. $num = $this->db->num_rows($resql);
  1404. while ($obj = $this->db->fetch_object($resql)) {
  1405. $record = new self($this->db);
  1406. $record->setVarsFromFetchObj($obj);
  1407. $records[$record->id] = $record;
  1408. }
  1409. $this->db->free($resql);
  1410. return $records;
  1411. } else {
  1412. $this->errors[] = 'Error '.$this->db->lasterror();
  1413. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1414. return -1;
  1415. }
  1416. }
  1417. /**
  1418. * Update object into database
  1419. *
  1420. * @param User $user User that modifies
  1421. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1422. * @return int <0 if KO, >0 if OK
  1423. */
  1424. public function update(User $user, $notrigger = false)
  1425. {
  1426. if ($this->efficiency < 0 || $this->efficiency > 1) {
  1427. $this->efficiency = 1;
  1428. }
  1429. return $this->updateCommon($user, $notrigger);
  1430. }
  1431. /**
  1432. * Delete object in database
  1433. *
  1434. * @param User $user User that deletes
  1435. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1436. * @return int <0 if KO, >0 if OK
  1437. */
  1438. public function delete(User $user, $notrigger = false)
  1439. {
  1440. return $this->deleteCommon($user, $notrigger);
  1441. //return $this->deleteCommon($user, $notrigger, 1);
  1442. }
  1443. /**
  1444. * Return a link to the object card (with optionaly the picto)
  1445. *
  1446. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1447. * @param string $option On what the link point to ('nolink', ...)
  1448. * @param int $notooltip 1=Disable tooltip
  1449. * @param string $morecss Add more css on link
  1450. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1451. * @return string String with URL
  1452. */
  1453. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1454. {
  1455. global $db, $conf, $langs, $hookmanager;
  1456. if (!empty($conf->dol_no_mouse_hover)) {
  1457. $notooltip = 1; // Force disable tooltips
  1458. }
  1459. $result = '';
  1460. $label = '<u>'.$langs->trans("BillOfMaterialsLine").'</u>';
  1461. $label .= '<br>';
  1462. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1463. $url = DOL_URL_ROOT.'/bom/bomline_card.php?id='.$this->id;
  1464. if ($option != 'nolink') {
  1465. // Add param to save lastsearch_values or not
  1466. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1467. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1468. $add_save_lastsearch_values = 1;
  1469. }
  1470. if ($add_save_lastsearch_values) {
  1471. $url .= '&save_lastsearch_values=1';
  1472. }
  1473. }
  1474. $linkclose = '';
  1475. if (empty($notooltip)) {
  1476. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1477. $label = $langs->trans("ShowBillOfMaterialsLine");
  1478. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1479. }
  1480. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1481. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1482. } else {
  1483. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1484. }
  1485. $linkstart = '<a href="'.$url.'"';
  1486. $linkstart .= $linkclose.'>';
  1487. $linkend = '</a>';
  1488. $result .= $linkstart;
  1489. if ($withpicto) {
  1490. $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);
  1491. }
  1492. if ($withpicto != 2) {
  1493. $result .= $this->ref;
  1494. }
  1495. $result .= $linkend;
  1496. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1497. global $action, $hookmanager;
  1498. $hookmanager->initHooks(array('bomlinedao'));
  1499. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1500. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1501. if ($reshook > 0) {
  1502. $result = $hookmanager->resPrint;
  1503. } else {
  1504. $result .= $hookmanager->resPrint;
  1505. }
  1506. return $result;
  1507. }
  1508. /**
  1509. * Return label of the status
  1510. *
  1511. * @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
  1512. * @return string Label of status
  1513. */
  1514. public function getLibStatut($mode = 0)
  1515. {
  1516. return $this->LibStatut($this->status, $mode);
  1517. }
  1518. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1519. /**
  1520. * Return the status
  1521. *
  1522. * @param int $status Id status
  1523. * @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
  1524. * @return string Label of status
  1525. */
  1526. public function LibStatut($status, $mode = 0)
  1527. {
  1528. // phpcs:enable
  1529. return '';
  1530. }
  1531. /**
  1532. * Load the info information in the object
  1533. *
  1534. * @param int $id Id of object
  1535. * @return void
  1536. */
  1537. public function info($id)
  1538. {
  1539. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  1540. $sql .= ' fk_user_creat, fk_user_modif';
  1541. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1542. $sql .= ' WHERE t.rowid = '.((int) $id);
  1543. $result = $this->db->query($sql);
  1544. if ($result) {
  1545. if ($this->db->num_rows($result)) {
  1546. $obj = $this->db->fetch_object($result);
  1547. $this->id = $obj->rowid;
  1548. $this->user_creation_id = $obj->fk_user_creat;
  1549. $this->user_modification_id = $obj->fk_user_modif;
  1550. $this->date_creation = $this->db->jdate($obj->datec);
  1551. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  1552. }
  1553. $this->db->free($result);
  1554. } else {
  1555. dol_print_error($this->db);
  1556. }
  1557. }
  1558. /**
  1559. * Initialise object with example values
  1560. * Id must be 0 if object instance is a specimen
  1561. *
  1562. * @return void
  1563. */
  1564. public function initAsSpecimen()
  1565. {
  1566. $this->initAsSpecimenCommon();
  1567. }
  1568. }