mo.class.php 65 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2020 Lenin Rivas <lenin@leninrivas.com>
  4. * Copyright (C) 2023 Frédéric France <frederic.france@free.fr>
  5. *
  6. * This program is free software; you can redistribute it and/or modify
  7. * it under the terms of the GNU General Public License as published by
  8. * the Free Software Foundation; either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU General Public License
  17. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * \file class/mo.class.php
  21. * \ingroup mrp
  22. * \brief This file is a CRUD class file for Mo (Create/Read/Update/Delete)
  23. */
  24. // Put here all includes required by your class file
  25. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  27. /**
  28. * Class for Mo
  29. */
  30. class Mo extends CommonObject
  31. {
  32. /**
  33. * @var string ID to identify managed object
  34. */
  35. public $element = 'mo';
  36. /**
  37. * @var string Name of table without prefix where object is stored
  38. */
  39. public $table_element = 'mrp_mo';
  40. /**
  41. * @var int Does mo support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  42. */
  43. public $ismultientitymanaged = 1;
  44. /**
  45. * @var int Does mo support extrafields ? 0=No, 1=Yes
  46. */
  47. public $isextrafieldmanaged = 1;
  48. /**
  49. * @var string String with name of icon for mo. Must be the part after the 'object_' into object_mo.png
  50. */
  51. public $picto = 'mrp';
  52. const STATUS_DRAFT = 0;
  53. const STATUS_VALIDATED = 1; // To produce
  54. const STATUS_INPROGRESS = 2;
  55. const STATUS_PRODUCED = 3;
  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: 'maxwidth200', 'wordbreak', '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. /**
  83. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  84. */
  85. public $fields = array(
  86. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
  87. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1),
  88. 'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>4, 'position'=>10, 'notnull'=>1, 'default'=>'(PROV)', 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'showoncombobox'=>'1', 'noteditable'=>1),
  89. 'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:(t.status:=:1)', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>'$conf->bom->enabled', 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM", 'css'=>'minwidth100 maxwidth500', 'csslist'=>'tdoverflowmax150', 'picto'=>'bom'),
  90. 'mrptype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>1, 'position'=>34, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing', 1=>'Disassemble'), 'css'=>'minwidth150', 'csslist'=>'minwidth150 center'),
  91. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:0', 'label'=>'Product', 'enabled'=>'isModEnabled("product")', 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce", 'css'=>'maxwidth300', 'csslist'=>'tdoverflowmax100', 'picto'=>'product'),
  92. 'qty' => array('type'=>'real', 'label'=>'QtyToProduce', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'notnull'=>1, 'comment'=>"Qty to produce", 'css'=>'width75', 'default'=>1, 'isameasure'=>1),
  93. 'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'showoncombobox'=>'2', 'css'=>'maxwidth300', 'csslist'=>'tdoverflowmax200', 'alwayseditable'=>1),
  94. 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'picto'=>'company', 'enabled'=>'isModEnabled("societe")', 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'css'=>'maxwidth400', 'csslist'=>'tdoverflowmax150'),
  95. 'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Project', 'picto'=>'project', 'enabled'=>'$conf->project->enabled', 'visible'=>-1, 'position'=>51, 'notnull'=>-1, 'index'=>1, 'css'=>'minwidth200 maxwidth400', 'csslist'=>'tdoverflowmax100'),
  96. 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'picto'=>'stock', 'enabled'=>'$conf->stock->enabled', 'visible'=>1, 'position'=>52, 'css'=>'maxwidth400', 'csslist'=>'tdoverflowmax200'),
  97. 'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,),
  98. 'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'notnull'=>-1,),
  99. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,),
  100. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>1,),
  101. 'date_valid' => array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-2, 'position'=>502,),
  102. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>510, 'notnull'=>1, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax100'),
  103. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1, 'csslist'=>'tdoverflowmax100'),
  104. 'date_start_planned' => array('type'=>'datetime', 'label'=>'DateStartPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>55, 'notnull'=>-1, 'index'=>1, 'help'=>'KeepEmptyForAsap', 'alwayseditable'=>1),
  105. 'date_end_planned' => array('type'=>'datetime', 'label'=>'DateEndPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>56, 'notnull'=>-1, 'index'=>1, 'alwayseditable'=>1),
  106. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
  107. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
  108. 'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>2, 'position'=>1000, 'default'=>0, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Draft', '1'=>'Validated', '2'=>'InProgress', '3'=>'StatusMOProduced', '9'=>'Canceled')),
  109. 'fk_parent_line' => array('type'=>'integer:MoLine:mrp/class/mo.class.php', 'label'=>'ParentMo', 'enabled'=>1, 'visible'=>0, 'position'=>1020, 'default'=>0, 'notnull'=>0, 'index'=>1,'showoncombobox'=>0),
  110. );
  111. public $rowid;
  112. public $entity;
  113. public $ref;
  114. /**
  115. * @var int mrptype
  116. */
  117. public $mrptype;
  118. public $label;
  119. public $qty;
  120. public $fk_warehouse;
  121. public $fk_soc;
  122. public $socid;
  123. /**
  124. * @var string public note
  125. */
  126. public $note_public;
  127. /**
  128. * @var string private note
  129. */
  130. public $note_private;
  131. /**
  132. * @var integer|string date_creation
  133. */
  134. public $date_creation;
  135. public $tms;
  136. public $fk_user_creat;
  137. public $fk_user_modif;
  138. public $import_key;
  139. public $status;
  140. /**
  141. * @var int ID of product
  142. */
  143. public $fk_product;
  144. /**
  145. * @var Product product object
  146. */
  147. public $product;
  148. /**
  149. * @var integer|string date_start_planned
  150. */
  151. public $date_start_planned;
  152. /**
  153. * @var integer|string date_end_planned
  154. */
  155. public $date_end_planned;
  156. /**
  157. * @var int ID bom
  158. */
  159. public $fk_bom;
  160. /**
  161. * @var Bom bom
  162. */
  163. public $bom;
  164. /**
  165. * @var int ID project
  166. */
  167. public $fk_project;
  168. // If this object has a subtable with lines
  169. /**
  170. * @var string Name of subtable line
  171. */
  172. public $table_element_line = 'mrp_production';
  173. /**
  174. * @var string Field with ID of parent key if this field has a parent
  175. */
  176. public $fk_element = 'fk_mo';
  177. /**
  178. * @var string Name of subtable class that manage subtable lines
  179. */
  180. public $class_element_line = 'MoLine';
  181. /**
  182. * @var array List of child tables. To test if we can delete object.
  183. */
  184. protected $childtables = array();
  185. /**
  186. * @var array List of child tables. To know object to delete on cascade.
  187. */
  188. protected $childtablesoncascade = array('mrp_production');
  189. /**
  190. * @var MoLine[] Array of subtable lines
  191. */
  192. public $lines = array();
  193. /**
  194. * @var MoLine MO line
  195. */
  196. public $line = array();
  197. /**
  198. * @var int ID of parent line
  199. */
  200. public $fk_parent_line;
  201. /**
  202. * @var array tpl
  203. */
  204. public $tpl = array();
  205. /**
  206. * Constructor
  207. *
  208. * @param DoliDb $db Database handler
  209. */
  210. public function __construct(DoliDB $db)
  211. {
  212. global $conf, $langs;
  213. $this->db = $db;
  214. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  215. $this->fields['rowid']['visible'] = 0;
  216. }
  217. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  218. $this->fields['entity']['enabled'] = 0;
  219. }
  220. // Unset fields that are disabled
  221. foreach ($this->fields as $key => $val) {
  222. if (isset($val['enabled']) && empty($val['enabled'])) {
  223. unset($this->fields[$key]);
  224. }
  225. }
  226. // Translate some data of arrayofkeyval
  227. foreach ($this->fields as $key => $val) {
  228. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  229. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  230. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  231. }
  232. }
  233. }
  234. }
  235. /**
  236. * Create object into database
  237. *
  238. * @param User $user User that creates
  239. * @param bool $notrigger false=launch triggers after, true=disable triggers
  240. * @return int <=0 if KO, Id of created object if OK
  241. */
  242. public function create(User $user, $notrigger = false)
  243. {
  244. $error = 0;
  245. $idcreated = 0;
  246. // If kits feature is enabled and we don't allow kits into BOM and MO, we check that the product is not a kit/virtual product
  247. if (getDolGlobalString('PRODUIT_SOUSPRODUITS') && !getDolGlobalString('ALLOW_USE_KITS_INTO_BOM_AND_MO') && $this->fk_product > 0) {
  248. include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  249. $tmpproduct = new Product($this->db);
  250. $tmpproduct->fetch($this->fk_product);
  251. if ($tmpproduct->hasFatherOrChild(1) > 0) {
  252. $this->error = 'ErrorAVirtualProductCantBeUsedIntoABomOrMo';
  253. $this->errors[] = $this->error;
  254. return -1;
  255. }
  256. }
  257. $this->db->begin();
  258. if ($this->fk_bom > 0) {
  259. // If there is a nown BOM, we force the type of MO to the type of BOM
  260. include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
  261. $tmpbom = new BOM($this->db);
  262. $tmpbom->fetch($this->fk_bom);
  263. $this->mrptype = $tmpbom->bomtype;
  264. }
  265. if (!$error) {
  266. $idcreated = $this->createCommon($user, $notrigger);
  267. if ($idcreated <= 0) {
  268. $error++;
  269. }
  270. }
  271. if (!$error) {
  272. $result = $this->createProduction($user, $notrigger); // Insert lines from BOM
  273. if ($result <= 0) {
  274. $error++;
  275. }
  276. }
  277. if (!$error) {
  278. $this->db->commit();
  279. } else {
  280. $this->db->rollback();
  281. }
  282. return $idcreated;
  283. }
  284. /**
  285. * Clone an object into another one
  286. *
  287. * @param User $user User that creates
  288. * @param int $fromid Id of object to clone
  289. * @return mixed New object created, <0 if KO
  290. */
  291. public function createFromClone(User $user, $fromid)
  292. {
  293. global $langs, $extrafields;
  294. $error = 0;
  295. dol_syslog(__METHOD__, LOG_DEBUG);
  296. $object = new self($this->db);
  297. $this->db->begin();
  298. // Load source object
  299. $result = $object->fetchCommon($fromid);
  300. if ($result > 0 && !empty($object->table_element_line)) {
  301. $object->fetchLines();
  302. }
  303. // get lines so they will be clone
  304. //foreach($this->lines as $line)
  305. // $line->fetch_optionals();
  306. // Reset some properties
  307. unset($object->id);
  308. unset($object->fk_user_creat);
  309. unset($object->import_key);
  310. // Clear fields
  311. $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default'];
  312. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  313. $object->status = self::STATUS_DRAFT;
  314. // ...
  315. // Clear extrafields that are unique
  316. if (is_array($object->array_options) && count($object->array_options) > 0) {
  317. $extrafields->fetch_name_optionals_label($this->table_element);
  318. foreach ($object->array_options as $key => $option) {
  319. $shortkey = preg_replace('/options_/', '', $key);
  320. if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
  321. //var_dump($key);
  322. //var_dump($clonedObj->array_options[$key]); exit;
  323. unset($object->array_options[$key]);
  324. }
  325. }
  326. }
  327. // Create clone
  328. $object->context['createfromclone'] = 'createfromclone';
  329. $result = $object->createCommon($user);
  330. if ($result < 0) {
  331. $error++;
  332. $this->error = $object->error;
  333. $this->errors = $object->errors;
  334. }
  335. if (!$error) {
  336. // copy internal contacts
  337. if ($this->copy_linked_contact($object, 'internal') < 0) {
  338. $error++;
  339. }
  340. }
  341. if (!$error) {
  342. // copy external contacts if same company
  343. if (property_exists($this, 'socid') && $this->socid == $object->socid) {
  344. if ($this->copy_linked_contact($object, 'external') < 0) {
  345. $error++;
  346. }
  347. }
  348. }
  349. unset($object->context['createfromclone']);
  350. // End
  351. if (!$error) {
  352. $this->db->commit();
  353. return $object;
  354. } else {
  355. $this->db->rollback();
  356. return -1;
  357. }
  358. }
  359. /**
  360. * Load object in memory from the database
  361. *
  362. * @param int $id Id object
  363. * @param string $ref Ref
  364. * @return int <0 if KO, 0 if not found, >0 if OK
  365. */
  366. public function fetch($id, $ref = null)
  367. {
  368. $result = $this->fetchCommon($id, $ref);
  369. if ($result > 0 && !empty($this->table_element_line)) {
  370. $this->fetchLines();
  371. }
  372. $this->socid = $this->fk_soc;
  373. return $result;
  374. }
  375. /**
  376. * Load object lines in memory from the database
  377. *
  378. * @return int <0 if KO, 0 if not found, >0 if OK
  379. */
  380. public function fetchLines()
  381. {
  382. $this->lines = array();
  383. $result = $this->fetchLinesCommon();
  384. return $result;
  385. }
  386. /**
  387. * Load list of objects in memory from the database.
  388. *
  389. * @param string $sortorder Sort Order
  390. * @param string $sortfield Sort field
  391. * @param int $limit limit
  392. * @param int $offset Offset
  393. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  394. * @param string $filtermode Filter mode (AND or OR)
  395. * @return array|int int <0 if KO, array of pages if OK
  396. */
  397. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  398. {
  399. global $conf;
  400. dol_syslog(__METHOD__, LOG_DEBUG);
  401. $records = array();
  402. $sql = 'SELECT ';
  403. $sql .= $this->getFieldList();
  404. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  405. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  406. $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
  407. } else {
  408. $sql .= ' WHERE 1 = 1';
  409. }
  410. // Manage filter
  411. $sqlwhere = array();
  412. if (count($filter) > 0) {
  413. foreach ($filter as $key => $value) {
  414. if ($key == 't.rowid') {
  415. $sqlwhere[] = $key." = ".((int) $value);
  416. } elseif (strpos($key, 'date') !== false) {
  417. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  418. } elseif ($key == 'customsql') {
  419. $sqlwhere[] = $value;
  420. } else {
  421. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  422. }
  423. }
  424. }
  425. if (count($sqlwhere) > 0) {
  426. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  427. }
  428. if (!empty($sortfield)) {
  429. $sql .= $this->db->order($sortfield, $sortorder);
  430. }
  431. if (!empty($limit)) {
  432. $sql .= $this->db->plimit($limit, $offset);
  433. }
  434. $resql = $this->db->query($sql);
  435. if ($resql) {
  436. $num = $this->db->num_rows($resql);
  437. $i = 0;
  438. while ($i < min($limit, $num)) {
  439. $obj = $this->db->fetch_object($resql);
  440. $record = new self($this->db);
  441. $record->setVarsFromFetchObj($obj);
  442. $records[$record->id] = $record;
  443. $i++;
  444. }
  445. $this->db->free($resql);
  446. return $records;
  447. } else {
  448. $this->errors[] = 'Error '.$this->db->lasterror();
  449. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  450. return -1;
  451. }
  452. }
  453. /**
  454. * Get list of lines linked to current line for a defined role.
  455. *
  456. * @param string $role Get lines linked to current line with the selected role ('consumed', 'produced', ...)
  457. * @param int $lineid Id of production line to filter childs
  458. * @return array Array of lines
  459. */
  460. public function fetchLinesLinked($role, $lineid = 0)
  461. {
  462. $resarray = array();
  463. $mostatic = new MoLine($this->db);
  464. $sql = 'SELECT ';
  465. $sql .= $mostatic->getFieldList();
  466. $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t';
  467. $sql .= " WHERE t.role = '".$this->db->escape($role)."'";
  468. if ($lineid > 0) {
  469. $sql .= ' AND t.fk_mrp_production = '.((int) $lineid);
  470. } else {
  471. $sql .= 'AND t.fk_mo = '.((int) $this->id);
  472. }
  473. $resql = $this->db->query($sql);
  474. if ($resql) {
  475. $num = $this->db->num_rows($resql);
  476. $i = 0;
  477. while ($i < $num) {
  478. $obj = $this->db->fetch_object($resql);
  479. if ($obj) {
  480. $resarray[] = array(
  481. 'rowid'=> $obj->rowid,
  482. 'date'=> $this->db->jdate($obj->date_creation),
  483. 'qty' => $obj->qty,
  484. 'role' => $obj->role,
  485. 'fk_product' => $obj->fk_product,
  486. 'fk_warehouse' => $obj->fk_warehouse,
  487. 'batch' => $obj->batch,
  488. 'fk_stock_movement' => $obj->fk_stock_movement
  489. );
  490. }
  491. $i++;
  492. }
  493. return $resarray;
  494. } else {
  495. $this->error = $this->db->lasterror();
  496. return array();
  497. }
  498. }
  499. /**
  500. * Count number of movement with origin of MO
  501. *
  502. * @return int Number of movements
  503. */
  504. public function countMovements()
  505. {
  506. $result = 0;
  507. $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'stock_mouvement as sm';
  508. $sql .= " WHERE sm.origintype = 'mo' and sm.fk_origin = ".((int) $this->id);
  509. $resql = $this->db->query($sql);
  510. if ($resql) {
  511. $num = $this->db->num_rows($resql);
  512. $i = 0;
  513. while ($i < $num) {
  514. $obj = $this->db->fetch_object($resql);
  515. if ($obj) {
  516. $result = $obj->nb;
  517. }
  518. $i++;
  519. }
  520. } else {
  521. $this->error = $this->db->lasterror();
  522. }
  523. return $result;
  524. }
  525. /**
  526. * Update object into database
  527. *
  528. * @param User $user User that modifies
  529. * @param bool $notrigger false=launch triggers after, true=disable triggers
  530. * @return int <0 if KO, >0 if OK
  531. */
  532. public function update(User $user, $notrigger = false)
  533. {
  534. global $langs;
  535. $error = 0;
  536. $this->db->begin();
  537. $result = $this->updateCommon($user, $notrigger);
  538. if ($result <= 0) {
  539. $error++;
  540. }
  541. // Update the lines (the qty) to consume or to produce
  542. $result = $this->updateProduction($user, $notrigger);
  543. if ($result <= 0) {
  544. $error++;
  545. }
  546. if (!$error) {
  547. $this->db->commit();
  548. return 1;
  549. } else {
  550. $this->db->rollback();
  551. return -1;
  552. }
  553. }
  554. /**
  555. * Erase and update the line to consume and to produce.
  556. *
  557. * @param User $user User that modifies
  558. * @param bool $notrigger false=launch triggers after, true=disable triggers
  559. * @return int <0 if KO, >0 if OK
  560. */
  561. public function createProduction(User $user, $notrigger = true)
  562. {
  563. $error = 0;
  564. $role = "";
  565. if ($this->status != self::STATUS_DRAFT) {
  566. return -1;
  567. }
  568. $this->db->begin();
  569. // Insert lines in mrp_production table from BOM data
  570. if (!$error) {
  571. $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.((int) $this->id);
  572. $this->db->query($sql);
  573. $moline = new MoLine($this->db);
  574. // Line to produce
  575. $moline->fk_mo = $this->id;
  576. $moline->qty = $this->qty;
  577. $moline->fk_product = $this->fk_product;
  578. $moline->position = 1;
  579. if ($this->fk_bom > 0) { // If a BOM is defined, we know what to produce.
  580. include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
  581. $bom = new Bom($this->db);
  582. $bom->fetch($this->fk_bom);
  583. if ($bom->bomtype == 1) {
  584. $role = 'toproduce';
  585. $moline->role = 'toconsume';
  586. } else {
  587. $role = 'toconsume';
  588. $moline->role = 'toproduce';
  589. }
  590. } else {
  591. if ($this->mrptype == 1) {
  592. $moline->role = 'toconsume';
  593. } else {
  594. $moline->role = 'toproduce';
  595. }
  596. }
  597. $resultline = $moline->create($user, false); // Never use triggers here
  598. if ($resultline <= 0) {
  599. $error++;
  600. $this->error = $moline->error;
  601. $this->errors = $moline->errors;
  602. dol_print_error($this->db, $moline->error, $moline->errors);
  603. }
  604. if ($this->fk_bom > 0) { // If a BOM is defined, we know what to consume.
  605. if ($bom->id > 0) {
  606. // Lines to consume
  607. if (!$error) {
  608. foreach ($bom->lines as $line) {
  609. $moline = new MoLine($this->db);
  610. $moline->fk_mo = $this->id;
  611. $moline->origin_id = $line->id;
  612. $moline->origin_type = 'bomline';
  613. if ($line->qty_frozen) {
  614. $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce
  615. } else {
  616. $moline->qty = price2num(($line->qty / ( !empty($bom->qty) ? $bom->qty : 1 ) ) * $this->qty / ( !empty($line->efficiency) ? $line->efficiency : 1 ), 'MS'); // Calculate with Qty to produce and more presition
  617. }
  618. if ($moline->qty <= 0) {
  619. $error++;
  620. $this->error = "BadValueForquantityToConsume";
  621. break;
  622. } else {
  623. $moline->fk_product = $line->fk_product;
  624. $moline->role = $role;
  625. $moline->position = $line->position;
  626. $moline->qty_frozen = $line->qty_frozen;
  627. $moline->disable_stock_change = $line->disable_stock_change;
  628. $resultline = $moline->create($user, false); // Never use triggers here
  629. if ($resultline <= 0) {
  630. $error++;
  631. $this->error = $moline->error;
  632. $this->errors = $moline->errors;
  633. dol_print_error($this->db, $moline->error, $moline->errors);
  634. break;
  635. }
  636. }
  637. }
  638. }
  639. }
  640. }
  641. }
  642. if (!$error) {
  643. $this->db->commit();
  644. return 1;
  645. } else {
  646. $this->db->rollback();
  647. return -1;
  648. }
  649. }
  650. /**
  651. * Update quantities in lines to consume and to produce.
  652. *
  653. * @param User $user User that modifies
  654. * @param bool $notrigger false=launch triggers after, true=disable triggers
  655. * @return int <0 if KO, >0 if OK
  656. */
  657. public function updateProduction(User $user, $notrigger = true)
  658. {
  659. $error = 0;
  660. if ($this->status != self::STATUS_DRAFT) return 1;
  661. $this->db->begin();
  662. $oldQty = $this->oldQty;
  663. $newQty = $this->qty;
  664. if ($newQty != $oldQty && !empty($this->oldQty)) {
  665. $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "mrp_production WHERE fk_mo = " . (int) $this->id;
  666. $resql = $this->db->query($sql);
  667. if ($resql) {
  668. while ($obj = $this->db->fetch_object($resql)) {
  669. $moLine = new MoLine($this->db);
  670. $res = $moLine->fetch($obj->rowid);
  671. if (!$res) $error++;
  672. if ($moLine->role == 'toconsume' || $moLine->role == 'toproduce') {
  673. if (empty($moLine->qty_frozen)) {
  674. $qty = $newQty * $moLine->qty / $oldQty;
  675. $moLine->qty = price2num($qty * (!empty($line->efficiency) ? $line->efficiency : 1 ), 'MS'); // Calculate with Qty to produce and more presition
  676. $res = $moLine->update($user);
  677. if (!$res) $error++;
  678. }
  679. }
  680. }
  681. }
  682. }
  683. if (!$error) {
  684. $this->db->commit();
  685. return 1;
  686. } else {
  687. $this->db->rollback();
  688. return -1;
  689. }
  690. }
  691. /**
  692. * Delete object in database
  693. *
  694. * @param User $user User that deletes
  695. * @param bool $notrigger false=launch triggers after, true=disable triggers
  696. * @return int <0 if KO, >0 if OK
  697. */
  698. public function delete(User $user, $notrigger = false)
  699. {
  700. return $this->deleteCommon($user, $notrigger);
  701. //return $this->deleteCommon($user, $notrigger, 1);
  702. }
  703. /**
  704. * Delete a line of object in database
  705. *
  706. * @param User $user User that delete
  707. * @param int $idline Id of line to delete
  708. * @param bool $notrigger false=launch triggers after, true=disable triggers
  709. * @return int >0 if OK, <0 if KO
  710. */
  711. public function deleteLine(User $user, $idline, $notrigger = false)
  712. {
  713. global $langs;
  714. $langs->load('stocks');
  715. if ($this->status < 0) {
  716. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  717. return -2;
  718. }
  719. $productstatic = new Product($this->db);
  720. $fk_movement = GETPOST('fk_movement', 'int');
  721. $arrayoflines = $this->fetchLinesLinked('consumed', $idline);
  722. if (!empty($arrayoflines)) {
  723. $this->db->begin();
  724. $stockmove = new MouvementStock($this->db);
  725. $stockmove->setOrigin($this->element, $this->id);
  726. if (!empty($fk_movement)) {
  727. $moline = new MoLine($this->db);
  728. $TArrayMoLine = $moline->fetchAll('', '', 1, 0, array('customsql' => 'fk_stock_movement ='.$fk_movement));
  729. $moline = array_shift($TArrayMoLine);
  730. $movement = new MouvementStock($this->db);
  731. $movement->fetch($fk_movement);
  732. $productstatic->fetch($movement->product_id);
  733. $qtytoprocess = $movement->qty;
  734. // Reverse stock movement
  735. $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
  736. $codemovementCancel = $langs->trans("StockIncrease");
  737. if (($qtytoprocess >= 0)) {
  738. $idstockmove = $stockmove->reception($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, '', '', $movement->batch, dol_now(), 0, $codemovementCancel);
  739. } else {
  740. $idstockmove = $stockmove->livraison($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $movement->batch, 0, $codemovementCancel);
  741. }
  742. if ($idstockmove < 0) {
  743. $this->error++;
  744. $this->db->rollback();
  745. setEventMessages($stockmove->error, $stockmove->errors, 'errors');
  746. } else {
  747. $this->db->commit();
  748. }
  749. return $moline->delete($user, $notrigger);
  750. } else {
  751. foreach ($arrayoflines as $key => $arrayofline) {
  752. $lineDetails = $arrayoflines[$key];
  753. $productstatic->fetch($lineDetails['fk_product']);
  754. $qtytoprocess = $lineDetails['qty'];
  755. // Reverse stock movement
  756. $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
  757. $codemovementCancel = $langs->trans("StockIncrease");
  758. if ($qtytoprocess >= 0) {
  759. $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
  760. } else {
  761. $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
  762. }
  763. if ($idstockmove < 0) {
  764. $this->error++;
  765. $this->db->rollback();
  766. setEventMessages($stockmove->error, $stockmove->errors, 'errors');
  767. } else {
  768. $this->db->commit();
  769. }
  770. }
  771. return $this->deleteLineCommon($user, $idline, $notrigger);
  772. }
  773. } else {
  774. return $this->deleteLineCommon($user, $idline, $notrigger);
  775. }
  776. }
  777. /**
  778. * Returns the reference to the following non used MO depending on the active numbering module
  779. * defined into MRP_MO_ADDON
  780. *
  781. * @param Product $prod Object product
  782. * @return string MO free reference
  783. */
  784. public function getNextNumRef($prod)
  785. {
  786. global $langs, $conf;
  787. $langs->load("mrp");
  788. if (!empty($conf->global->MRP_MO_ADDON)) {
  789. $mybool = false;
  790. $file = $conf->global->MRP_MO_ADDON.".php";
  791. $classname = $conf->global->MRP_MO_ADDON;
  792. // Include file with class
  793. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  794. foreach ($dirmodels as $reldir) {
  795. $dir = dol_buildpath($reldir."core/modules/mrp/");
  796. // Load file with numbering class (if found)
  797. $mybool |= @include_once $dir.$file;
  798. }
  799. if ($mybool === false) {
  800. dol_print_error('', "Failed to include file ".$file);
  801. return '';
  802. }
  803. $obj = new $classname();
  804. $numref = $obj->getNextValue($prod, $this);
  805. if ($numref != "") {
  806. return $numref;
  807. } else {
  808. $this->error = $obj->error;
  809. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  810. return "";
  811. }
  812. } else {
  813. print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
  814. return "";
  815. }
  816. }
  817. /**
  818. * Validate Mo
  819. *
  820. * @param User $user User making status change
  821. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  822. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  823. */
  824. public function validate($user, $notrigger = 0)
  825. {
  826. global $conf, $langs;
  827. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  828. $error = 0;
  829. // Protection
  830. if ($this->status == self::STATUS_VALIDATED) {
  831. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  832. return 0;
  833. }
  834. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->create))
  835. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->mrp_advance->validate))))
  836. {
  837. $this->error='NotEnoughPermissions';
  838. dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
  839. return -1;
  840. }*/
  841. $now = dol_now();
  842. $this->db->begin();
  843. // Define new ref
  844. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  845. $this->fetch_product();
  846. $num = $this->getNextNumRef($this->product);
  847. } else {
  848. $num = $this->ref;
  849. }
  850. $this->newref = $num;
  851. // Validate
  852. $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
  853. $sql .= " SET ref = '".$this->db->escape($num)."',";
  854. $sql .= " status = ".self::STATUS_VALIDATED.",";
  855. $sql .= " date_valid='".$this->db->idate($now)."',";
  856. $sql .= " fk_user_valid = ".$user->id;
  857. $sql .= " WHERE rowid = ".((int) $this->id);
  858. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  859. $resql = $this->db->query($sql);
  860. if (!$resql) {
  861. dol_print_error($this->db);
  862. $this->error = $this->db->lasterror();
  863. $error++;
  864. }
  865. if (!$error && !$notrigger) {
  866. // Call trigger
  867. $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
  868. if ($result < 0) {
  869. $error++;
  870. }
  871. // End call triggers
  872. }
  873. if (!$error) {
  874. $this->oldref = $this->ref;
  875. // Rename directory if dir was a temporary ref
  876. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  877. // Now we rename also files into index
  878. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'mrp/".$this->db->escape($this->newref)."'";
  879. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  880. $resql = $this->db->query($sql);
  881. if (!$resql) {
  882. $error++; $this->error = $this->db->lasterror();
  883. }
  884. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  885. $oldref = dol_sanitizeFileName($this->ref);
  886. $newref = dol_sanitizeFileName($num);
  887. $dirsource = $conf->mrp->dir_output.'/'.$oldref;
  888. $dirdest = $conf->mrp->dir_output.'/'.$newref;
  889. if (!$error && file_exists($dirsource)) {
  890. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  891. if (@rename($dirsource, $dirdest)) {
  892. dol_syslog("Rename ok");
  893. // Rename docs starting with $oldref with $newref
  894. $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  895. foreach ($listoffiles as $fileentry) {
  896. $dirsource = $fileentry['name'];
  897. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  898. $dirsource = $fileentry['path'].'/'.$dirsource;
  899. $dirdest = $fileentry['path'].'/'.$dirdest;
  900. @rename($dirsource, $dirdest);
  901. }
  902. }
  903. }
  904. }
  905. }
  906. // Set new ref and current status
  907. if (!$error) {
  908. $this->ref = $num;
  909. $this->status = self::STATUS_VALIDATED;
  910. }
  911. if (!$error) {
  912. $this->db->commit();
  913. return 1;
  914. } else {
  915. $this->db->rollback();
  916. return -1;
  917. }
  918. }
  919. /**
  920. * Set draft status
  921. *
  922. * @param User $user Object user that modify
  923. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  924. * @return int <0 if KO, >0 if OK
  925. */
  926. public function setDraft($user, $notrigger = 0)
  927. {
  928. // Protection
  929. if ($this->status <= self::STATUS_DRAFT) {
  930. return 0;
  931. }
  932. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
  933. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
  934. {
  935. $this->error='Permission denied';
  936. return -1;
  937. }*/
  938. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MRP_MO_UNVALIDATE');
  939. }
  940. /**
  941. * Set cancel status
  942. *
  943. * @param User $user Object user that modify
  944. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  945. * @return int <0 if KO, 0=Nothing done, >0 if OK
  946. */
  947. public function cancel($user, $notrigger = 0)
  948. {
  949. // Protection
  950. if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) {
  951. return 0;
  952. }
  953. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
  954. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
  955. {
  956. $this->error='Permission denied';
  957. return -1;
  958. }*/
  959. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MRP_MO_CANCEL');
  960. }
  961. /**
  962. * Set back to validated status
  963. *
  964. * @param User $user Object user that modify
  965. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  966. * @return int <0 if KO, 0=Nothing done, >0 if OK
  967. */
  968. public function reopen($user, $notrigger = 0)
  969. {
  970. // Protection
  971. if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) {
  972. return 0;
  973. }
  974. /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
  975. || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
  976. {
  977. $this->error='Permission denied';
  978. return -1;
  979. }*/
  980. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MRP_MO_REOPEN');
  981. }
  982. /**
  983. * getTooltipContentArray
  984. *
  985. * @param array $params ex option, infologin
  986. * @since v18
  987. * @return array
  988. */
  989. public function getTooltipContentArray($params)
  990. {
  991. global $conf, $langs;
  992. $langs->loadLangs(['mrp', 'products']);
  993. $nofetch = isset($params['nofetch']) ? true : false;
  994. $datas = [];
  995. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ManufacturingOrder").'</u>';
  996. if (isset($this->status)) {
  997. $datas['picto'] .= ' '.$this->getLibStatut(5);
  998. }
  999. $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
  1000. if (isset($this->label)) {
  1001. $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
  1002. }
  1003. if (isset($this->mrptype)) {
  1004. $datas['type'] = '<br><b>'.$langs->trans('Type').':</b> '.$this->fields['mrptype']['arrayofkeyval'][$this->mrptype];
  1005. }
  1006. if (isset($this->qty)) {
  1007. $datas['qty'] = '<br><b>'.$langs->trans('QtyToProduce').':</b> '.$this->qty;
  1008. }
  1009. if (!$nofetch && isset($this->fk_product)) {
  1010. require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  1011. $product = new Product($this->db);
  1012. $product->fetch($this->fk_product);
  1013. $datas['product'] = '<br><b>'.$langs->trans('Product').':</b> '.$product->getNomUrl(1, '', 0, -1, 1);
  1014. }
  1015. if (!$nofetch && isset($this->fk_warehouse)) {
  1016. require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
  1017. $warehouse = new Entrepot($this->db);
  1018. $warehouse->fetch($this->fk_warehouse);
  1019. $datas['warehouse'] = '<br><b>'.$langs->trans('WarehouseForProduction').':</b> '.$warehouse->getNomUrl(1, '', 0, 1);
  1020. }
  1021. return $datas;
  1022. }
  1023. /**
  1024. * Return a link to the object card (with optionaly the picto)
  1025. *
  1026. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  1027. * @param string $option On what the link point to ('nolink', '', 'production', ...)
  1028. * @param int $notooltip 1=Disable tooltip
  1029. * @param string $morecss Add more css on link
  1030. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  1031. * @return string String with URL
  1032. */
  1033. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  1034. {
  1035. global $conf, $langs, $hookmanager;
  1036. if (!empty($conf->dol_no_mouse_hover)) {
  1037. $notooltip = 1; // Force disable tooltips
  1038. }
  1039. $result = '';
  1040. $params = [
  1041. 'id' => $this->id,
  1042. 'objecttype' => $this->element,
  1043. 'option' => $option,
  1044. 'nofetch' => 1,
  1045. ];
  1046. $classfortooltip = 'classfortooltip';
  1047. $dataparams = '';
  1048. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  1049. $classfortooltip = 'classforajaxtooltip';
  1050. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  1051. $label = '';
  1052. } else {
  1053. $label = implode($this->getTooltipContentArray($params));
  1054. }
  1055. $url = DOL_URL_ROOT.'/mrp/mo_card.php?id='.$this->id;
  1056. if ($option == 'production') {
  1057. $url = DOL_URL_ROOT.'/mrp/mo_production.php?id='.$this->id;
  1058. }
  1059. if ($option != 'nolink') {
  1060. // Add param to save lastsearch_values or not
  1061. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  1062. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  1063. $add_save_lastsearch_values = 1;
  1064. }
  1065. if ($add_save_lastsearch_values) {
  1066. $url .= '&save_lastsearch_values=1';
  1067. }
  1068. }
  1069. $linkclose = '';
  1070. if (empty($notooltip)) {
  1071. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  1072. $label = $langs->trans("ShowMo");
  1073. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  1074. }
  1075. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  1076. $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
  1077. } else {
  1078. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  1079. }
  1080. $linkstart = '<a href="'.$url.'"';
  1081. $linkstart .= $linkclose.'>';
  1082. $linkend = '</a>';
  1083. $result .= $linkstart;
  1084. if ($withpicto) {
  1085. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
  1086. }
  1087. if ($withpicto != 2) {
  1088. $result .= $this->ref;
  1089. }
  1090. $result .= $linkend;
  1091. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  1092. global $action, $hookmanager;
  1093. $hookmanager->initHooks(array('modao'));
  1094. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  1095. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1096. if ($reshook > 0) {
  1097. $result = $hookmanager->resPrint;
  1098. } else {
  1099. $result .= $hookmanager->resPrint;
  1100. }
  1101. return $result;
  1102. }
  1103. /**
  1104. * Return label of the status
  1105. *
  1106. * @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
  1107. * @return string Label of status
  1108. */
  1109. public function getLibStatut($mode = 0)
  1110. {
  1111. return $this->LibStatut($this->status, $mode);
  1112. }
  1113. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1114. /**
  1115. * Return the status
  1116. *
  1117. * @param int $status Id status
  1118. * @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
  1119. * @return string Label of status
  1120. */
  1121. public function LibStatut($status, $mode = 0)
  1122. {
  1123. // phpcs:enable
  1124. if (empty($this->labelStatus)) {
  1125. global $langs;
  1126. //$langs->load("mrp");
  1127. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  1128. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatedToProduce');
  1129. $this->labelStatus[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
  1130. $this->labelStatus[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
  1131. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
  1132. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  1133. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
  1134. $this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
  1135. $this->labelStatusShort[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
  1136. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
  1137. }
  1138. $statusType = 'status'.$status;
  1139. if ($status == self::STATUS_VALIDATED) {
  1140. $statusType = 'status1';
  1141. }
  1142. if ($status == self::STATUS_INPROGRESS) {
  1143. $statusType = 'status4';
  1144. }
  1145. if ($status == self::STATUS_PRODUCED) {
  1146. $statusType = 'status6';
  1147. }
  1148. if ($status == self::STATUS_CANCELED) {
  1149. $statusType = 'status9';
  1150. }
  1151. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  1152. }
  1153. /**
  1154. * Load the info information in the object
  1155. *
  1156. * @param int $id Id of object
  1157. * @return void
  1158. */
  1159. public function info($id)
  1160. {
  1161. $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
  1162. $sql .= ' fk_user_creat, fk_user_modif';
  1163. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1164. $sql .= ' WHERE t.rowid = '.((int) $id);
  1165. $result = $this->db->query($sql);
  1166. if ($result) {
  1167. if ($this->db->num_rows($result)) {
  1168. $obj = $this->db->fetch_object($result);
  1169. $this->id = $obj->rowid;
  1170. $this->user_creation_id = $obj->fk_user_creat;
  1171. $this->user_modification_id = $obj->fk_user_modif;
  1172. $this->date_creation = $this->db->jdate($obj->datec);
  1173. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  1174. }
  1175. $this->db->free($result);
  1176. } else {
  1177. dol_print_error($this->db);
  1178. }
  1179. }
  1180. /**
  1181. * Initialise object with example values
  1182. * Id must be 0 if object instance is a specimen
  1183. *
  1184. * @return void
  1185. */
  1186. public function initAsSpecimen()
  1187. {
  1188. $this->initAsSpecimenCommon();
  1189. $this->lines = array();
  1190. }
  1191. /**
  1192. * Create an array of lines
  1193. * @param string $rolefilter string lines role filter
  1194. * @return array|int array of lines if OK, <0 if KO
  1195. */
  1196. public function getLinesArray($rolefilter = '')
  1197. {
  1198. $this->lines = array();
  1199. $objectline = new MoLine($this->db);
  1200. $TFilters = array('customsql'=>'fk_mo = '.((int) $this->id));
  1201. if (!empty($rolefilter)) $TFilters['role'] = $rolefilter;
  1202. $result = $objectline->fetchAll('ASC', 'position', 0, 0, $TFilters);
  1203. if (is_numeric($result)) {
  1204. $this->error = $objectline->error;
  1205. $this->errors = $objectline->errors;
  1206. return $result;
  1207. } else {
  1208. $this->lines = $result;
  1209. return $this->lines;
  1210. }
  1211. }
  1212. /**
  1213. * Create a document onto disk according to template module.
  1214. *
  1215. * @param string $modele Force template to use ('' to not force)
  1216. * @param Translate $outputlangs objet lang a utiliser pour traduction
  1217. * @param int $hidedetails Hide details of lines
  1218. * @param int $hidedesc Hide description
  1219. * @param int $hideref Hide ref
  1220. * @param null|array $moreparams Array to provide more information
  1221. * @return int 0 if KO, 1 if OK
  1222. */
  1223. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  1224. {
  1225. global $conf, $langs;
  1226. $langs->load("mrp");
  1227. if (!dol_strlen($modele)) {
  1228. //$modele = 'standard';
  1229. $modele = ''; // Remove this once a pdf_standard.php exists.
  1230. if ($this->model_pdf) {
  1231. $modele = $this->model_pdf;
  1232. } elseif (!empty($conf->global->MO_ADDON_PDF)) {
  1233. $modele = $conf->global->MO_ADDON_PDF;
  1234. }
  1235. }
  1236. $modelpath = "core/modules/mrp/doc/";
  1237. if (empty($modele)) {
  1238. return 1; // Remove this once a pdf_standard.php exists.
  1239. }
  1240. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  1241. }
  1242. /**
  1243. * Action executed by scheduler
  1244. * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters'
  1245. * Use public function doScheduledJob($param1, $param2, ...) to get parameters
  1246. *
  1247. * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK)
  1248. */
  1249. public function doScheduledJob()
  1250. {
  1251. global $conf, $langs;
  1252. //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
  1253. $error = 0;
  1254. $this->output = '';
  1255. $this->error = '';
  1256. dol_syslog(__METHOD__, LOG_DEBUG);
  1257. $now = dol_now();
  1258. $this->db->begin();
  1259. // ...
  1260. $this->db->commit();
  1261. return $error;
  1262. }
  1263. /**
  1264. * Return HTML table table of source object lines
  1265. * TODO Move this and previous function into output html class file (htmlline.class.php).
  1266. * If lines are into a template, title must also be into a template
  1267. * But for the moment we don't know if it's possible, so we keep the method available on overloaded objects.
  1268. *
  1269. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only
  1270. * @param array $selectedLines Array of lines id for selected lines
  1271. * @return void
  1272. */
  1273. public function printOriginLinesList($restrictlist = '', $selectedLines = array())
  1274. {
  1275. global $langs, $hookmanager, $conf, $form;
  1276. $langs->load('stocks');
  1277. $text_stock_options = $langs->trans("RealStockDesc").'<br>';
  1278. $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen").'<br>';
  1279. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) ? '- '.$langs->trans("DeStockOnShipment").'<br>' : '');
  1280. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) ? '- '.$langs->trans("DeStockOnValidateOrder").'<br>' : '');
  1281. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_BILL) ? '- '.$langs->trans("DeStockOnBill").'<br>' : '');
  1282. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) ? '- '.$langs->trans("ReStockOnBill").'<br>' : '');
  1283. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) ? '- '.$langs->trans("ReStockOnValidateOrder").'<br>' : '');
  1284. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) ? '- '.$langs->trans("ReStockOnDispatchOrder").'<br>' : '');
  1285. $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? '- '.$langs->trans("StockOnReception").'<br>' : '');
  1286. print '<tr class="liste_titre">';
  1287. // Product or sub-bom
  1288. print '<td class="linecoldescription">'.$langs->trans('Ref');
  1289. if (!empty($conf->global->BOM_SUB_BOM)) {
  1290. print ' &nbsp; <a id="show_all" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a>&nbsp;&nbsp;';
  1291. print '<a id="hide_all" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a>&nbsp;';
  1292. }
  1293. print '</td>';
  1294. // Qty
  1295. print '<td class="right">'.$langs->trans('Qty');
  1296. if ($this->bom->bomtype == 0) {
  1297. print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityOf", $this->bom->qty).')</span>';
  1298. } else {
  1299. print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityToConsumeOf", $this->bom->qty).')</span>';
  1300. }
  1301. print '</td>';
  1302. print '<td class="center">'.$form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1).'</td>';
  1303. print '<td class="center">'.$form->textwithpicto($langs->trans("VirtualStock"), $langs->trans("VirtualStockDesc")).'</td>';
  1304. print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
  1305. print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
  1306. print '<td class="center">'.$langs->trans('MoChildGenerate').'</td>';
  1307. //print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
  1308. //print '<td class="center"></td>';
  1309. print '</tr>';
  1310. $i = 0;
  1311. if (!empty($this->lines)) {
  1312. foreach ($this->lines as $line) {
  1313. $reshook = 0;
  1314. if (is_object($hookmanager)) {
  1315. $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
  1316. if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
  1317. $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1318. }
  1319. if (empty($reshook)) {
  1320. $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
  1321. }
  1322. $i++;
  1323. }
  1324. }
  1325. }
  1326. /**
  1327. * Return HTML with a line of table array of source object lines
  1328. * TODO Move this and previous function into output html class file (htmlline.class.php).
  1329. * If lines are into a template, title must also be into a template
  1330. * But for the moment we don't know if it's possible as we keep a method available on overloaded objects.
  1331. *
  1332. * @param MoLine $line Line
  1333. * @param string $var Var
  1334. * @param string $restrictlist ''=All lines, 'services'=Restrict to services only (strike line if not)
  1335. * @param string $defaulttpldir Directory where to find the template
  1336. * @param array $selectedLines Array of lines id for selected lines
  1337. * @return void
  1338. */
  1339. public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
  1340. {
  1341. global $langs, $conf;
  1342. $this->tpl['id'] = $line->id;
  1343. $this->tpl['label'] = '';
  1344. if (!empty($line->fk_product)) {
  1345. $productstatic = new Product($this->db);
  1346. $productstatic->fetch($line->fk_product);
  1347. $productstatic->load_virtual_stock();
  1348. $this->tpl['label'] .= $productstatic->getNomUrl(1);
  1349. //$this->tpl['label'].= ' - '.$productstatic->label;
  1350. } else {
  1351. // If origin MRP line is not a product, but another MRP
  1352. // TODO
  1353. }
  1354. $this->tpl['qty_bom'] = 1;
  1355. if (is_object($this->bom) && $this->bom->qty > 1) {
  1356. $this->tpl['qty_bom'] = $this->bom->qty;
  1357. }
  1358. $this->tpl['stock'] = $productstatic->stock_reel;
  1359. $this->tpl['seuil_stock_alerte'] = $productstatic->seuil_stock_alerte;
  1360. $this->tpl['virtual_stock'] = $productstatic->stock_theorique;
  1361. $this->tpl['qty'] = $line->qty;
  1362. $this->tpl['qty_frozen'] = $line->qty_frozen;
  1363. $this->tpl['disable_stock_change'] = $line->disable_stock_change;
  1364. $this->tpl['efficiency'] = $line->efficiency;
  1365. $tpl = DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
  1366. $res = include $tpl;
  1367. }
  1368. /**
  1369. * Function used to replace a thirdparty id with another one.
  1370. *
  1371. * @param DoliDB $db Database handler
  1372. * @param int $origin_id Old thirdparty id
  1373. * @param int $dest_id New thirdparty id
  1374. * @return bool
  1375. */
  1376. public static function replaceThirdparty($db, $origin_id, $dest_id)
  1377. {
  1378. $tables = array('mrp_mo');
  1379. return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
  1380. }
  1381. /**
  1382. * Function used to return childs of Mo
  1383. *
  1384. * @return Mo[]|int array if OK, -1 if KO
  1385. */
  1386. public function getMoChilds()
  1387. {
  1388. $TMoChilds = array();
  1389. $error = 0;
  1390. $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_mo as mo_child";
  1391. $sql.= " WHERE fk_parent_line IN ";
  1392. $sql.= " (SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_production as line_parent";
  1393. $sql.= " WHERE fk_mo=".((int) $this->id).")";
  1394. $resql = $this->db->query($sql);
  1395. if ($resql) {
  1396. if ($this->db->num_rows($resql) > 0) {
  1397. while ($obj = $this->db->fetch_object($resql)) {
  1398. $MoChild = new Mo($this->db);
  1399. $res = $MoChild->fetch($obj->rowid);
  1400. if ($res > 0) $TMoChilds[$MoChild->id] = $MoChild;
  1401. else $error++;
  1402. }
  1403. }
  1404. } else {
  1405. $error++;
  1406. }
  1407. if ($error) {
  1408. return -1;
  1409. } else {
  1410. return $TMoChilds;
  1411. }
  1412. }
  1413. /**
  1414. * Function used to return childs of Mo
  1415. *
  1416. * @return Mo|int MO object if OK, -1 if KO, 0 if not exist
  1417. */
  1418. public function getMoParent()
  1419. {
  1420. $MoParent = new Mo($this->db);
  1421. $error = 0;
  1422. $sql = "SELECT lineparent.fk_mo as id_moparent FROM ".MAIN_DB_PREFIX."mrp_mo as mo";
  1423. $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."mrp_production lineparent ON mo.fk_parent_line = lineparent.rowid";
  1424. $sql.= " WHERE mo.rowid = ".((int) $this->id);
  1425. $resql = $this->db->query($sql);
  1426. if ($resql) {
  1427. if ($this->db->num_rows($resql) > 0) {
  1428. $obj = $this->db->fetch_object($resql);
  1429. $res = $MoParent->fetch($obj->id_moparent);
  1430. if ($res < 0) $error++;
  1431. } else {
  1432. return 0;
  1433. }
  1434. } else {
  1435. $error++;
  1436. }
  1437. if ($error) {
  1438. return -1;
  1439. } else {
  1440. return $MoParent;
  1441. }
  1442. }
  1443. /**
  1444. * Return clicable link of object (with eventually picto)
  1445. *
  1446. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  1447. * @param array $arraydata Array of data
  1448. * @return string HTML Code for Kanban thumb.
  1449. */
  1450. public function getKanbanView($option = '', $arraydata = null)
  1451. {
  1452. global $langs;
  1453. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  1454. $return = '<div class="box-flex-item box-flex-grow-zero">';
  1455. $return .= '<div class="info-box info-box-sm">';
  1456. $return .= '<span class="info-box-icon bg-infobox-action">';
  1457. $return .= img_picto('', $this->picto);
  1458. //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
  1459. $return .= '</span>';
  1460. $return .= '<div class="info-box-content">';
  1461. $return .= '<span class="info-box-ref">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  1462. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  1463. if (property_exists($this, 'fk_bom')) {
  1464. $return .= '<br><span class="info-box-label opacitymedium">'.$this->fk_bom.'</span>';
  1465. }
  1466. if (property_exists($this, 'qty')) {
  1467. $return .= '<br><span class="info-box-label">'.$langs->trans('Quantity').' : '.$this->qty.'</span>';
  1468. }
  1469. if (method_exists($this, 'getLibStatut')) {
  1470. $return .= '<br><div class="info-box-status margintoponly">'.$this->getLibStatut(3).'</div>';
  1471. }
  1472. $return .= '</div>';
  1473. $return .= '</div>';
  1474. $return .= '</div>';
  1475. return $return;
  1476. }
  1477. }
  1478. /**
  1479. * Class MoLine. You can also remove this and generate a CRUD class for lines objects.
  1480. */
  1481. class MoLine extends CommonObjectLine
  1482. {
  1483. /**
  1484. * @var string ID to identify managed object
  1485. */
  1486. public $element = 'mrp_production';
  1487. /**
  1488. * @var string Name of table without prefix where object is stored
  1489. */
  1490. public $table_element = 'mrp_production';
  1491. /**
  1492. * @var int Does myobject support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  1493. */
  1494. public $ismultientitymanaged = 0;
  1495. /**
  1496. * @var int Does moline support extrafields ? 0=No, 1=Yes
  1497. */
  1498. public $isextrafieldmanaged = 0;
  1499. public $fields = array(
  1500. 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
  1501. 'fk_mo' =>array('type'=>'integer', 'label'=>'Mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
  1502. 'origin_id' =>array('type'=>'integer', 'label'=>'Origin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>17),
  1503. 'origin_type' =>array('type'=>'varchar(10)', 'label'=>'Origin type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>18),
  1504. 'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
  1505. 'fk_product' =>array('type'=>'integer', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
  1506. 'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
  1507. 'qty' =>array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
  1508. 'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
  1509. 'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
  1510. 'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
  1511. 'role' =>array('type'=>'varchar(10)', 'label'=>'Role', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
  1512. 'fk_mrp_production' =>array('type'=>'integer', 'label'=>'Fk mrp production', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
  1513. 'fk_stock_movement' =>array('type'=>'integer', 'label'=>'StockMovement', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
  1514. 'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>160),
  1515. 'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>165),
  1516. 'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>170),
  1517. 'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModification', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
  1518. 'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
  1519. 'fk_default_workstation' =>array('type'=>'integer', 'label'=>'DefaultWorkstation', 'enabled'=>1, 'visible'=>1, 'notnull'=>0, 'position'=>185)
  1520. );
  1521. public $rowid;
  1522. public $fk_mo;
  1523. public $origin_id;
  1524. public $origin_type;
  1525. public $position;
  1526. public $fk_product;
  1527. public $fk_warehouse;
  1528. public $qty;
  1529. public $qty_frozen;
  1530. public $disable_stock_change;
  1531. public $efficiency;
  1532. public $batch;
  1533. public $role;
  1534. public $fk_mrp_production;
  1535. public $fk_stock_movement;
  1536. public $date_creation;
  1537. public $tms;
  1538. public $fk_user_creat;
  1539. public $fk_user_modif;
  1540. public $import_key;
  1541. public $fk_parent_line;
  1542. /**
  1543. * @var int Service Workstation
  1544. */
  1545. public $fk_default_workstation;
  1546. /**
  1547. * Constructor
  1548. *
  1549. * @param DoliDb $db Database handler
  1550. */
  1551. public function __construct(DoliDB $db)
  1552. {
  1553. global $conf, $langs;
  1554. $this->db = $db;
  1555. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  1556. $this->fields['rowid']['visible'] = 0;
  1557. }
  1558. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  1559. $this->fields['entity']['enabled'] = 0;
  1560. }
  1561. // Unset fields that are disabled
  1562. foreach ($this->fields as $key => $val) {
  1563. if (isset($val['enabled']) && empty($val['enabled'])) {
  1564. unset($this->fields[$key]);
  1565. }
  1566. }
  1567. // Translate some data of arrayofkeyval
  1568. if (is_object($langs)) {
  1569. foreach ($this->fields as $key => $val) {
  1570. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  1571. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  1572. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. }
  1578. /**
  1579. * Create object into database
  1580. *
  1581. * @param User $user User that creates
  1582. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1583. * @return int <0 if KO, Id of created object if OK
  1584. */
  1585. public function create(User $user, $notrigger = false)
  1586. {
  1587. if (empty($this->qty)) {
  1588. $this->error = 'BadValueForQty';
  1589. return -1;
  1590. }
  1591. return $this->createCommon($user, $notrigger);
  1592. }
  1593. /**
  1594. * Load object in memory from the database
  1595. *
  1596. * @param int $id Id object
  1597. * @param string $ref Ref
  1598. * @return int <0 if KO, 0 if not found, >0 if OK
  1599. */
  1600. public function fetch($id, $ref = null)
  1601. {
  1602. $result = $this->fetchCommon($id, $ref);
  1603. return $result;
  1604. }
  1605. /**
  1606. * Load list of objects in memory from the database.
  1607. *
  1608. * @param string $sortorder Sort Order
  1609. * @param string $sortfield Sort field
  1610. * @param int $limit limit
  1611. * @param int $offset Offset
  1612. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  1613. * @param string $filtermode Filter mode (AND or OR)
  1614. * @return array|int int <0 if KO, array of pages if OK
  1615. */
  1616. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  1617. {
  1618. global $conf;
  1619. dol_syslog(__METHOD__, LOG_DEBUG);
  1620. $records = array();
  1621. $sql = 'SELECT ';
  1622. $sql .= $this->getFieldList();
  1623. $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
  1624. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  1625. $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
  1626. } else {
  1627. $sql .= ' WHERE 1 = 1';
  1628. }
  1629. // Manage filter
  1630. $sqlwhere = array();
  1631. if (count($filter) > 0) {
  1632. foreach ($filter as $key => $value) {
  1633. if ($key == 't.rowid') {
  1634. $sqlwhere[] = $key." = ".((int) $value);
  1635. } elseif (strpos($key, 'date') !== false) {
  1636. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  1637. } elseif ($key == 'customsql') {
  1638. $sqlwhere[] = $value;
  1639. } else {
  1640. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  1641. }
  1642. }
  1643. }
  1644. if (count($sqlwhere) > 0) {
  1645. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  1646. }
  1647. if (!empty($sortfield)) {
  1648. $sql .= $this->db->order($sortfield, $sortorder);
  1649. }
  1650. if (!empty($limit)) {
  1651. $sql .= $this->db->plimit($limit, $offset);
  1652. }
  1653. $resql = $this->db->query($sql);
  1654. if ($resql) {
  1655. $num = $this->db->num_rows($resql);
  1656. $i = 0;
  1657. while ($i < ($limit ? min($limit, $num) : $num)) {
  1658. $obj = $this->db->fetch_object($resql);
  1659. $record = new self($this->db);
  1660. $record->setVarsFromFetchObj($obj);
  1661. $records[$record->id] = $record;
  1662. $i++;
  1663. }
  1664. $this->db->free($resql);
  1665. return $records;
  1666. } else {
  1667. $this->errors[] = 'Error '.$this->db->lasterror();
  1668. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  1669. return -1;
  1670. }
  1671. }
  1672. /**
  1673. * Update object into database
  1674. *
  1675. * @param User $user User that modifies
  1676. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1677. * @return int <0 if KO, >0 if OK
  1678. */
  1679. public function update(User $user, $notrigger = false)
  1680. {
  1681. return $this->updateCommon($user, $notrigger);
  1682. }
  1683. /**
  1684. * Delete object in database
  1685. *
  1686. * @param User $user User that deletes
  1687. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1688. * @return int <0 if KO, >0 if OK
  1689. */
  1690. public function delete(User $user, $notrigger = false)
  1691. {
  1692. return $this->deleteCommon($user, $notrigger);
  1693. //return $this->deleteCommon($user, $notrigger, 1);
  1694. }
  1695. }