bom.class.php 62 KB

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