dolibarr  16.0.5
mo.class.php
Go to the documentation of this file.
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 
26 // Put here all includes required by your class file
27 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
29 //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
30 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
31 
35 class Mo extends CommonObject
36 {
40  public $element = 'mo';
41 
45  public $table_element = 'mrp_mo';
46 
50  public $ismultientitymanaged = 1;
51 
55  public $isextrafieldmanaged = 1;
56 
60  public $picto = 'mrp';
61 
62 
63  const STATUS_DRAFT = 0;
64  const STATUS_VALIDATED = 1; // To produce
65  const STATUS_INPROGRESS = 2;
66  const STATUS_PRODUCED = 3;
67  const STATUS_CANCELED = 9;
68 
69 
96  // BEGIN MODULEBUILDER PROPERTIES
100  public $fields = array(
101  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
102  'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1),
103  '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),
104  'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:t.status=1', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>'$conf->bom->enabled', 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM", 'css'=>'minwidth100 maxwidth300', 'csslist'=>'nowraponall', 'picto'=>'bom'),
105  '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'),
106  'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:0', 'label'=>'Product', 'enabled'=>'$conf->product->enabled', 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce", 'css'=>'maxwidth300', 'csslist'=>'tdoverflowmax100', 'picto'=>'product'),
107  'qty' => array('type'=>'real', 'label'=>'QtyToProduce', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'notnull'=>1, 'comment'=>"Qty to produce", 'css'=>'width75', 'default'=>1, 'isameasure'=>1),
108  'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'showoncombobox'=>'2', 'css'=>'maxwidth300', 'csslist'=>'tdoverflowmax200'),
109  'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'picto'=>'company', 'enabled'=>'$conf->societe->enabled', 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'css'=>'maxwidth400', 'csslist'=>'tdoverflowmax150'),
110  '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'),
111  'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'picto'=>'stock', 'enabled'=>'$conf->stock->enabled', 'visible'=>1, 'position'=>52, 'css'=>'maxwidth400', 'csslist'=>'tdoverflowmax200'),
112  'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,),
113  'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'notnull'=>-1,),
114  'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,),
115  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>1,),
116  'date_valid' => array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-2, 'position'=>502,),
117  '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'),
118  'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1, 'csslist'=>'tdoverflowmax100'),
119  'date_start_planned' => array('type'=>'datetime', 'label'=>'DateStartPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>55, 'notnull'=>-1, 'index'=>1, 'help'=>'KeepEmptyForAsap'),
120  'date_end_planned' => array('type'=>'datetime', 'label'=>'DateEndPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>56, 'notnull'=>-1, 'index'=>1,),
121  'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
122  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
123  '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')),
124  '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),
125  );
126  public $rowid;
127  public $entity;
128  public $ref;
129  public $mrptype;
130  public $label;
131  public $qty;
132  public $fk_warehouse;
133  public $fk_soc;
134 
138  public $note_public;
139 
143  public $note_private;
144 
148  public $date_creation;
149 
150 
151  public $tms;
152  public $fk_user_creat;
153  public $fk_user_modif;
154  public $import_key;
155  public $status;
156  public $fk_product;
157 
161  public $date_start_planned;
162 
166  public $date_end_planned;
167 
168 
169  public $fk_bom;
170  public $fk_project;
171  // END MODULEBUILDER PROPERTIES
172 
173 
174  // If this object has a subtable with lines
175 
179  public $table_element_line = 'mrp_production';
180 
184  public $fk_element = 'fk_mo';
185 
189  public $class_element_line = 'MoLine';
190 
194  protected $childtables = array();
195 
199  protected $childtablesoncascade = array('mrp_production');
200 
204  public $lines = array();
205 
210  public $fk_parent_line;
211 
212 
218  public function __construct(DoliDB $db)
219  {
220  global $conf, $langs;
221 
222  $this->db = $db;
223 
224  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
225  $this->fields['rowid']['visible'] = 0;
226  }
227  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
228  $this->fields['entity']['enabled'] = 0;
229  }
230 
231  // Unset fields that are disabled
232  foreach ($this->fields as $key => $val) {
233  if (isset($val['enabled']) && empty($val['enabled'])) {
234  unset($this->fields[$key]);
235  }
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 
255  public function create(User $user, $notrigger = false)
256  {
257  global $conf;
258 
259  $error = 0;
260  $idcreated = 0;
261 
262  $this->db->begin();
263 
264  // Check that product is not a kit/virtual product
265  if (empty($conf->global->ALLOW_USE_KITS_INTO_BOM_AND_MO) && $this->fk_product > 0) {
266  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
267  $tmpproduct = new Product($this->db);
268  $tmpproduct->fetch($this->fk_product);
269  if ($tmpproduct->hasFatherOrChild(1) > 0) {
270  $this->error = 'ErrorAVirtualProductCantBeUsedIntoABomOrMo';
271  $this->errors[] = $this->error;
272  $this->db->rollback();
273  return -1;
274  }
275  }
276 
277  if ($this->fk_bom > 0) {
278  // If there is a nown BOM, we force the type of MO to the type of BOM
279  $tmpbom = new BOM($this->db);
280  $tmpbom->fetch($this->fk_bom);
281 
282  $this->mrptype = $tmpbom->bomtype;
283  }
284 
285  if (!$error) {
286  $idcreated = $this->createCommon($user, $notrigger);
287  if ($idcreated <= 0) {
288  $error++;
289  }
290  }
291 
292  if (!$error) {
293  $result = $this->updateProduction($user, $notrigger); // Insert lines from BOM
294  if ($result <= 0) {
295  $error++;
296  }
297  }
298 
299  if (!$error) {
300  $this->db->commit();
301  } else {
302  $this->db->rollback();
303  }
304 
305  return $idcreated;
306  }
307 
315  public function createFromClone(User $user, $fromid)
316  {
317  global $langs, $extrafields;
318  $error = 0;
319 
320  dol_syslog(__METHOD__, LOG_DEBUG);
321 
322  $object = new self($this->db);
323 
324  $this->db->begin();
325 
326  // Load source object
327  $result = $object->fetchCommon($fromid);
328  if ($result > 0 && !empty($object->table_element_line)) {
329  $object->fetchLines();
330  }
331 
332  // get lines so they will be clone
333  //foreach($this->lines as $line)
334  // $line->fetch_optionals();
335 
336  // Reset some properties
337  unset($object->id);
338  unset($object->fk_user_creat);
339  unset($object->import_key);
340 
341  // Clear fields
342  $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default'];
343  $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
344  $object->status = self::STATUS_DRAFT;
345  // ...
346  // Clear extrafields that are unique
347  if (is_array($object->array_options) && count($object->array_options) > 0) {
348  $extrafields->fetch_name_optionals_label($this->table_element);
349  foreach ($object->array_options as $key => $option) {
350  $shortkey = preg_replace('/options_/', '', $key);
351  if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
352  //var_dump($key);
353  //var_dump($clonedObj->array_options[$key]); exit;
354  unset($object->array_options[$key]);
355  }
356  }
357  }
358 
359  // Create clone
360  $object->context['createfromclone'] = 'createfromclone';
361  $result = $object->createCommon($user);
362  if ($result < 0) {
363  $error++;
364  $this->error = $object->error;
365  $this->errors = $object->errors;
366  }
367 
368  if (!$error) {
369  // copy internal contacts
370  if ($this->copy_linked_contact($object, 'internal') < 0) {
371  $error++;
372  }
373  }
374 
375  if (!$error) {
376  // copy external contacts if same company
377  if (property_exists($this, 'socid') && $this->socid == $object->socid) {
378  if ($this->copy_linked_contact($object, 'external') < 0) {
379  $error++;
380  }
381  }
382  }
383 
384  unset($object->context['createfromclone']);
385 
386  // End
387  if (!$error) {
388  $this->db->commit();
389  return $object;
390  } else {
391  $this->db->rollback();
392  return -1;
393  }
394  }
395 
403  public function fetch($id, $ref = null)
404  {
405  $result = $this->fetchCommon($id, $ref);
406  if ($result > 0 && !empty($this->table_element_line)) {
407  $this->fetchLines();
408  }
409  return $result;
410  }
411 
417  public function fetchLines()
418  {
419  $this->lines = array();
420 
421  $result = $this->fetchLinesCommon();
422  return $result;
423  }
424 
425 
437  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
438  {
439  global $conf;
440 
441  dol_syslog(__METHOD__, LOG_DEBUG);
442 
443  $records = array();
444 
445  $sql = 'SELECT ';
446  $sql .= $this->getFieldList();
447  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
448  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
449  $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
450  } else {
451  $sql .= ' WHERE 1 = 1';
452  }
453  // Manage filter
454  $sqlwhere = array();
455  if (count($filter) > 0) {
456  foreach ($filter as $key => $value) {
457  if ($key == 't.rowid') {
458  $sqlwhere[] = $key." = ".((int) $value);
459  } elseif (strpos($key, 'date') !== false) {
460  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
461  } elseif ($key == 'customsql') {
462  $sqlwhere[] = $value;
463  } else {
464  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
465  }
466  }
467  }
468  if (count($sqlwhere) > 0) {
469  $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
470  }
471 
472  if (!empty($sortfield)) {
473  $sql .= $this->db->order($sortfield, $sortorder);
474  }
475  if (!empty($limit)) {
476  $sql .= $this->db->plimit($limit, $offset);
477  }
478 
479  $resql = $this->db->query($sql);
480  if ($resql) {
481  $num = $this->db->num_rows($resql);
482  $i = 0;
483  while ($i < min($limit, $num)) {
484  $obj = $this->db->fetch_object($resql);
485 
486  $record = new self($this->db);
487  $record->setVarsFromFetchObj($obj);
488 
489  $records[$record->id] = $record;
490 
491  $i++;
492  }
493  $this->db->free($resql);
494 
495  return $records;
496  } else {
497  $this->errors[] = 'Error '.$this->db->lasterror();
498  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
499 
500  return -1;
501  }
502  }
503 
511  public function fetchLinesLinked($role, $lineid = 0)
512  {
513  $resarray = array();
514  $mostatic = new MoLine($this->db);
515 
516  $sql = 'SELECT ';
517  $sql .= $mostatic->getFieldList();
518  $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t';
519  $sql .= " WHERE t.role = '".$this->db->escape($role)."'";
520  if ($lineid > 0) {
521  $sql .= ' AND t.fk_mrp_production = '.((int) $lineid);
522  } else {
523  $sql .= 'AND t.fk_mo = '.((int) $this->id);
524  }
525 
526  $resql = $this->db->query($sql);
527  if ($resql) {
528  $num = $this->db->num_rows($resql);
529 
530  $i = 0;
531  while ($i < $num) {
532  $obj = $this->db->fetch_object($resql);
533  if ($obj) {
534  $resarray[] = array(
535  'rowid'=> $obj->rowid,
536  'date'=> $this->db->jdate($obj->date_creation),
537  'qty' => $obj->qty,
538  'role' => $obj->role,
539  'fk_product' => $obj->fk_product,
540  'fk_warehouse' => $obj->fk_warehouse,
541  'batch' => $obj->batch,
542  'fk_stock_movement' => $obj->fk_stock_movement
543  );
544  }
545 
546  $i++;
547  }
548 
549  return $resarray;
550  } else {
551  $this->error = $this->db->lasterror();
552  return array();
553  }
554  }
555 
556 
562  public function countMovements()
563  {
564  $result = 0;
565 
566  $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'stock_mouvement as sm';
567  $sql .= " WHERE sm.origintype = 'mo' and sm.fk_origin = ".((int) $this->id);
568 
569  $resql = $this->db->query($sql);
570  if ($resql) {
571  $num = $this->db->num_rows($resql);
572 
573  $i = 0;
574  while ($i < $num) {
575  $obj = $this->db->fetch_object($resql);
576  if ($obj) {
577  $result = $obj->nb;
578  }
579 
580  $i++;
581  }
582  } else {
583  $this->error = $this->db->lasterror();
584  }
585 
586  return $result;
587  }
588 
589 
597  public function update(User $user, $notrigger = false)
598  {
599  global $langs;
600 
601  $error = 0;
602 
603  $this->db->begin();
604 
605  $result = $this->updateCommon($user, $notrigger);
606  if ($result <= 0) {
607  $error++;
608  }
609 
610  $result = $this->updateProduction($user, $notrigger);
611  if ($result <= 0) {
612  $error++;
613  }
614 
615  if (!$error) {
616  setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
617  $this->db->commit();
618  return 1;
619  } else {
620  setEventMessages($this->error, $this->errors, 'errors');
621  $this->db->rollback();
622  return -1;
623  }
624  }
625 
633  public function updateProduction(User $user, $notrigger = true)
634  {
635  $error = 0;
636  $role = "";
637 
638  if ($this->status != self::STATUS_DRAFT) {
639  $this->error = 'BadStatus';
640  return -1;
641  }
642 
643  $this->db->begin();
644 
645  // Insert lines in mrp_production table from BOM data
646  if (!$error) {
647  // TODO Check that production has not started. If yes, we stop here.
648 
649  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.((int) $this->id);
650  $this->db->query($sql);
651 
652  $moline = new MoLine($this->db);
653 
654  // Line to produce
655  $moline->fk_mo = $this->id;
656  $moline->qty = $this->qty;
657  $moline->fk_product = $this->fk_product;
658  $moline->position = 1;
659 
660  if ($this->fk_bom > 0) { // If a BOM is defined, we know what to produce.
661  include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
662  $bom = new Bom($this->db);
663  $bom->fetch($this->fk_bom);
664  if ($bom->bomtype == 1) {
665  $role = 'toproduce';
666  $moline->role = 'toconsume';
667  } else {
668  $role = 'toconsume';
669  $moline->role = 'toproduce';
670  }
671  } else {
672  if ($this->mrptype == 1) {
673  $moline->role = 'toconsume';
674  } else {
675  $moline->role = 'toproduce';
676  }
677  }
678 
679  $resultline = $moline->create($user, false); // Never use triggers here
680  if ($resultline <= 0) {
681  $error++;
682  $this->error = $moline->error;
683  $this->errors = $moline->errors;
684  dol_print_error($this->db, $moline->error, $moline->errors);
685  }
686 
687  if ($this->fk_bom > 0) { // If a BOM is defined, we know what to consume.
688  if ($bom->id > 0) {
689  // Lines to consume
690  if (!$error) {
691  foreach ($bom->lines as $line) {
692  $moline = new MoLine($this->db);
693 
694  $moline->fk_mo = $this->id;
695  $moline->origin_id = $line->id;
696  $moline->origin_type = 'bomline';
697  if ($line->qty_frozen) {
698  $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce
699  } else {
700  $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
701  }
702  if ($moline->qty <= 0) {
703  $error++;
704  $this->error = "BadValueForquantityToConsume";
705  break;
706  } else {
707  $moline->fk_product = $line->fk_product;
708  $moline->role = $role;
709  $moline->position = $line->position;
710  $moline->qty_frozen = $line->qty_frozen;
711  $moline->disable_stock_change = $line->disable_stock_change;
712 
713  $resultline = $moline->create($user, false); // Never use triggers here
714  if ($resultline <= 0) {
715  $error++;
716  $this->error = $moline->error;
717  $this->errors = $moline->errors;
718  dol_print_error($this->db, $moline->error, $moline->errors);
719  break;
720  }
721  }
722  }
723  }
724  }
725  }
726  }
727 
728  if (!$error) {
729  $this->db->commit();
730  return 1;
731  } else {
732  $this->db->rollback();
733  return -1;
734  }
735  }
736 
737 
745  public function delete(User $user, $notrigger = false)
746  {
747  return $this->deleteCommon($user, $notrigger);
748  //return $this->deleteCommon($user, $notrigger, 1);
749  }
750 
759  public function deleteLine(User $user, $idline, $notrigger = false)
760  {
761  global $langs;
762  $langs->load('stocks');
763 
764  if ($this->status < 0) {
765  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
766  return -2;
767  }
768 
769  $productstatic = new Product($this->db);
770  $fk_movement = GETPOST('fk_movement', 'int');
771  $arrayoflines = $this->fetchLinesLinked('consumed', $idline);
772 
773  if (! empty($arrayoflines)) {
774  $this->db->begin();
775 
776  $stockmove = new MouvementStock($this->db);
777  $stockmove->setOrigin($this->element, $this->id);
778 
779  if (! empty($fk_movement)) {
780  $moline = new MoLine($this->db);
781  $TArrayMoLine = $moline->fetchAll('', '', 1, 0, array('customsql' => 'fk_stock_movement ='.$fk_movement));
782  $moline = array_shift($TArrayMoLine);
783 
784  $movement = new MouvementStock($this->db);
785  $movement->fetch($fk_movement);
786  $productstatic->fetch($movement->product_id);
787  $qtytoprocess = $movement->qty;
788 
789  // Reverse stock movement
790  $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
791  $codemovementCancel = $langs->trans("StockIncrease");
792 
793  if (($qtytoprocess >= 0)) {
794  $idstockmove = $stockmove->reception($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, '', '', $movement->batch, dol_now(), 0, $codemovementCancel);
795  } else {
796  $idstockmove = $stockmove->livraison($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $movement->batch, 0, $codemovementCancel);
797  }
798  if ($idstockmove < 0) {
799  $this->error++;
800  $this->db->rollback();
801  setEventMessages($stockmove->error, $stockmove->errors, 'errors');
802  } else {
803  $this->db->commit();
804  }
805  return $moline->delete($user, $notrigger);
806  } else {
807  foreach ($arrayoflines as $key => $arrayofline) {
808  $lineDetails = $arrayoflines[$key];
809  $productstatic->fetch($lineDetails['fk_product']);
810  $qtytoprocess = $lineDetails['qty'];
811 
812  // Reverse stock movement
813  $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
814  $codemovementCancel = $langs->trans("StockIncrease");
815 
816  if ($qtytoprocess >= 0) {
817  $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
818  } else {
819  $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
820  }
821  if ($idstockmove < 0) {
822  $this->error++;
823  $this->db->rollback();
824  setEventMessages($stockmove->error, $stockmove->errors, 'errors');
825  } else {
826  $this->db->commit();
827  }
828  }
829  return $this->deleteLineCommon($user, $idline, $notrigger);
830  }
831  } else {
832  return $this->deleteLineCommon($user, $idline, $notrigger);
833  }
834  }
835 
836 
844  public function getNextNumRef($prod)
845  {
846  global $langs, $conf;
847  $langs->load("mrp");
848 
849  if (!empty($conf->global->MRP_MO_ADDON)) {
850  $mybool = false;
851 
852  $file = $conf->global->MRP_MO_ADDON.".php";
853  $classname = $conf->global->MRP_MO_ADDON;
854 
855  // Include file with class
856  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
857  foreach ($dirmodels as $reldir) {
858  $dir = dol_buildpath($reldir."core/modules/mrp/");
859 
860  // Load file with numbering class (if found)
861  $mybool |= @include_once $dir.$file;
862  }
863 
864  if ($mybool === false) {
865  dol_print_error('', "Failed to include file ".$file);
866  return '';
867  }
868 
869  $obj = new $classname();
870  $numref = $obj->getNextValue($prod, $this);
871 
872  if ($numref != "") {
873  return $numref;
874  } else {
875  $this->error = $obj->error;
876  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
877  return "";
878  }
879  } else {
880  print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
881  return "";
882  }
883  }
884 
892  public function validate($user, $notrigger = 0)
893  {
894  global $conf, $langs;
895 
896  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
897 
898  $error = 0;
899 
900  // Protection
901  if ($this->status == self::STATUS_VALIDATED) {
902  dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
903  return 0;
904  }
905 
906  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mrp->create))
907  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mrp->mrp_advance->validate))))
908  {
909  $this->error='NotEnoughPermissions';
910  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
911  return -1;
912  }*/
913 
914  $now = dol_now();
915 
916  $this->db->begin();
917 
918  // Define new ref
919  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
920  $this->fetch_product();
921  $num = $this->getNextNumRef($this->product);
922  } else {
923  $num = $this->ref;
924  }
925  $this->newref = $num;
926 
927  // Validate
928  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
929  $sql .= " SET ref = '".$this->db->escape($num)."',";
930  $sql .= " status = ".self::STATUS_VALIDATED.",";
931  $sql .= " date_valid='".$this->db->idate($now)."',";
932  $sql .= " fk_user_valid = ".$user->id;
933  $sql .= " WHERE rowid = ".((int) $this->id);
934 
935  dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
936  $resql = $this->db->query($sql);
937  if (!$resql) {
938  dol_print_error($this->db);
939  $this->error = $this->db->lasterror();
940  $error++;
941  }
942 
943  if (!$error && !$notrigger) {
944  // Call trigger
945  $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
946  if ($result < 0) {
947  $error++;
948  }
949  // End call triggers
950  }
951 
952  if (!$error) {
953  $this->oldref = $this->ref;
954 
955  // Rename directory if dir was a temporary ref
956  if (preg_match('/^[\(]?PROV/i', $this->ref)) {
957  // Now we rename also files into index
958  $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)."'";
959  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
960  $resql = $this->db->query($sql);
961  if (!$resql) {
962  $error++; $this->error = $this->db->lasterror();
963  }
964 
965  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
966  $oldref = dol_sanitizeFileName($this->ref);
967  $newref = dol_sanitizeFileName($num);
968  $dirsource = $conf->mrp->dir_output.'/'.$oldref;
969  $dirdest = $conf->mrp->dir_output.'/'.$newref;
970  if (!$error && file_exists($dirsource)) {
971  dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
972 
973  if (@rename($dirsource, $dirdest)) {
974  dol_syslog("Rename ok");
975  // Rename docs starting with $oldref with $newref
976  $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
977  foreach ($listoffiles as $fileentry) {
978  $dirsource = $fileentry['name'];
979  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
980  $dirsource = $fileentry['path'].'/'.$dirsource;
981  $dirdest = $fileentry['path'].'/'.$dirdest;
982  @rename($dirsource, $dirdest);
983  }
984  }
985  }
986  }
987  }
988 
989  // Set new ref and current status
990  if (!$error) {
991  $this->ref = $num;
992  $this->status = self::STATUS_VALIDATED;
993  }
994 
995  if (!$error) {
996  $this->db->commit();
997  return 1;
998  } else {
999  $this->db->rollback();
1000  return -1;
1001  }
1002  }
1003 
1011  public function setDraft($user, $notrigger = 0)
1012  {
1013  // Protection
1014  if ($this->status <= self::STATUS_DRAFT) {
1015  return 0;
1016  }
1017 
1018  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
1019  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
1020  {
1021  $this->error='Permission denied';
1022  return -1;
1023  }*/
1024 
1025  return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MRP_MO_UNVALIDATE');
1026  }
1027 
1035  public function cancel($user, $notrigger = 0)
1036  {
1037  // Protection
1038  if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) {
1039  return 0;
1040  }
1041 
1042  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
1043  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
1044  {
1045  $this->error='Permission denied';
1046  return -1;
1047  }*/
1048 
1049  return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MRP_MO_CANCEL');
1050  }
1051 
1059  public function reopen($user, $notrigger = 0)
1060  {
1061  // Protection
1062  if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) {
1063  return 0;
1064  }
1065 
1066  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
1067  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
1068  {
1069  $this->error='Permission denied';
1070  return -1;
1071  }*/
1072 
1073  return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MRP_MO_REOPEN');
1074  }
1075 
1086  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1087  {
1088  global $conf, $langs, $hookmanager;
1089 
1090  if (!empty($conf->dol_no_mouse_hover)) {
1091  $notooltip = 1; // Force disable tooltips
1092  }
1093 
1094  $result = '';
1095 
1096  $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ManufacturingOrder").'</u>';
1097  if (isset($this->status)) {
1098  $label .= ' '.$this->getLibStatut(5);
1099  }
1100  $label .= '<br>';
1101  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
1102  if (isset($this->label)) {
1103  $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1104  }
1105 
1106  $url = DOL_URL_ROOT.'/mrp/mo_card.php?id='.$this->id;
1107  if ($option == 'production') {
1108  $url = DOL_URL_ROOT.'/mrp/mo_production.php?id='.$this->id;
1109  }
1110 
1111  if ($option != 'nolink') {
1112  // Add param to save lastsearch_values or not
1113  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1114  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1115  $add_save_lastsearch_values = 1;
1116  }
1117  if ($add_save_lastsearch_values) {
1118  $url .= '&save_lastsearch_values=1';
1119  }
1120  }
1121 
1122  $linkclose = '';
1123  if (empty($notooltip)) {
1124  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
1125  $label = $langs->trans("ShowMo");
1126  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1127  }
1128  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1129  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1130  } else {
1131  $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1132  }
1133 
1134  $linkstart = '<a href="'.$url.'"';
1135  $linkstart .= $linkclose.'>';
1136  $linkend = '</a>';
1137 
1138  $result .= $linkstart;
1139  if ($withpicto) {
1140  $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);
1141  }
1142  if ($withpicto != 2) {
1143  $result .= $this->ref;
1144  }
1145  $result .= $linkend;
1146  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1147 
1148  global $action, $hookmanager;
1149  $hookmanager->initHooks(array('modao'));
1150  $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
1151  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1152  if ($reshook > 0) {
1153  $result = $hookmanager->resPrint;
1154  } else {
1155  $result .= $hookmanager->resPrint;
1156  }
1157 
1158  return $result;
1159  }
1160 
1167  public function getLibStatut($mode = 0)
1168  {
1169  return $this->LibStatut($this->status, $mode);
1170  }
1171 
1172  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1180  public function LibStatut($status, $mode = 0)
1181  {
1182  // phpcs:enable
1183  if (empty($this->labelStatus)) {
1184  global $langs;
1185  //$langs->load("mrp");
1186  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1187  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatedToProduce');
1188  $this->labelStatus[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1189  $this->labelStatus[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1190  $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1191 
1192  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1193  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
1194  $this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1195  $this->labelStatusShort[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1196  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1197  }
1198 
1199  $statusType = 'status'.$status;
1200  if ($status == self::STATUS_VALIDATED) {
1201  $statusType = 'status1';
1202  }
1203  if ($status == self::STATUS_INPROGRESS) {
1204  $statusType = 'status4';
1205  }
1206  if ($status == self::STATUS_PRODUCED) {
1207  $statusType = 'status6';
1208  }
1209  if ($status == self::STATUS_CANCELED) {
1210  $statusType = 'status9';
1211  }
1212 
1213  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1214  }
1215 
1222  public function info($id)
1223  {
1224  $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1225  $sql .= ' fk_user_creat, fk_user_modif';
1226  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1227  $sql .= ' WHERE t.rowid = '.((int) $id);
1228  $result = $this->db->query($sql);
1229  if ($result) {
1230  if ($this->db->num_rows($result)) {
1231  $obj = $this->db->fetch_object($result);
1232  $this->id = $obj->rowid;
1233 
1234  $this->user_creation_id = $obj->fk_user_creat;
1235  $this->user_modification_id = $obj->fk_user_modif;
1236  $this->date_creation = $this->db->jdate($obj->datec);
1237  $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1238  }
1239 
1240  $this->db->free($result);
1241  } else {
1242  dol_print_error($this->db);
1243  }
1244  }
1245 
1252  public function initAsSpecimen()
1253  {
1254  $this->initAsSpecimenCommon();
1255 
1256  $this->lines = array();
1257  }
1258 
1264  public function getLinesArray($rolefilter = '')
1265  {
1266  $this->lines = array();
1267 
1268  $objectline = new MoLine($this->db);
1269 
1270  $TFilters = array('customsql'=>'fk_mo = '.((int) $this->id));
1271  if (!empty($rolefilter)) $TFilters['role'] = $rolefilter;
1272  $result = $objectline->fetchAll('ASC', 'position', 0, 0, $TFilters);
1273 
1274  if (is_numeric($result)) {
1275  $this->error = $this->error;
1276  $this->errors = $this->errors;
1277  return $result;
1278  } else {
1279  $this->lines = $result;
1280  return $this->lines;
1281  }
1282  }
1283 
1295  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1296  {
1297  global $conf, $langs;
1298 
1299  $langs->load("mrp");
1300 
1301  if (!dol_strlen($modele)) {
1302  //$modele = 'standard';
1303  $modele = ''; // Remove this once a pdf_standard.php exists.
1304 
1305  if ($this->model_pdf) {
1306  $modele = $this->model_pdf;
1307  } elseif (!empty($conf->global->MO_ADDON_PDF)) {
1308  $modele = $conf->global->MO_ADDON_PDF;
1309  }
1310  }
1311 
1312  $modelpath = "core/modules/mrp/doc/";
1313 
1314  if (empty($modele)) {
1315  return 1; // Remove this once a pdf_standard.php exists.
1316  }
1317 
1318  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1319  }
1320 
1328  public function doScheduledJob()
1329  {
1330  global $conf, $langs;
1331 
1332  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1333 
1334  $error = 0;
1335  $this->output = '';
1336  $this->error = '';
1337 
1338  dol_syslog(__METHOD__, LOG_DEBUG);
1339 
1340  $now = dol_now();
1341 
1342  $this->db->begin();
1343 
1344  // ...
1345 
1346  $this->db->commit();
1347 
1348  return $error;
1349  }
1350 
1361  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
1362  {
1363  global $langs, $hookmanager, $conf, $form;
1364 
1365  $langs->load('stocks');
1366  $text_stock_options = $langs->trans("RealStockDesc").'<br>';
1367  $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen").'<br>';
1368  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT) || !empty($conf->global->STOCK_CALCULATE_ON_SHIPMENT_CLOSE) ? '- '.$langs->trans("DeStockOnShipment").'<br>' : '');
1369  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_VALIDATE_ORDER) ? '- '.$langs->trans("DeStockOnValidateOrder").'<br>' : '');
1370  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_BILL) ? '- '.$langs->trans("DeStockOnBill").'<br>' : '');
1371  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_BILL) ? '- '.$langs->trans("ReStockOnBill").'<br>' : '');
1372  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER) ? '- '.$langs->trans("ReStockOnValidateOrder").'<br>' : '');
1373  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER) ? '- '.$langs->trans("ReStockOnDispatchOrder").'<br>' : '');
1374  $text_stock_options .= (!empty($conf->global->STOCK_CALCULATE_ON_RECEPTION) || !empty($conf->global->STOCK_CALCULATE_ON_RECEPTION_CLOSE) ? '- '.$langs->trans("StockOnReception").'<br>' : '');
1375 
1376  print '<tr class="liste_titre">';
1377  // Product or sub-bom
1378  print '<td class="linecoldescription">'.$langs->trans('Ref');
1379  if (!empty($conf->global->BOM_SUB_BOM)) {
1380  print ' &nbsp; <a id="show_all" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a>&nbsp;&nbsp;';
1381  print '<a id="hide_all" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a>&nbsp;';
1382  }
1383  print '</td>';
1384  // Qty
1385  print '<td class="right">'.$langs->trans('Qty');
1386  if ($this->bom->bomtype == 0) {
1387  print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityOf", $this->bom->qty).')</span>';
1388  } else {
1389  print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityToConsumeOf", $this->bom->qty).')</span>';
1390  }
1391  print '</td>';
1392  print '<td class="center">'.$form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1).'</td>';
1393  print '<td class="center">'.$form->textwithpicto($langs->trans("VirtualStock"), $langs->trans("VirtualStockDesc")).'</td>';
1394  print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
1395  print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
1396  print '<td class="center">'.$langs->trans('MoChildGenerate').'</td>';
1397  //print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
1398  //print '<td class="center"></td>';
1399  print '</tr>';
1400  $i = 0;
1401 
1402  if (!empty($this->lines)) {
1403  foreach ($this->lines as $line) {
1404  $reshook = 0;
1405  if (is_object($hookmanager)) {
1406  $parameters = array('line'=>$line, 'i'=>$i, 'restrictlist'=>$restrictlist, 'selectedLines'=> $selectedLines);
1407  if (!empty($line->fk_parent_line)) { $parameters['fk_parent_line'] = $line->fk_parent_line; }
1408  $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1409  }
1410  if (empty($reshook)) {
1411  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
1412  }
1413 
1414  $i++;
1415  }
1416  }
1417  }
1418 
1419 
1433  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
1434  {
1435  global $langs, $conf;
1436 
1437  $this->tpl['id'] = $line->id;
1438 
1439  $this->tpl['label'] = '';
1440  if (!empty($line->fk_product)) {
1441  $productstatic = new Product($this->db);
1442  $productstatic->fetch($line->fk_product);
1443  $productstatic->load_virtual_stock();
1444  $this->tpl['label'] .= $productstatic->getNomUrl(1);
1445  //$this->tpl['label'].= ' - '.$productstatic->label;
1446  } else {
1447  // If origin MRP line is not a product, but another MRP
1448  // TODO
1449  }
1450 
1451  $this->tpl['qty_bom'] = 1;
1452  if (is_object($this->bom) && $this->bom->qty > 1) {
1453  $this->tpl['qty_bom'] = $this->bom->qty;
1454  }
1455 
1456  $this->tpl['stock'] = $productstatic->stock_reel;
1457  $this->tpl['seuil_stock_alerte'] = $productstatic->seuil_stock_alerte;
1458  $this->tpl['virtual_stock'] = $productstatic->stock_theorique;
1459  $this->tpl['qty'] = $line->qty;
1460  $this->tpl['qty_frozen'] = $line->qty_frozen;
1461  $this->tpl['disable_stock_change'] = $line->disable_stock_change;
1462  $this->tpl['efficiency'] = $line->efficiency;
1463 
1464  $tpl = DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
1465  $res = include $tpl;
1466  }
1467 
1476  public static function replaceThirdparty($db, $origin_id, $dest_id)
1477  {
1478  $tables = array('mrp_mo');
1479 
1480  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1481  }
1482 
1483 
1489  public function getMoChilds()
1490  {
1491 
1492  $TMoChilds = array();
1493  $error = 0;
1494 
1495  $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_mo as mo_child";
1496  $sql.= " WHERE fk_parent_line IN ";
1497  $sql.= " (SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_production as line_parent";
1498  $sql.= " WHERE fk_mo=".((int) $this->id).")";
1499 
1500  $resql = $this->db->query($sql);
1501 
1502  if ($resql) {
1503  if ($this->db->num_rows($resql) > 0) {
1504  while ($obj = $this->db->fetch_object($resql)) {
1505  $MoChild = new Mo($this->db);
1506  $res = $MoChild->fetch($obj->rowid);
1507  if ($res > 0) $TMoChilds[$MoChild->id] = $MoChild;
1508  else $error++;
1509  }
1510  }
1511  } else {
1512  $error++;
1513  }
1514 
1515  if ($error) {
1516  return -1;
1517  } else {
1518  return $TMoChilds;
1519  }
1520  }
1521 
1527  public function getMoParent()
1528  {
1529 
1530  $MoParent = new Mo($this->db);
1531  $error = 0;
1532 
1533  $sql = "SELECT lineparent.fk_mo as id_moparent FROM ".MAIN_DB_PREFIX."mrp_mo as mo";
1534  $sql.= " LEFT JOIN ".MAIN_DB_PREFIX."mrp_production lineparent ON mo.fk_parent_line = lineparent.rowid";
1535  $sql.= " WHERE mo.rowid = ".((int) $this->id);
1536 
1537  $resql = $this->db->query($sql);
1538 
1539  if ($resql) {
1540  if ($this->db->num_rows($resql) > 0) {
1541  $obj = $this->db->fetch_object($resql);
1542  $res = $MoParent->fetch($obj->id_moparent);
1543  if ($res < 0) $error++;
1544  } else {
1545  return 0;
1546  }
1547  } else {
1548  $error++;
1549  }
1550 
1551  if ($error) {
1552  return -1;
1553  } else {
1554  return $MoParent;
1555  }
1556  }
1557 }
1558 
1563 {
1567  public $element = 'mrp_production';
1568 
1572  public $table_element = 'mrp_production';
1573 
1577  public $ismultientitymanaged = 0;
1578 
1582  public $isextrafieldmanaged = 0;
1583 
1584  public $fields = array(
1585  'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
1586  'fk_mo' =>array('type'=>'integer', 'label'=>'Mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
1587  'origin_id' =>array('type'=>'integer', 'label'=>'Origin', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>17),
1588  'origin_type' =>array('type'=>'varchar(10)', 'label'=>'Origin type', 'enabled'=>1, 'visible'=>-1, 'notnull'=>0, 'position'=>18),
1589  'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
1590  'fk_product' =>array('type'=>'integer', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
1591  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
1592  'qty' =>array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
1593  'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
1594  'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
1595  'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
1596  'role' =>array('type'=>'varchar(10)', 'label'=>'Role', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
1597  'fk_mrp_production' =>array('type'=>'integer', 'label'=>'Fk mrp production', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
1598  'fk_stock_movement' =>array('type'=>'integer', 'label'=>'StockMovement', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
1599  'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>160),
1600  'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>165),
1601  'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>170),
1602  'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModification', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
1603  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
1604  );
1605 
1606  public $rowid;
1607  public $fk_mo;
1608  public $origin_id;
1609  public $origin_type;
1610  public $position;
1611  public $fk_product;
1612  public $fk_warehouse;
1613  public $qty;
1614  public $qty_frozen;
1615  public $disable_stock_change;
1616  public $batch;
1617  public $role;
1618  public $fk_mrp_production;
1619  public $fk_stock_movement;
1620  public $date_creation;
1621  public $tms;
1622  public $fk_user_creat;
1623  public $fk_user_modif;
1624  public $import_key;
1625 
1631  public function __construct(DoliDB $db)
1632  {
1633  global $conf, $langs;
1634 
1635  $this->db = $db;
1636 
1637  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
1638  $this->fields['rowid']['visible'] = 0;
1639  }
1640  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
1641  $this->fields['entity']['enabled'] = 0;
1642  }
1643 
1644  // Unset fields that are disabled
1645  foreach ($this->fields as $key => $val) {
1646  if (isset($val['enabled']) && empty($val['enabled'])) {
1647  unset($this->fields[$key]);
1648  }
1649  }
1650 
1651  // Translate some data of arrayofkeyval
1652  if (is_object($langs)) {
1653  foreach ($this->fields as $key => $val) {
1654  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
1655  foreach ($val['arrayofkeyval'] as $key2 => $val2) {
1656  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
1657  }
1658  }
1659  }
1660  }
1661  }
1662 
1670  public function create(User $user, $notrigger = false)
1671  {
1672  if (empty($this->qty)) {
1673  $this->error = 'BadValueForQty';
1674  return -1;
1675  }
1676 
1677  return $this->createCommon($user, $notrigger);
1678  }
1679 
1687  public function fetch($id, $ref = null)
1688  {
1689  $result = $this->fetchCommon($id, $ref);
1690  return $result;
1691  }
1692 
1704  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
1705  {
1706  global $conf;
1707 
1708  dol_syslog(__METHOD__, LOG_DEBUG);
1709 
1710  $records = array();
1711 
1712  $sql = 'SELECT ';
1713  $sql .= $this->getFieldList();
1714  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1715  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
1716  $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
1717  } else {
1718  $sql .= ' WHERE 1 = 1';
1719  }
1720  // Manage filter
1721  $sqlwhere = array();
1722  if (count($filter) > 0) {
1723  foreach ($filter as $key => $value) {
1724  if ($key == 't.rowid') {
1725  $sqlwhere[] = $key." = ".((int) $value);
1726  } elseif (strpos($key, 'date') !== false) {
1727  $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
1728  } elseif ($key == 'customsql') {
1729  $sqlwhere[] = $value;
1730  } else {
1731  $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
1732  }
1733  }
1734  }
1735  if (count($sqlwhere) > 0) {
1736  $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
1737  }
1738 
1739  if (!empty($sortfield)) {
1740  $sql .= $this->db->order($sortfield, $sortorder);
1741  }
1742  if (!empty($limit)) {
1743  $sql .= $this->db->plimit($limit, $offset);
1744  }
1745 
1746  $resql = $this->db->query($sql);
1747  if ($resql) {
1748  $num = $this->db->num_rows($resql);
1749  $i = 0;
1750  while ($i < ($limit ? min($limit, $num) : $num)) {
1751  $obj = $this->db->fetch_object($resql);
1752 
1753  $record = new self($this->db);
1754  $record->setVarsFromFetchObj($obj);
1755 
1756  $records[$record->id] = $record;
1757 
1758  $i++;
1759  }
1760  $this->db->free($resql);
1761 
1762  return $records;
1763  } else {
1764  $this->errors[] = 'Error '.$this->db->lasterror();
1765  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1766 
1767  return -1;
1768  }
1769  }
1770 
1778  public function update(User $user, $notrigger = false)
1779  {
1780  return $this->updateCommon($user, $notrigger);
1781  }
1782 
1790  public function delete(User $user, $notrigger = false)
1791  {
1792  return $this->deleteCommon($user, $notrigger);
1793  //return $this->deleteCommon($user, $notrigger, 1);
1794  }
1795 }
CommonObject\deleteCommon
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
Definition: commonobject.class.php:9406
CommonObject\setStatusCommon
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
Definition: commonobject.class.php:9683
Mo\getNomUrl
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionaly the picto)
Definition: mo.class.php:1086
db
$conf db
API class for accounts.
Definition: inc.php:41
CommonObject\fetchCommon
fetchCommon($id, $ref=null, $morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9202
dol_sanitizeFileName
dol_sanitizeFileName($str, $newstr='_', $unaccent=1)
Clean a string to use it as a file name.
Definition: functions.lib.php:1226
CommonObject\copy_linked_contact
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
Definition: commonobject.class.php:1217
Mo\doScheduledJob
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
Definition: mo.class.php:1328
MoLine\__construct
__construct(DoliDB $db)
Constructor.
Definition: mo.class.php:1631
DoliDB
Class to manage Dolibarr database access.
Definition: DoliDB.class.php:30
GETPOST
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Definition: functions.lib.php:484
dol_print_error
dol_print_error($db='', $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
Definition: functions.lib.php:4844
Mo\printOriginLinesList
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
Definition: mo.class.php:1361
MoLine
Class MoLine.
Definition: mo.class.php:1562
dol_buildpath
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Definition: functions.lib.php:1062
CommonObject\fetchLinesCommon
fetchLinesCommon($morewhere='')
Load object in memory from the database.
Definition: commonobject.class.php:9258
ref
$object ref
Definition: info.php:77
$form
if($cancel &&! $id) if($action=='add' &&! $cancel) if($action=='delete') if($id) $form
Actions.
Definition: card.php:142
Mo\getNextNumRef
getNextNumRef($prod)
Returns the reference to the following non used MO depending on the active numbering module defined i...
Definition: mo.class.php:844
Mo\__construct
__construct(DoliDB $db)
Constructor.
Definition: mo.class.php:218
Mo\setDraft
setDraft($user, $notrigger=0)
Set draft status.
Definition: mo.class.php:1011
dol_dir_list
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:60
CommonObject\initAsSpecimenCommon
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: commonobject.class.php:9733
Mo\getMoParent
getMoParent()
Function used to return childs of Mo.
Definition: mo.class.php:1527
Mo
Class for Mo.
Definition: mo.class.php:35
CommonObjectLine
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
Definition: commonobjectline.class.php:32
CommonObject
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Definition: commonobject.class.php:44
Mo\fetchAll
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter=array(), $filtermode='AND')
Load list of objects in memory from the database.
Definition: mo.class.php:437
BOM
Class for BOM.
Definition: bom.class.php:34
price2num
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
Definition: functions.lib.php:5661
img_picto
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
Definition: functions.lib.php:3880
CommonObject\commonGenerateDocument
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
Definition: commonobject.class.php:5406
Mo\update
update(User $user, $notrigger=false)
Update object into database.
Definition: mo.class.php:597
CommonObject\createCommon
createCommon(User $user, $notrigger=false)
Create object into database.
Definition: commonobject.class.php:9035
Mo\getMoChilds
getMoChilds()
Function used to return childs of Mo.
Definition: mo.class.php:1489
MoLine\update
update(User $user, $notrigger=false)
Update object into database.
Definition: mo.class.php:1778
Mo\generateDocument
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: mo.class.php:1295
Mo\createFromClone
createFromClone(User $user, $fromid)
Clone an object into another one.
Definition: mo.class.php:315
MouvementStock
Class to manage stock movements.
Definition: mouvementstock.class.php:31
Mo\fetchLines
fetchLines()
Load object lines in memory from the database.
Definition: mo.class.php:417
Mo\getLinesArray
getLinesArray($rolefilter='')
Create an array of lines.
Definition: mo.class.php:1264
Mo\updateProduction
updateProduction(User $user, $notrigger=true)
Erase and update the line to consume and to produce.
Definition: mo.class.php:633
CommonObject\commonReplaceThirdparty
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
Definition: commonobject.class.php:8347
Mo\deleteLine
deleteLine(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: mo.class.php:759
dol_syslog
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
Definition: functions.lib.php:1603
Mo\printOriginLine
printOriginLine($line, $var, $restrictlist='', $defaulttpldir='/core/tpl', $selectedLines=array())
Return HTML with a line of table array of source object lines TODO Move this and previous function in...
Definition: mo.class.php:1433
Mo\LibStatut
LibStatut($status, $mode=0)
Return the status.
Definition: mo.class.php:1180
Mo\getLibStatut
getLibStatut($mode=0)
Return label of the status.
Definition: mo.class.php:1167
Mo\replaceThirdparty
static replaceThirdparty($db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: mo.class.php:1476
MoLine\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: mo.class.php:1687
CommonObject\updateCommon
updateCommon(User $user, $notrigger=false)
Update object into database.
Definition: commonobject.class.php:9308
dol_strlen
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
Definition: functions.lib.php:3747
MoLine\fetchAll
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, array $filter=array(), $filtermode='AND')
Load list of objects in memory from the database.
Definition: mo.class.php:1704
Mo\reopen
reopen($user, $notrigger=0)
Set back to validated status.
Definition: mo.class.php:1059
Mo\info
info($id)
Load the info information in the object.
Definition: mo.class.php:1222
CommonObject\fetch_product
fetch_product()
Load the product with id $this->fk_product into this->product.
Definition: commonobject.class.php:1891
User
Class to manage Dolibarr users.
Definition: user.class.php:44
Mo\create
create(User $user, $notrigger=false)
Create object into database.
Definition: mo.class.php:255
Mo\validate
validate($user, $notrigger=0)
Validate Mo.
Definition: mo.class.php:892
Mo\fetchLinesLinked
fetchLinesLinked($role, $lineid=0)
Get list of lines linked to current line for a defined role.
Definition: mo.class.php:511
Product
Class to manage products or services.
Definition: product.class.php:46
dolGetStatus
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
Definition: functions.lib.php:10338
Mo\fetch
fetch($id, $ref=null)
Load object in memory from the database.
Definition: mo.class.php:403
img_object
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
Definition: functions.lib.php:4211
Mo\cancel
cancel($user, $notrigger=0)
Set cancel status.
Definition: mo.class.php:1035
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
$resql
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->rights->fournisseur->facture->lire)||(isModEnabled('supplier_invoice') && $user->rights->supplier_invoice->lire)) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:742
Mo\countMovements
countMovements()
Count number of movement with origin of MO.
Definition: mo.class.php:562
CommonObject\deleteLineCommon
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: commonobject.class.php:9622
CommonObject\call_trigger
call_trigger($triggerName, $user)
Call trigger based on this instance.
Definition: commonobject.class.php:5791
setEventMessages
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='')
Set event messages in dol_events session object.
Definition: functions.lib.php:8137
MoLine\create
create(User $user, $notrigger=false)
Create object into database.
Definition: mo.class.php:1670
CommonObject\getFieldList
getFieldList($alias='')
Function to concat keys of fields.
Definition: commonobject.class.php:8987
Mo\initAsSpecimen
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: mo.class.php:1252