bom.class.php 64 KB

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