mo.class.php 73 KB

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