mo.class.php 58 KB

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