bom.class.php 68 KB

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