bom.class.php 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636
  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',),
  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. * Delete a line of object in database
  427. *
  428. * @param User $user User that delete
  429. * @param int $idline Id of line to delete
  430. * @param bool $notrigger false=launch triggers after, true=disable triggers
  431. * @return int >0 if OK, <0 if KO
  432. */
  433. public function deleteLine(User $user, $idline, $notrigger = false)
  434. {
  435. if ($this->status < 0) {
  436. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  437. return -2;
  438. }
  439. return $this->deleteLineCommon($user, $idline, $notrigger);
  440. }
  441. /**
  442. * Returns the reference to the following non used BOM depending on the active numbering module
  443. * defined into BOM_ADDON
  444. *
  445. * @param Product $prod Object product
  446. * @return string BOM free reference
  447. */
  448. public function getNextNumRef($prod)
  449. {
  450. global $langs, $conf;
  451. $langs->load("mrp");
  452. if (!empty($conf->global->BOM_ADDON)) {
  453. $mybool = false;
  454. $file = $conf->global->BOM_ADDON.".php";
  455. $classname = $conf->global->BOM_ADDON;
  456. // Include file with class
  457. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  458. foreach ($dirmodels as $reldir) {
  459. $dir = dol_buildpath($reldir."core/modules/bom/");
  460. // Load file with numbering class (if found)
  461. $mybool |= @include_once $dir.$file;
  462. }
  463. if ($mybool === false) {
  464. dol_print_error('', "Failed to include file ".$file);
  465. return '';
  466. }
  467. $obj = new $classname();
  468. $numref = $obj->getNextValue($prod, $this);
  469. if ($numref != "") {
  470. return $numref;
  471. } else {
  472. $this->error = $obj->error;
  473. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  474. return "";
  475. }
  476. } else {
  477. print $langs->trans("Error")." ".$langs->trans("Error_BOM_ADDON_NotDefined");
  478. return "";
  479. }
  480. }
  481. /**
  482. * Validate bom
  483. *
  484. * @param User $user User making status change
  485. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  486. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  487. */
  488. public function validate($user, $notrigger = 0)
  489. {
  490. global $conf, $langs;
  491. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  492. $error = 0;
  493. // Protection
  494. if ($this->status == self::STATUS_VALIDATED) {
  495. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  496. return 0;
  497. }
  498. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->create))
  499. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  500. {
  501. $this->error='NotEnoughPermissions';
  502. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  503. return -1;
  504. }*/
  505. $now = dol_now();
  506. $this->db->begin();
  507. // Define new ref
  508. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  509. $this->fetch_product();
  510. $num = $this->getNextNumRef($this->product);
  511. } else {
  512. $num = $this->ref;
  513. }
  514. $this->newref = dol_sanitizeFileName($num);
  515. // Validate
  516. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  517. $sql .= " SET ref = '".$this->db->escape($num)."',";
  518. $sql .= " status = ".self::STATUS_VALIDATED.",";
  519. $sql .= " date_valid='".$this->db->idate($now)."',";
  520. $sql .= " fk_user_valid = ".((int) $user->id);
  521. $sql .= " WHERE rowid = ".((int) $this->id);
  522. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  523. $resql = $this->db->query($sql);
  524. if (!$resql) {
  525. dol_print_error($this->db);
  526. $this->error = $this->db->lasterror();
  527. $error++;
  528. }
  529. if (!$error && !$notrigger) {
  530. // Call trigger
  531. $result = $this->call_trigger('BOM_VALIDATE', $user);
  532. if ($result < 0) {
  533. $error++;
  534. }
  535. // End call triggers
  536. }
  537. if (!$error) {
  538. $this->oldref = $this->ref;
  539. // Rename directory if dir was a temporary ref
  540. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  541. // Now we rename also files into index
  542. $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)."'";
  543. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  544. $resql = $this->db->query($sql);
  545. if (!$resql) {
  546. $error++; $this->error = $this->db->lasterror();
  547. }
  548. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  549. $oldref = dol_sanitizeFileName($this->ref);
  550. $newref = dol_sanitizeFileName($num);
  551. $dirsource = $conf->bom->dir_output.'/'.$oldref;
  552. $dirdest = $conf->bom->dir_output.'/'.$newref;
  553. if (!$error && file_exists($dirsource)) {
  554. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  555. if (@rename($dirsource, $dirdest)) {
  556. dol_syslog("Rename ok");
  557. // Rename docs starting with $oldref with $newref
  558. $listoffiles = dol_dir_list($conf->bom->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  559. foreach ($listoffiles as $fileentry) {
  560. $dirsource = $fileentry['name'];
  561. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  562. $dirsource = $fileentry['path'].'/'.$dirsource;
  563. $dirdest = $fileentry['path'].'/'.$dirdest;
  564. @rename($dirsource, $dirdest);
  565. }
  566. }
  567. }
  568. }
  569. }
  570. // Set new ref and current status
  571. if (!$error) {
  572. $this->ref = $num;
  573. $this->status = self::STATUS_VALIDATED;
  574. }
  575. if (!$error) {
  576. $this->db->commit();
  577. return 1;
  578. } else {
  579. $this->db->rollback();
  580. return -1;
  581. }
  582. }
  583. /**
  584. * Set draft status
  585. *
  586. * @param User $user Object user that modify
  587. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  588. * @return int <0 if KO, >0 if OK
  589. */
  590. public function setDraft($user, $notrigger = 0)
  591. {
  592. // Protection
  593. if ($this->status <= self::STATUS_DRAFT) {
  594. return 0;
  595. }
  596. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
  597. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  598. {
  599. $this->error='Permission denied';
  600. return -1;
  601. }*/
  602. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'BOM_UNVALIDATE');
  603. }
  604. /**
  605. * Set cancel status
  606. *
  607. * @param User $user Object user that modify
  608. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  609. * @return int <0 if KO, 0=Nothing done, >0 if OK
  610. */
  611. public function cancel($user, $notrigger = 0)
  612. {
  613. // Protection
  614. if ($this->status != self::STATUS_VALIDATED) {
  615. return 0;
  616. }
  617. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
  618. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  619. {
  620. $this->error='Permission denied';
  621. return -1;
  622. }*/
  623. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'BOM_CLOSE');
  624. }
  625. /**
  626. * Set cancel status
  627. *
  628. * @param User $user Object user that modify
  629. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  630. * @return int <0 if KO, 0=Nothing done, >0 if OK
  631. */
  632. public function reopen($user, $notrigger = 0)
  633. {
  634. // Protection
  635. if ($this->status != self::STATUS_CANCELED) {
  636. return 0;
  637. }
  638. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->write))
  639. || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->bom->bom_advance->validate))))
  640. {
  641. $this->error='Permission denied';
  642. return -1;
  643. }*/
  644. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'BOM_REOPEN');
  645. }
  646. /**
  647. * Return a link to the object card (with optionaly the picto)
  648. *
  649. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  650. * @param string $option On what the link point to ('nolink', ...)
  651. * @param int $notooltip 1=Disable tooltip
  652. * @param string $morecss Add more css on link
  653. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  654. * @return string String with URL
  655. */
  656. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  657. {
  658. global $db, $conf, $langs, $hookmanager;
  659. if (!empty($conf->dol_no_mouse_hover)) {
  660. $notooltip = 1; // Force disable tooltips
  661. }
  662. $result = '';
  663. $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("BillOfMaterials").'</u>';
  664. if (isset($this->status)) {
  665. $label .= ' '.$this->getLibStatut(5);
  666. }
  667. $label .= '<br>';
  668. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  669. if (isset($this->label)) {
  670. $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
  671. }
  672. if (!empty($this->fk_product) && $this->fk_product > 0) {
  673. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  674. $product = new Product($db);
  675. $resultFetch = $product->fetch($this->fk_product);
  676. if ($resultFetch > 0) {
  677. $label .= "<br><b>".$langs->trans("Product").'</b>: '.$product->ref.' - '.$product->label;
  678. }
  679. }
  680. $url = DOL_URL_ROOT.'/bom/bom_card.php?id='.$this->id;
  681. if ($option != 'nolink') {
  682. // Add param to save lastsearch_values or not
  683. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  684. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  685. $add_save_lastsearch_values = 1;
  686. }
  687. if ($add_save_lastsearch_values) {
  688. $url .= '&save_lastsearch_values=1';
  689. }
  690. }
  691. $linkclose = '';
  692. if (empty($notooltip)) {
  693. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  694. $label = $langs->trans("ShowBillOfMaterials");
  695. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  696. }
  697. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  698. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  699. /*
  700. $hookmanager->initHooks(array('bomdao'));
  701. $parameters=array('id'=>$this->id);
  702. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  703. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  704. */
  705. } else {
  706. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  707. }
  708. $linkstart = '<a href="'.$url.'"';
  709. $linkstart .= $linkclose.'>';
  710. $linkend = '</a>';
  711. $result .= $linkstart;
  712. if ($withpicto) {
  713. $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);
  714. }
  715. if ($withpicto != 2) {
  716. $result .= $this->ref;
  717. }
  718. $result .= $linkend;
  719. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  720. global $action, $hookmanager;
  721. $hookmanager->initHooks(array('bomdao'));
  722. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  723. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  724. if ($reshook > 0) {
  725. $result = $hookmanager->resPrint;
  726. } else {
  727. $result .= $hookmanager->resPrint;
  728. }
  729. return $result;
  730. }
  731. /**
  732. * Return label of the status
  733. *
  734. * @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
  735. * @return string Label of status
  736. */
  737. public function getLibStatut($mode = 0)
  738. {
  739. return $this->LibStatut($this->status, $mode);
  740. }
  741. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  742. /**
  743. * Return the status
  744. *
  745. * @param int $status Id status
  746. * @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
  747. * @return string Label of status
  748. */
  749. public function LibStatut($status, $mode = 0)
  750. {
  751. // phpcs:enable
  752. if (empty($this->labelStatus)) {
  753. global $langs;
  754. //$langs->load("mrp");
  755. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  756. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  757. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  758. }
  759. $statusType = 'status'.$status;
  760. if ($status == self::STATUS_VALIDATED) {
  761. $statusType = 'status4';
  762. }
  763. if ($status == self::STATUS_CANCELED) {
  764. $statusType = 'status6';
  765. }
  766. return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode);
  767. }
  768. /**
  769. * Load the info information in the object
  770. *
  771. * @param int $id Id of object
  772. * @return void
  773. */
  774. public function info($id)
  775. {
  776. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  777. $sql .= ' fk_user_creat, fk_user_modif';
  778. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  779. $sql .= ' WHERE t.rowid = '.((int) $id);
  780. $result = $this->db->query($sql);
  781. if ($result) {
  782. if ($this->db->num_rows($result)) {
  783. $obj = $this->db->fetch_object($result);
  784. $this->id = $obj->rowid;
  785. if (!empty($obj->fk_user_author)) {
  786. $cuser = new User($this->db);
  787. $cuser->fetch($obj->fk_user_author);
  788. $this->user_creation = $cuser;
  789. }
  790. if (!empty($obj->fk_user_valid)) {
  791. $vuser = new User($this->db);
  792. $vuser->fetch($obj->fk_user_valid);
  793. $this->user_validation = $vuser;
  794. }
  795. if (!empty($obj->fk_user_cloture)) {
  796. $cluser = new User($this->db);
  797. $cluser->fetch($obj->fk_user_cloture);
  798. $this->user_cloture = $cluser;
  799. }
  800. $this->date_creation = $this->db->jdate($obj->datec);
  801. $this->date_modification = !empty($obj->datem) ? $this->db->jdate($obj->datem) : "";
  802. $this->date_validation = !empty($obj->datev) ? $this->db->jdate($obj->datev) : "";
  803. }
  804. $this->db->free($result);
  805. } else {
  806. dol_print_error($this->db);
  807. }
  808. }
  809. /**
  810. * Create an array of lines
  811. *
  812. * @return array|int array of lines if OK, <0 if KO
  813. */
  814. public function getLinesArray()
  815. {
  816. $this->lines = array();
  817. $objectline = new BOMLine($this->db);
  818. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.((int) $this->id)));
  819. if (is_numeric($result)) {
  820. $this->error = $this->error;
  821. $this->errors = $this->errors;
  822. return $result;
  823. } else {
  824. $this->lines = $result;
  825. return $this->lines;
  826. }
  827. }
  828. /**
  829. * Create a document onto disk according to template module.
  830. *
  831. * @param string $modele Force template to use ('' to not force)
  832. * @param Translate $outputlangs objet lang a utiliser pour traduction
  833. * @param int $hidedetails Hide details of lines
  834. * @param int $hidedesc Hide description
  835. * @param int $hideref Hide ref
  836. * @param null|array $moreparams Array to provide more information
  837. * @return int 0 if KO, 1 if OK
  838. */
  839. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  840. {
  841. global $conf, $langs;
  842. $langs->load("mrp");
  843. $outputlangs->load("products");
  844. if (!dol_strlen($modele)) {
  845. $modele = 'standard';
  846. if ($this->model_pdf) {
  847. $modele = $this->model_pdf;
  848. } elseif (!empty($conf->global->BOM_ADDON_PDF)) {
  849. $modele = $conf->global->BOM_ADDON_PDF;
  850. }
  851. }
  852. $modelpath = "core/modules/bom/doc/";
  853. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  854. }
  855. /**
  856. * Initialise object with example values
  857. * Id must be 0 if object instance is a specimen
  858. *
  859. * @return void
  860. */
  861. public function initAsSpecimen()
  862. {
  863. $this->initAsSpecimenCommon();
  864. $this->ref = 'BOM-123';
  865. $this->date = $this->date_creation;
  866. }
  867. /**
  868. * Action executed by scheduler
  869. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  870. *
  871. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  872. */
  873. public function doScheduledJob()
  874. {
  875. global $conf, $langs;
  876. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  877. $error = 0;
  878. $this->output = '';
  879. $this->error = '';
  880. dol_syslog(__METHOD__, LOG_DEBUG);
  881. $now = dol_now();
  882. $this->db->begin();
  883. // ...
  884. $this->db->commit();
  885. return $error;
  886. }
  887. /**
  888. * BOM costs calculation based on cost_price or pmp of each BOM line.
  889. * Set the property ->total_cost and ->unit_cost of BOM.
  890. *
  891. * @return void
  892. */
  893. public function calculateCosts()
  894. {
  895. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  896. $this->unit_cost = 0;
  897. $this->total_cost = 0;
  898. if (is_array($this->lines) && count($this->lines)) {
  899. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  900. $productFournisseur = new ProductFournisseur($this->db);
  901. $tmpproduct = new Product($this->db);
  902. foreach ($this->lines as &$line) {
  903. $tmpproduct->cost_price = 0;
  904. $tmpproduct->pmp = 0;
  905. if (empty($line->fk_bom_child)) {
  906. $result = $tmpproduct->fetch($line->fk_product, '', '', '', 0, 1, 1); // We discard selling price and language loading
  907. if ($result < 0) {
  908. $this->error = $tmpproduct->error;
  909. return -1;
  910. }
  911. $line->unit_cost = price2num((!empty($tmpproduct->cost_price)) ? $tmpproduct->cost_price : $tmpproduct->pmp);
  912. if (empty($line->unit_cost)) {
  913. if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) {
  914. $line->unit_cost = $productFournisseur->fourn_unitprice;
  915. }
  916. }
  917. $line->total_cost = price2num($line->qty * $line->unit_cost, 'MT');
  918. $this->total_cost += $line->total_cost;
  919. } else {
  920. $bom_child= new BOM($this->db);
  921. $res = $bom_child->fetch($line->fk_bom_child);
  922. if ($res>0) {
  923. $bom_child->calculateCosts();
  924. $line->childBom[] = $bom_child;
  925. $this->total_cost += $bom_child->total_cost * $line->qty;
  926. } else {
  927. $this->error = $bom_child->error;
  928. return -2;
  929. }
  930. }
  931. }
  932. $this->total_cost = price2num($this->total_cost, 'MT');
  933. if ($this->qty > 0) {
  934. $this->unit_cost = price2num($this->total_cost / $this->qty, 'MU');
  935. } elseif ($this->qty < 0) {
  936. $this->unit_cost = price2num($this->total_cost * $this->qty, 'MU');
  937. }
  938. }
  939. }
  940. /**
  941. * Function used to replace a product id with another one.
  942. *
  943. * @param DoliDB $db Database handler
  944. * @param int $origin_id Old product id
  945. * @param int $dest_id New product id
  946. * @return bool
  947. */
  948. public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
  949. {
  950. $tables = array(
  951. 'bom_bomline'
  952. );
  953. return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
  954. }
  955. /**
  956. * Get Net needs by product
  957. *
  958. * @param array $TNetNeeds Array of ChildBom and infos linked to
  959. * @param int $qty qty needed
  960. * @return void
  961. */
  962. public function getNetNeeds(&$TNetNeeds = array(), $qty = 0)
  963. {
  964. if (! empty($this->lines)) {
  965. foreach ($this->lines as $line) {
  966. if (! empty($line->childBom)) {
  967. foreach ($line->childBom as $childBom) $childBom->getNetNeeds($TNetNeeds, $line->qty*$qty);
  968. } else {
  969. if (empty($TNetNeeds[$line->fk_product])) {
  970. $TNetNeeds[$line->fk_product] = 0;
  971. }
  972. $TNetNeeds[$line->fk_product] += $line->qty*$qty;
  973. }
  974. }
  975. }
  976. }
  977. /**
  978. * Get Net needs Tree by product or bom
  979. *
  980. * @param array $TNetNeeds Array of ChildBom and infos linked to
  981. * @param int $qty qty needed
  982. * @param int $level level of recursivity
  983. * @return void
  984. */
  985. public function getNetNeedsTree(&$TNetNeeds = array(), $qty = 0, $level = 0)
  986. {
  987. if (! empty($this->lines)) {
  988. foreach ($this->lines as $line) {
  989. if (! empty($line->childBom)) {
  990. foreach ($line->childBom as $childBom) {
  991. $TNetNeeds[$childBom->id]['bom'] = $childBom;
  992. $TNetNeeds[$childBom->id]['parentid'] = $this->id;
  993. $TNetNeeds[$childBom->id]['qty'] = $line->qty*$qty;
  994. $TNetNeeds[$childBom->id]['level'] = $level;
  995. $childBom->getNetNeedsTree($TNetNeeds, $line->qty*$qty, $level+1);
  996. }
  997. } else {
  998. $TNetNeeds[$this->id]['product'][$line->fk_product]['qty'] += $line->qty * $qty;
  999. $TNetNeeds[$this->id]['product'][$line->fk_product]['level'] = $level;
  1000. }
  1001. }
  1002. }
  1003. }
  1004. }
  1005. /**
  1006. * Class for BOMLine
  1007. */
  1008. class BOMLine extends CommonObjectLine
  1009. {
  1010. /**
  1011. * @var string ID to identify managed object
  1012. */
  1013. public $element = 'bomline';
  1014. /**
  1015. * @var string Name of table without prefix where object is stored
  1016. */
  1017. public $table_element = 'bom_bomline';
  1018. /**
  1019. * @var int Does bomline support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  1020. */
  1021. public $ismultientitymanaged = 0;
  1022. /**
  1023. * @var int Does bomline support extrafields ? 0=No, 1=Yes
  1024. */
  1025. public $isextrafieldmanaged = 1;
  1026. /**
  1027. * @var string String with name of icon for bomline. Must be the part after the 'object_' into object_bomline.png
  1028. */
  1029. public $picto = 'bomline';
  1030. /**
  1031. * 'type' if the field format.
  1032. * 'label' the translation key.
  1033. * 'enabled' is a condition when the field must be managed.
  1034. * '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)
  1035. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  1036. * 'default' is a default value for creation (can still be replaced by the global setup of default values)
  1037. * 'index' if we want an index in database.
  1038. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  1039. * 'position' is the sort order of field.
  1040. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  1041. * '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).
  1042. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  1043. * 'help' is a string visible as a tooltip on field
  1044. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  1045. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  1046. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  1047. */
  1048. // BEGIN MODULEBUILDER PROPERTIES
  1049. /**
  1050. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  1051. */
  1052. public $fields = array(
  1053. 'rowid' => array('type'=>'integer', 'label'=>'LineID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
  1054. 'fk_bom' => array('type'=>'integer:BillOfMaterials:societe/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1,),
  1055. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
  1056. 'fk_bom_child' => array('type'=>'integer:BOM:bom/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>-1, 'position'=>40, 'notnull'=>-1,),
  1057. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,),
  1058. 'qty' => array('type'=>'double(24,8)', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'notnull'=>1, 'isameasure'=>'1',),
  1059. 'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
  1060. 'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
  1061. 'efficiency' => array('type'=>'double(24,8)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfEfficiencyConsumedMeans'),
  1062. 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,),
  1063. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
  1064. );
  1065. /**
  1066. * @var int rowid
  1067. */
  1068. public $rowid;
  1069. /**
  1070. * @var int fk_bom
  1071. */
  1072. public $fk_bom;
  1073. /**
  1074. * @var int Id of product
  1075. */
  1076. public $fk_product;
  1077. /**
  1078. * @var int Id of parent bom
  1079. */
  1080. public $fk_bom_child;
  1081. /**
  1082. * @var string description
  1083. */
  1084. public $description;
  1085. public $qty;
  1086. /**
  1087. * @var int qty frozen
  1088. */
  1089. public $qty_frozen;
  1090. public $disable_stock_change;
  1091. public $efficiency;
  1092. /**
  1093. * @var int position of line
  1094. */
  1095. public $position;
  1096. /**
  1097. * @var string import key
  1098. */
  1099. public $import_key;
  1100. // END MODULEBUILDER PROPERTIES
  1101. /**
  1102. * @var int Calculated cost for the BOM line
  1103. */
  1104. public $total_cost = 0;
  1105. /**
  1106. * @var int Line unit cost based on product cost price or pmp
  1107. */
  1108. public $unit_cost = 0;
  1109. /**
  1110. * @var Bom array of Bom in line
  1111. */
  1112. public $childBom = array();
  1113. /**
  1114. * Constructor
  1115. *
  1116. * @param DoliDb $db Database handler
  1117. */
  1118. public function __construct(DoliDB $db)
  1119. {
  1120. global $conf, $langs;
  1121. $this->db = $db;
  1122. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  1123. $this->fields['rowid']['visible'] = 0;
  1124. }
  1125. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  1126. $this->fields['entity']['enabled'] = 0;
  1127. }
  1128. // Unset fields that are disabled
  1129. foreach ($this->fields as $key => $val) {
  1130. if (isset($val['enabled']) && empty($val['enabled'])) {
  1131. unset($this->fields[$key]);
  1132. }
  1133. }
  1134. // Translate some data of arrayofkeyval
  1135. foreach ($this->fields as $key => $val) {
  1136. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  1137. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  1138. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. /**
  1144. * Create object into database
  1145. *
  1146. * @param User $user User that creates
  1147. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1148. * @return int <0 if KO, Id of created object if OK
  1149. */
  1150. public function create(User $user, $notrigger = false)
  1151. {
  1152. if ($this->efficiency < 0 || $this->efficiency > 1) {
  1153. $this->efficiency = 1;
  1154. }
  1155. return $this->createCommon($user, $notrigger);
  1156. }
  1157. /**
  1158. * Load object in memory from the database
  1159. *
  1160. * @param int $id Id object
  1161. * @param string $ref Ref
  1162. * @return int <0 if KO, 0 if not found, >0 if OK
  1163. */
  1164. public function fetch($id, $ref = null)
  1165. {
  1166. $result = $this->fetchCommon($id, $ref);
  1167. //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
  1168. return $result;
  1169. }
  1170. /**
  1171. * Load list of objects in memory from the database.
  1172. *
  1173. * @param string $sortorder Sort Order
  1174. * @param string $sortfield Sort field
  1175. * @param int $limit limit
  1176. * @param int $offset Offset
  1177. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  1178. * @param string $filtermode Filter mode (AND or OR)
  1179. * @return array|int int <0 if KO, array of pages if OK
  1180. */
  1181. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  1182. {
  1183. global $conf;
  1184. dol_syslog(__METHOD__, LOG_DEBUG);
  1185. $records = array();
  1186. $sql = 'SELECT ';
  1187. $sql .= $this->getFieldList();
  1188. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1189. if ($this->ismultientitymanaged) {
  1190. $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
  1191. } else {
  1192. $sql .= ' WHERE 1 = 1';
  1193. }
  1194. // Manage filter
  1195. $sqlwhere = array();
  1196. if (count($filter) > 0) {
  1197. foreach ($filter as $key => $value) {
  1198. if ($key == 't.rowid') {
  1199. $sqlwhere[] = $key." = ".((int) $value);
  1200. } elseif (strpos($key, 'date') !== false) {
  1201. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  1202. } elseif ($key == 'customsql') {
  1203. $sqlwhere[] = $value;
  1204. } else {
  1205. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  1206. }
  1207. }
  1208. }
  1209. if (count($sqlwhere) > 0) {
  1210. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  1211. }
  1212. if (!empty($sortfield)) {
  1213. $sql .= $this->db->order($sortfield, $sortorder);
  1214. }
  1215. if (!empty($limit)) {
  1216. $sql .= $this->db->plimit($limit, $offset);
  1217. }
  1218. $resql = $this->db->query($sql);
  1219. if ($resql) {
  1220. $num = $this->db->num_rows($resql);
  1221. while ($obj = $this->db->fetch_object($resql)) {
  1222. $record = new self($this->db);
  1223. $record->setVarsFromFetchObj($obj);
  1224. $records[$record->id] = $record;
  1225. }
  1226. $this->db->free($resql);
  1227. return $records;
  1228. } else {
  1229. $this->errors[] = 'Error '.$this->db->lasterror();
  1230. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1231. return -1;
  1232. }
  1233. }
  1234. /**
  1235. * Update object into database
  1236. *
  1237. * @param User $user User that modifies
  1238. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1239. * @return int <0 if KO, >0 if OK
  1240. */
  1241. public function update(User $user, $notrigger = false)
  1242. {
  1243. if ($this->efficiency < 0 || $this->efficiency > 1) {
  1244. $this->efficiency = 1;
  1245. }
  1246. return $this->updateCommon($user, $notrigger);
  1247. }
  1248. /**
  1249. * Delete object in database
  1250. *
  1251. * @param User $user User that deletes
  1252. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1253. * @return int <0 if KO, >0 if OK
  1254. */
  1255. public function delete(User $user, $notrigger = false)
  1256. {
  1257. return $this->deleteCommon($user, $notrigger);
  1258. //return $this->deleteCommon($user, $notrigger, 1);
  1259. }
  1260. /**
  1261. * Return a link to the object card (with optionaly the picto)
  1262. *
  1263. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1264. * @param string $option On what the link point to ('nolink', ...)
  1265. * @param int $notooltip 1=Disable tooltip
  1266. * @param string $morecss Add more css on link
  1267. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1268. * @return string String with URL
  1269. */
  1270. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1271. {
  1272. global $db, $conf, $langs, $hookmanager;
  1273. if (!empty($conf->dol_no_mouse_hover)) {
  1274. $notooltip = 1; // Force disable tooltips
  1275. }
  1276. $result = '';
  1277. $label = '<u>'.$langs->trans("BillOfMaterialsLine").'</u>';
  1278. $label .= '<br>';
  1279. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1280. $url = DOL_URL_ROOT.'/bom/bomline_card.php?id='.$this->id;
  1281. if ($option != 'nolink') {
  1282. // Add param to save lastsearch_values or not
  1283. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1284. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1285. $add_save_lastsearch_values = 1;
  1286. }
  1287. if ($add_save_lastsearch_values) {
  1288. $url .= '&save_lastsearch_values=1';
  1289. }
  1290. }
  1291. $linkclose = '';
  1292. if (empty($notooltip)) {
  1293. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1294. $label = $langs->trans("ShowBillOfMaterialsLine");
  1295. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1296. }
  1297. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1298. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1299. /*
  1300. $hookmanager->initHooks(array('bomlinedao'));
  1301. $parameters=array('id'=>$this->id);
  1302. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1303. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  1304. */
  1305. } else {
  1306. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1307. }
  1308. $linkstart = '<a href="'.$url.'"';
  1309. $linkstart .= $linkclose.'>';
  1310. $linkend = '</a>';
  1311. $result .= $linkstart;
  1312. if ($withpicto) {
  1313. $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);
  1314. }
  1315. if ($withpicto != 2) {
  1316. $result .= $this->ref;
  1317. }
  1318. $result .= $linkend;
  1319. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1320. global $action, $hookmanager;
  1321. $hookmanager->initHooks(array('bomlinedao'));
  1322. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1323. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1324. if ($reshook > 0) {
  1325. $result = $hookmanager->resPrint;
  1326. } else {
  1327. $result .= $hookmanager->resPrint;
  1328. }
  1329. return $result;
  1330. }
  1331. /**
  1332. * Return label of the status
  1333. *
  1334. * @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
  1335. * @return string Label of status
  1336. */
  1337. public function getLibStatut($mode = 0)
  1338. {
  1339. return $this->LibStatut($this->status, $mode);
  1340. }
  1341. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1342. /**
  1343. * Return the status
  1344. *
  1345. * @param int $status Id status
  1346. * @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
  1347. * @return string Label of status
  1348. */
  1349. public function LibStatut($status, $mode = 0)
  1350. {
  1351. // phpcs:enable
  1352. return '';
  1353. }
  1354. /**
  1355. * Load the info information in the object
  1356. *
  1357. * @param int $id Id of object
  1358. * @return void
  1359. */
  1360. public function info($id)
  1361. {
  1362. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  1363. $sql .= ' fk_user_creat, fk_user_modif';
  1364. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1365. $sql .= ' WHERE t.rowid = '.((int) $id);
  1366. $result = $this->db->query($sql);
  1367. if ($result) {
  1368. if ($this->db->num_rows($result)) {
  1369. $obj = $this->db->fetch_object($result);
  1370. $this->id = $obj->rowid;
  1371. if ($obj->fk_user_author) {
  1372. $cuser = new User($this->db);
  1373. $cuser->fetch($obj->fk_user_author);
  1374. $this->user_creation = $cuser;
  1375. }
  1376. if ($obj->fk_user_valid) {
  1377. $vuser = new User($this->db);
  1378. $vuser->fetch($obj->fk_user_valid);
  1379. $this->user_validation = $vuser;
  1380. }
  1381. if ($obj->fk_user_cloture) {
  1382. $cluser = new User($this->db);
  1383. $cluser->fetch($obj->fk_user_cloture);
  1384. $this->user_cloture = $cluser;
  1385. }
  1386. $this->date_creation = $this->db->jdate($obj->datec);
  1387. $this->date_modification = $this->db->jdate($obj->datem);
  1388. $this->date_validation = $this->db->jdate($obj->datev);
  1389. }
  1390. $this->db->free($result);
  1391. } else {
  1392. dol_print_error($this->db);
  1393. }
  1394. }
  1395. /**
  1396. * Initialise object with example values
  1397. * Id must be 0 if object instance is a specimen
  1398. *
  1399. * @return void
  1400. */
  1401. public function initAsSpecimen()
  1402. {
  1403. $this->initAsSpecimenCommon();
  1404. }
  1405. }