mo.class.php 66 KB

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