mo.class.php 53 KB

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