mo.class.php 60 KB

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