mo.class.php 60 KB

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