bom.class.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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: 'maxwidth200', 'wordbreak', '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'=>'maxwidth300', '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)) {
  673. $product = new Product($db);
  674. $resultFetch = $product->fetch($this->fk_product);
  675. if ($resultFetch < 0) {
  676. setEventMessages($product->error, $product->errors, 'errors');
  677. } else {
  678. $label .= "<br><b>".$langs->trans("Product").'</b>: '.$product->getNomUrl(0,'',0,-1,1);
  679. }
  680. }
  681. $url = DOL_URL_ROOT.'/bom/bom_card.php?id='.$this->id;
  682. if ($option != 'nolink') {
  683. // Add param to save lastsearch_values or not
  684. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  685. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  686. $add_save_lastsearch_values = 1;
  687. }
  688. if ($add_save_lastsearch_values) {
  689. $url .= '&save_lastsearch_values=1';
  690. }
  691. }
  692. $linkclose = '';
  693. if (empty($notooltip)) {
  694. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  695. $label = $langs->trans("ShowBillOfMaterials");
  696. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  697. }
  698. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  699. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  700. /*
  701. $hookmanager->initHooks(array('bomdao'));
  702. $parameters=array('id'=>$this->id);
  703. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  704. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  705. */
  706. } else {
  707. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  708. }
  709. $linkstart = '<a href="'.$url.'"';
  710. $linkstart .= $linkclose.'>';
  711. $linkend = '</a>';
  712. $result .= $linkstart;
  713. if ($withpicto) {
  714. $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);
  715. }
  716. if ($withpicto != 2) {
  717. $result .= $this->ref;
  718. }
  719. $result .= $linkend;
  720. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  721. global $action, $hookmanager;
  722. $hookmanager->initHooks(array('bomdao'));
  723. $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
  724. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  725. if ($reshook > 0) {
  726. $result = $hookmanager->resPrint;
  727. } else {
  728. $result .= $hookmanager->resPrint;
  729. }
  730. return $result;
  731. }
  732. /**
  733. * Return label of the status
  734. *
  735. * @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
  736. * @return string Label of status
  737. */
  738. public function getLibStatut($mode = 0)
  739. {
  740. return $this->LibStatut($this->status, $mode);
  741. }
  742. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  743. /**
  744. * Return the status
  745. *
  746. * @param int $status Id status
  747. * @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
  748. * @return string Label of status
  749. */
  750. public function LibStatut($status, $mode = 0)
  751. {
  752. // phpcs:enable
  753. if (empty($this->labelStatus)) {
  754. global $langs;
  755. //$langs->load("mrp");
  756. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  757. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  758. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  759. }
  760. $statusType = 'status'.$status;
  761. if ($status == self::STATUS_VALIDATED) {
  762. $statusType = 'status4';
  763. }
  764. if ($status == self::STATUS_CANCELED) {
  765. $statusType = 'status6';
  766. }
  767. return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode);
  768. }
  769. /**
  770. * Load the info information in the object
  771. *
  772. * @param int $id Id of object
  773. * @return void
  774. */
  775. public function info($id)
  776. {
  777. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  778. $sql .= ' fk_user_creat, fk_user_modif';
  779. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  780. $sql .= ' WHERE t.rowid = '.((int) $id);
  781. $result = $this->db->query($sql);
  782. if ($result) {
  783. if ($this->db->num_rows($result)) {
  784. $obj = $this->db->fetch_object($result);
  785. $this->id = $obj->rowid;
  786. if ($obj->fk_user_author) {
  787. $cuser = new User($this->db);
  788. $cuser->fetch($obj->fk_user_author);
  789. $this->user_creation = $cuser;
  790. }
  791. if ($obj->fk_user_valid) {
  792. $vuser = new User($this->db);
  793. $vuser->fetch($obj->fk_user_valid);
  794. $this->user_validation = $vuser;
  795. }
  796. if ($obj->fk_user_cloture) {
  797. $cluser = new User($this->db);
  798. $cluser->fetch($obj->fk_user_cloture);
  799. $this->user_cloture = $cluser;
  800. }
  801. $this->date_creation = $this->db->jdate($obj->datec);
  802. $this->date_modification = $this->db->jdate($obj->datem);
  803. $this->date_validation = $this->db->jdate($obj->datev);
  804. }
  805. $this->db->free($result);
  806. } else {
  807. dol_print_error($this->db);
  808. }
  809. }
  810. /**
  811. * Create an array of lines
  812. *
  813. * @return array|int array of lines if OK, <0 if KO
  814. */
  815. public function getLinesArray()
  816. {
  817. $this->lines = array();
  818. $objectline = new BOMLine($this->db);
  819. $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_bom = '.((int) $this->id)));
  820. if (is_numeric($result)) {
  821. $this->error = $this->error;
  822. $this->errors = $this->errors;
  823. return $result;
  824. } else {
  825. $this->lines = $result;
  826. return $this->lines;
  827. }
  828. }
  829. /**
  830. * Create a document onto disk according to template module.
  831. *
  832. * @param string $modele Force template to use ('' to not force)
  833. * @param Translate $outputlangs objet lang a utiliser pour traduction
  834. * @param int $hidedetails Hide details of lines
  835. * @param int $hidedesc Hide description
  836. * @param int $hideref Hide ref
  837. * @param null|array $moreparams Array to provide more information
  838. * @return int 0 if KO, 1 if OK
  839. */
  840. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  841. {
  842. global $conf, $langs;
  843. $langs->load("mrp");
  844. $outputlangs->load("products");
  845. if (!dol_strlen($modele)) {
  846. $modele = 'standard';
  847. if ($this->model_pdf) {
  848. $modele = $this->model_pdf;
  849. } elseif (!empty($conf->global->BOM_ADDON_PDF)) {
  850. $modele = $conf->global->BOM_ADDON_PDF;
  851. }
  852. }
  853. $modelpath = "core/modules/bom/doc/";
  854. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  855. }
  856. /**
  857. * Initialise object with example values
  858. * Id must be 0 if object instance is a specimen
  859. *
  860. * @return void
  861. */
  862. public function initAsSpecimen()
  863. {
  864. $this->initAsSpecimenCommon();
  865. $this->ref = 'BOM-123';
  866. $this->date = $this->date_creation;
  867. }
  868. /**
  869. * Action executed by scheduler
  870. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  871. *
  872. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  873. */
  874. public function doScheduledJob()
  875. {
  876. global $conf, $langs;
  877. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  878. $error = 0;
  879. $this->output = '';
  880. $this->error = '';
  881. dol_syslog(__METHOD__, LOG_DEBUG);
  882. $now = dol_now();
  883. $this->db->begin();
  884. // ...
  885. $this->db->commit();
  886. return $error;
  887. }
  888. /**
  889. * BOM costs calculation based on cost_price or pmp of each BOM line.
  890. * Set the property ->total_cost and ->unit_cost of BOM.
  891. *
  892. * @return void
  893. */
  894. public function calculateCosts()
  895. {
  896. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  897. $this->unit_cost = 0;
  898. $this->total_cost = 0;
  899. if (is_array($this->lines) && count($this->lines)) {
  900. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  901. $productFournisseur = new ProductFournisseur($this->db);
  902. $tmpproduct = new Product($this->db);
  903. foreach ($this->lines as &$line) {
  904. $tmpproduct->cost_price = 0;
  905. $tmpproduct->pmp = 0;
  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. }
  920. $this->total_cost = price2num($this->total_cost, 'MT');
  921. if ($this->qty) {
  922. $this->unit_cost = price2num($this->total_cost / $this->qty, 'MU');
  923. }
  924. }
  925. }
  926. }
  927. /**
  928. * Class for BOMLine
  929. */
  930. class BOMLine extends CommonObjectLine
  931. {
  932. /**
  933. * @var string ID to identify managed object
  934. */
  935. public $element = 'bomline';
  936. /**
  937. * @var string Name of table without prefix where object is stored
  938. */
  939. public $table_element = 'bom_bomline';
  940. /**
  941. * @var int Does bomline support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  942. */
  943. public $ismultientitymanaged = 0;
  944. /**
  945. * @var int Does bomline support extrafields ? 0=No, 1=Yes
  946. */
  947. public $isextrafieldmanaged = 1;
  948. /**
  949. * @var string String with name of icon for bomline. Must be the part after the 'object_' into object_bomline.png
  950. */
  951. public $picto = 'bomline';
  952. /**
  953. * 'type' if the field format.
  954. * 'label' the translation key.
  955. * 'enabled' is a condition when the field must be managed.
  956. * '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)
  957. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  958. * 'default' is a default value for creation (can still be replaced by the global setup of default values)
  959. * 'index' if we want an index in database.
  960. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  961. * 'position' is the sort order of field.
  962. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  963. * '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).
  964. * 'css' is the CSS style to use on field. For example: 'maxwidth200'
  965. * 'help' is a string visible as a tooltip on field
  966. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  967. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  968. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  969. */
  970. // BEGIN MODULEBUILDER PROPERTIES
  971. /**
  972. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  973. */
  974. public $fields = array(
  975. 'rowid' => array('type'=>'integer', 'label'=>'LineID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
  976. 'fk_bom' => array('type'=>'integer:BillOfMaterials:societe/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1,),
  977. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
  978. 'fk_bom_child' => array('type'=>'integer:BOM:bom/class/bom.class.php', 'label'=>'BillOfMaterials', 'enabled'=>1, 'visible'=>-1, 'position'=>40, 'notnull'=>-1,),
  979. 'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-1, 'position'=>60, 'notnull'=>-1,),
  980. 'qty' => array('type'=>'double(24,8)', 'label'=>'Quantity', 'enabled'=>1, 'visible'=>1, 'position'=>100, 'notnull'=>1, 'isameasure'=>'1',),
  981. 'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
  982. 'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
  983. 'efficiency' => array('type'=>'double(24,8)', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'position'=>110, 'notnull'=>1, 'css'=>'maxwidth50imp', 'help'=>'ValueOfEfficiencyConsumedMeans'),
  984. 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,),
  985. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
  986. );
  987. /**
  988. * @var int rowid
  989. */
  990. public $rowid;
  991. /**
  992. * @var int fk_bom
  993. */
  994. public $fk_bom;
  995. /**
  996. * @var int Id of product
  997. */
  998. public $fk_product;
  999. /**
  1000. * @var int Id of parent bom
  1001. */
  1002. public $fk_bom_child;
  1003. /**
  1004. * @var string description
  1005. */
  1006. public $description;
  1007. public $qty;
  1008. /**
  1009. * @var int qty frozen
  1010. */
  1011. public $qty_frozen;
  1012. public $disable_stock_change;
  1013. public $efficiency;
  1014. /**
  1015. * @var int position of line
  1016. */
  1017. public $position;
  1018. /**
  1019. * @var string import key
  1020. */
  1021. public $import_key;
  1022. // END MODULEBUILDER PROPERTIES
  1023. /**
  1024. * @var int Calculated cost for the BOM line
  1025. */
  1026. public $total_cost = 0;
  1027. /**
  1028. * @var int Line unit cost based on product cost price or pmp
  1029. */
  1030. public $unit_cost = 0;
  1031. /**
  1032. * Constructor
  1033. *
  1034. * @param DoliDb $db Database handler
  1035. */
  1036. public function __construct(DoliDB $db)
  1037. {
  1038. global $conf, $langs;
  1039. $this->db = $db;
  1040. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  1041. $this->fields['rowid']['visible'] = 0;
  1042. }
  1043. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
  1044. $this->fields['entity']['enabled'] = 0;
  1045. }
  1046. // Unset fields that are disabled
  1047. foreach ($this->fields as $key => $val) {
  1048. if (isset($val['enabled']) && empty($val['enabled'])) {
  1049. unset($this->fields[$key]);
  1050. }
  1051. }
  1052. // Translate some data of arrayofkeyval
  1053. foreach ($this->fields as $key => $val) {
  1054. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  1055. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  1056. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  1057. }
  1058. }
  1059. }
  1060. }
  1061. /**
  1062. * Create object into database
  1063. *
  1064. * @param User $user User that creates
  1065. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1066. * @return int <0 if KO, Id of created object if OK
  1067. */
  1068. public function create(User $user, $notrigger = false)
  1069. {
  1070. if ($this->efficiency < 0 || $this->efficiency > 1) {
  1071. $this->efficiency = 1;
  1072. }
  1073. return $this->createCommon($user, $notrigger);
  1074. }
  1075. /**
  1076. * Load object in memory from the database
  1077. *
  1078. * @param int $id Id object
  1079. * @param string $ref Ref
  1080. * @return int <0 if KO, 0 if not found, >0 if OK
  1081. */
  1082. public function fetch($id, $ref = null)
  1083. {
  1084. $result = $this->fetchCommon($id, $ref);
  1085. //if ($result > 0 && ! empty($this->table_element_line)) $this->fetchLines();
  1086. return $result;
  1087. }
  1088. /**
  1089. * Load list of objects in memory from the database.
  1090. *
  1091. * @param string $sortorder Sort Order
  1092. * @param string $sortfield Sort field
  1093. * @param int $limit limit
  1094. * @param int $offset Offset
  1095. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  1096. * @param string $filtermode Filter mode (AND or OR)
  1097. * @return array|int int <0 if KO, array of pages if OK
  1098. */
  1099. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  1100. {
  1101. global $conf;
  1102. dol_syslog(__METHOD__, LOG_DEBUG);
  1103. $records = array();
  1104. $sql = 'SELECT ';
  1105. $sql .= $this->getFieldList();
  1106. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1107. if ($this->ismultientitymanaged) {
  1108. $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
  1109. } else {
  1110. $sql .= ' WHERE 1 = 1';
  1111. }
  1112. // Manage filter
  1113. $sqlwhere = array();
  1114. if (count($filter) > 0) {
  1115. foreach ($filter as $key => $value) {
  1116. if ($key == 't.rowid') {
  1117. $sqlwhere[] = $key." = ".((int) $value);
  1118. } elseif (strpos($key, 'date') !== false) {
  1119. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  1120. } elseif ($key == 'customsql') {
  1121. $sqlwhere[] = $value;
  1122. } else {
  1123. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  1124. }
  1125. }
  1126. }
  1127. if (count($sqlwhere) > 0) {
  1128. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  1129. }
  1130. if (!empty($sortfield)) {
  1131. $sql .= $this->db->order($sortfield, $sortorder);
  1132. }
  1133. if (!empty($limit)) {
  1134. $sql .= $this->db->plimit($limit, $offset);
  1135. }
  1136. $resql = $this->db->query($sql);
  1137. if ($resql) {
  1138. $num = $this->db->num_rows($resql);
  1139. while ($obj = $this->db->fetch_object($resql)) {
  1140. $record = new self($this->db);
  1141. $record->setVarsFromFetchObj($obj);
  1142. $records[$record->id] = $record;
  1143. }
  1144. $this->db->free($resql);
  1145. return $records;
  1146. } else {
  1147. $this->errors[] = 'Error '.$this->db->lasterror();
  1148. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1149. return -1;
  1150. }
  1151. }
  1152. /**
  1153. * Update object into database
  1154. *
  1155. * @param User $user User that modifies
  1156. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1157. * @return int <0 if KO, >0 if OK
  1158. */
  1159. public function update(User $user, $notrigger = false)
  1160. {
  1161. if ($this->efficiency < 0 || $this->efficiency > 1) {
  1162. $this->efficiency = 1;
  1163. }
  1164. return $this->updateCommon($user, $notrigger);
  1165. }
  1166. /**
  1167. * Delete object in database
  1168. *
  1169. * @param User $user User that deletes
  1170. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1171. * @return int <0 if KO, >0 if OK
  1172. */
  1173. public function delete(User $user, $notrigger = false)
  1174. {
  1175. return $this->deleteCommon($user, $notrigger);
  1176. //return $this->deleteCommon($user, $notrigger, 1);
  1177. }
  1178. /**
  1179. * Return a link to the object card (with optionaly the picto)
  1180. *
  1181. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1182. * @param string $option On what the link point to ('nolink', ...)
  1183. * @param int $notooltip 1=Disable tooltip
  1184. * @param string $morecss Add more css on link
  1185. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1186. * @return string String with URL
  1187. */
  1188. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1189. {
  1190. global $db, $conf, $langs, $hookmanager;
  1191. if (!empty($conf->dol_no_mouse_hover)) {
  1192. $notooltip = 1; // Force disable tooltips
  1193. }
  1194. $result = '';
  1195. $label = '<u>'.$langs->trans("BillOfMaterialsLine").'</u>';
  1196. $label .= '<br>';
  1197. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1198. $url = DOL_URL_ROOT.'/bom/bomline_card.php?id='.$this->id;
  1199. if ($option != 'nolink') {
  1200. // Add param to save lastsearch_values or not
  1201. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1202. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1203. $add_save_lastsearch_values = 1;
  1204. }
  1205. if ($add_save_lastsearch_values) {
  1206. $url .= '&save_lastsearch_values=1';
  1207. }
  1208. }
  1209. $linkclose = '';
  1210. if (empty($notooltip)) {
  1211. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1212. $label = $langs->trans("ShowBillOfMaterialsLine");
  1213. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1214. }
  1215. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  1216. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  1217. /*
  1218. $hookmanager->initHooks(array('bomlinedao'));
  1219. $parameters=array('id'=>$this->id);
  1220. $reshook=$hookmanager->executeHooks('getnomurltooltip',$parameters,$this,$action); // Note that $action and $object may have been modified by some hooks
  1221. if ($reshook > 0) $linkclose = $hookmanager->resPrint;
  1222. */
  1223. } else {
  1224. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1225. }
  1226. $linkstart = '<a href="'.$url.'"';
  1227. $linkstart .= $linkclose.'>';
  1228. $linkend = '</a>';
  1229. $result .= $linkstart;
  1230. if ($withpicto) {
  1231. $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);
  1232. }
  1233. if ($withpicto != 2) {
  1234. $result .= $this->ref;
  1235. }
  1236. $result .= $linkend;
  1237. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1238. global $action, $hookmanager;
  1239. $hookmanager->initHooks(array('bomlinedao'));
  1240. $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
  1241. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1242. if ($reshook > 0) {
  1243. $result = $hookmanager->resPrint;
  1244. } else {
  1245. $result .= $hookmanager->resPrint;
  1246. }
  1247. return $result;
  1248. }
  1249. /**
  1250. * Return label of the status
  1251. *
  1252. * @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
  1253. * @return string Label of status
  1254. */
  1255. public function getLibStatut($mode = 0)
  1256. {
  1257. return $this->LibStatut($this->status, $mode);
  1258. }
  1259. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1260. /**
  1261. * Return the status
  1262. *
  1263. * @param int $status Id status
  1264. * @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
  1265. * @return string Label of status
  1266. */
  1267. public function LibStatut($status, $mode = 0)
  1268. {
  1269. // phpcs:enable
  1270. return '';
  1271. }
  1272. /**
  1273. * Load the info information in the object
  1274. *
  1275. * @param int $id Id of object
  1276. * @return void
  1277. */
  1278. public function info($id)
  1279. {
  1280. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  1281. $sql .= ' fk_user_creat, fk_user_modif';
  1282. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1283. $sql .= ' WHERE t.rowid = '.((int) $id);
  1284. $result = $this->db->query($sql);
  1285. if ($result) {
  1286. if ($this->db->num_rows($result)) {
  1287. $obj = $this->db->fetch_object($result);
  1288. $this->id = $obj->rowid;
  1289. if ($obj->fk_user_author) {
  1290. $cuser = new User($this->db);
  1291. $cuser->fetch($obj->fk_user_author);
  1292. $this->user_creation = $cuser;
  1293. }
  1294. if ($obj->fk_user_valid) {
  1295. $vuser = new User($this->db);
  1296. $vuser->fetch($obj->fk_user_valid);
  1297. $this->user_validation = $vuser;
  1298. }
  1299. if ($obj->fk_user_cloture) {
  1300. $cluser = new User($this->db);
  1301. $cluser->fetch($obj->fk_user_cloture);
  1302. $this->user_cloture = $cluser;
  1303. }
  1304. $this->date_creation = $this->db->jdate($obj->datec);
  1305. $this->date_modification = $this->db->jdate($obj->datem);
  1306. $this->date_validation = $this->db->jdate($obj->datev);
  1307. }
  1308. $this->db->free($result);
  1309. } else {
  1310. dol_print_error($this->db);
  1311. }
  1312. }
  1313. /**
  1314. * Initialise object with example values
  1315. * Id must be 0 if object instance is a specimen
  1316. *
  1317. * @return void
  1318. */
  1319. public function initAsSpecimen()
  1320. {
  1321. $this->initAsSpecimenCommon();
  1322. }
  1323. }