bom.class.php 50 KB

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