dolibarr  13.0.2
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 . '/societe/class/societe.class.php';
29 //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
30 
34 class Mo extends CommonObject
35 {
39  public $element = 'mo';
40 
44  public $table_element = 'mrp_mo';
45 
49  public $ismultientitymanaged = 0;
50 
54  public $isextrafieldmanaged = 1;
55 
59  public $picto = 'mrp';
60 
61 
62  const STATUS_DRAFT = 0;
63  const STATUS_VALIDATED = 1; // To produce
64  const STATUS_INPROGRESS = 2;
65  const STATUS_PRODUCED = 3;
66  const STATUS_CANCELED = 9;
67 
68 
69 
91  // BEGIN MODULEBUILDER PROPERTIES
95  public $fields = array(
96  'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>"Id",),
97  'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'position'=>5, 'notnull'=>1, 'default'=>'1', 'index'=>1),
98  '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),
99  'fk_bom' => array('type'=>'integer:Bom:bom/class/bom.class.php:0:t.status=1', 'filter'=>'active=1', 'label'=>'BOM', 'enabled'=>1, 'visible'=>1, 'position'=>33, 'notnull'=>-1, 'index'=>1, 'comment'=>"Original BOM", 'css'=>'minwidth100 maxwidth300'),
100  'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:0', 'label'=>'Product', 'enabled'=>1, 'visible'=>1, 'position'=>35, 'notnull'=>1, 'index'=>1, 'comment'=>"Product to produce", 'css'=>'maxwidth300', 'picto'=>'product'),
101  'qty' => array('type'=>'real', 'label'=>'QtyToProduce', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'notnull'=>1, 'comment'=>"Qty to produce", 'css'=>'width75', 'default'=>1, 'isameasure'=>1),
102  'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>1, 'position'=>42, 'notnull'=>-1, 'searchall'=>1, 'showoncombobox'=>'1',),
103  'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php:1', 'label'=>'ThirdParty', 'picto'=>'company', 'enabled'=>1, 'visible'=>-1, 'position'=>50, 'notnull'=>-1, 'index'=>1, 'css'=>'maxwidth400'),
104  'fk_project' => array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Project', 'picto'=>'project', 'enabled'=>1, 'visible'=>-1, 'position'=>51, 'notnull'=>-1, 'index'=>1, 'css'=>'minwidth200 maxwidth400'),
105  'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label'=>'WarehouseForProduction', 'picto'=>'stock', 'enabled'=>1, 'visible'=>1, 'position'=>52, 'css'=>'maxwidth400'),
106  'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>1, 'visible'=>0, 'position'=>61, 'notnull'=>-1,),
107  'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>1, 'visible'=>0, 'position'=>62, 'notnull'=>-1,),
108  'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>500, 'notnull'=>1,),
109  'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'position'=>501, 'notnull'=>1,),
110  'date_valid' => array('type'=>'datetime', 'label'=>'DateValidation', 'enabled'=>1, 'visible'=>-2, 'position'=>502,),
111  'fk_user_creat' => array('type'=>'integer', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'position'=>510, 'notnull'=>1, 'foreignkey'=>'user.rowid',),
112  'fk_user_modif' => array('type'=>'integer', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'position'=>511, 'notnull'=>-1,),
113  'date_start_planned' => array('type'=>'datetime', 'label'=>'DateStartPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>55, 'notnull'=>-1, 'index'=>1, 'help'=>'KeepEmptyForAsap'),
114  'date_end_planned' => array('type'=>'datetime', 'label'=>'DateEndPlannedMo', 'enabled'=>1, 'visible'=>1, 'position'=>56, 'notnull'=>-1, 'index'=>1,),
115  'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000, 'notnull'=>-1,),
116  'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
117  'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>1, 'visible'=>2, 'position'=>1000, 'default'=>0, 'notnull'=>1, 'index'=>1, 'arrayofkeyval'=>array('0'=>'Brouillon', '1'=>'Validated', '2'=>'InProgress', '3'=>'StatusMOProduced', '9'=>'Canceled')),
118  );
119  public $rowid;
120  public $ref;
121  public $entity;
122  public $label;
123  public $qty;
124  public $fk_warehouse;
125  public $fk_soc;
126 
130  public $note_public;
131 
135  public $note_private;
136 
140  public $date_creation;
141 
142 
143  public $tms;
144  public $fk_user_creat;
145  public $fk_user_modif;
146  public $import_key;
147  public $status;
148  public $fk_product;
149 
153  public $date_start_planned;
154 
158  public $date_end_planned;
159 
160 
161  public $fk_bom;
162  public $fk_project;
163  // END MODULEBUILDER PROPERTIES
164 
165 
166  // If this object has a subtable with lines
167 
171  public $table_element_line = 'mo_production';
172 
176  public $fk_element = 'fk_mo';
177 
181  public $class_element_line = 'MoLine';
182 
186  protected $childtables = array();
187 
191  protected $childtablesoncascade = array('mrp_production');
192 
196  public $lines = array();
197 
198 
199 
205  public function __construct(DoliDB $db)
206  {
207  global $conf, $langs;
208 
209  $this->db = $db;
210 
211  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
212  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
213 
214  // Unset fields that are disabled
215  foreach ($this->fields as $key => $val)
216  {
217  if (isset($val['enabled']) && empty($val['enabled']))
218  {
219  unset($this->fields[$key]);
220  }
221  }
222 
223  // Translate some data of arrayofkeyval
224  foreach ($this->fields as $key => $val)
225  {
226  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
227  {
228  foreach ($val['arrayofkeyval'] as $key2 => $val2)
229  {
230  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
231  }
232  }
233  }
234  }
235 
243  public function create(User $user, $notrigger = false)
244  {
245  global $conf;
246 
247  $error = 0;
248  $idcreated = 0;
249 
250  $this->db->begin();
251 
252  if ($this->fk_product > 0) {
253  include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
254  $tmpproduct = new Product($this->db);
255  $tmpproduct->fetch($this->fk_product);
256  if ($tmpproduct->hasFatherOrChild(1) > 0) {
257  $this->error = 'ErrorAVirtualProductCantBeUsedIntoABomOrMo';
258  $this->errors[] = $this->error;
259  $this->db->rollback();
260  return -1;
261  }
262  }
263 
264  // Check that product is not a kit/virtual product
265  if (!$error) {
266  $idcreated = $this->createCommon($user, $notrigger);
267  if ($idcreated <= 0) {
268  $error++;
269  }
270  }
271 
272  if (!$error) {
273  $result = $this->updateProduction($user, $notrigger);
274  if ($result <= 0) {
275  $error++;
276  }
277  }
278 
279  if (!$error) {
280  $this->db->commit();
281  } else {
282  $this->db->rollback();
283  }
284 
285  return $idcreated;
286  }
287 
295  public function createFromClone(User $user, $fromid)
296  {
297  global $langs, $extrafields;
298  $error = 0;
299 
300  dol_syslog(__METHOD__, LOG_DEBUG);
301 
302  $object = new self($this->db);
303 
304  $this->db->begin();
305 
306  // Load source object
307  $result = $object->fetchCommon($fromid);
308  if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
309 
310  // get lines so they will be clone
311  //foreach($this->lines as $line)
312  // $line->fetch_optionals();
313 
314  // Reset some properties
315  unset($object->id);
316  unset($object->fk_user_creat);
317  unset($object->import_key);
318 
319  // Clear fields
320  $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default'];
321  $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
322  $object->status = self::STATUS_DRAFT;
323  // ...
324  // Clear extrafields that are unique
325  if (is_array($object->array_options) && count($object->array_options) > 0)
326  {
327  $extrafields->fetch_name_optionals_label($this->table_element);
328  foreach ($object->array_options as $key => $option)
329  {
330  $shortkey = preg_replace('/options_/', '', $key);
331  if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey]))
332  {
333  //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
334  unset($object->array_options[$key]);
335  }
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 
348  if (!$error)
349  {
350  // copy internal contacts
351  if ($this->copy_linked_contact($object, 'internal') < 0)
352  {
353  $error++;
354  }
355  }
356 
357  if (!$error)
358  {
359  // copy external contacts if same company
360  if (property_exists($this, 'socid') && $this->socid == $object->socid)
361  {
362  if ($this->copy_linked_contact($object, 'external') < 0)
363  $error++;
364  }
365  }
366 
367  unset($object->context['createfromclone']);
368 
369  // End
370  if (!$error) {
371  $this->db->commit();
372  return $object;
373  } else {
374  $this->db->rollback();
375  return -1;
376  }
377  }
378 
386  public function fetch($id, $ref = null)
387  {
388  $result = $this->fetchCommon($id, $ref);
389  if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
390  return $result;
391  }
392 
398  public function fetchLines()
399  {
400  $this->lines = array();
401 
402  $result = $this->fetchLinesCommon();
403  return $result;
404  }
405 
406 
418  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
419  {
420  global $conf;
421 
422  dol_syslog(__METHOD__, LOG_DEBUG);
423 
424  $records = array();
425 
426  $sql = 'SELECT ';
427  $sql .= $this->getFieldList();
428  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
429  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
430  else $sql .= ' WHERE 1 = 1';
431  // Manage filter
432  $sqlwhere = array();
433  if (count($filter) > 0) {
434  foreach ($filter as $key => $value) {
435  if ($key == 't.rowid') {
436  $sqlwhere[] = $key.'='.$value;
437  } elseif (strpos($key, 'date') !== false) {
438  $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
439  } elseif ($key == 'customsql') {
440  $sqlwhere[] = $value;
441  } else {
442  $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
443  }
444  }
445  }
446  if (count($sqlwhere) > 0) {
447  $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
448  }
449 
450  if (!empty($sortfield)) {
451  $sql .= $this->db->order($sortfield, $sortorder);
452  }
453  if (!empty($limit)) {
454  $sql .= ' '.$this->db->plimit($limit, $offset);
455  }
456 
457  $resql = $this->db->query($sql);
458  if ($resql) {
459  $num = $this->db->num_rows($resql);
460  $i = 0;
461  while ($i < min($limit, $num))
462  {
463  $obj = $this->db->fetch_object($resql);
464 
465  $record = new self($this->db);
466  $record->setVarsFromFetchObj($obj);
467 
468  $records[$record->id] = $record;
469 
470  $i++;
471  }
472  $this->db->free($resql);
473 
474  return $records;
475  } else {
476  $this->errors[] = 'Error '.$this->db->lasterror();
477  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
478 
479  return -1;
480  }
481  }
482 
490  public function fetchLinesLinked($role, $lineid = 0)
491  {
492  $resarray = array();
493  $mostatic = new MoLine($this->db);
494 
495  $sql = 'SELECT ';
496  $sql .= $mostatic->getFieldList();
497  $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t';
498  $sql .= " WHERE t.role = '".$this->db->escape($role)."'";
499  if ($lineid > 0) $sql .= ' AND t.fk_mrp_production = '.$lineid;
500  else $sql .= 'AND t.fk_mo = '.$this->id;
501 
502  $resql = $this->db->query($sql);
503  if ($resql) {
504  $num = $this->db->num_rows($resql);
505 
506  $i = 0;
507  while ($i < $num) {
508  $obj = $this->db->fetch_object($resql);
509  if ($obj) {
510  $resarray[] = array(
511  'rowid'=> $obj->rowid,
512  'date'=> $this->db->jdate($obj->date_creation),
513  'qty' => $obj->qty,
514  'role' => $obj->role,
515  'fk_product' => $obj->fk_product,
516  'fk_warehouse' => $obj->fk_warehouse,
517  'batch' => $obj->batch,
518  'fk_stock_movement' => $obj->fk_stock_movement
519  );
520  }
521 
522  $i++;
523  }
524 
525  return $resarray;
526  } else {
527  $this->error = $this->db->lasterror();
528  return array();
529  }
530  }
531 
532 
538  public function countMovements()
539  {
540  $result = 0;
541 
542  $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'stock_mouvement as sm';
543  $sql .= " WHERE sm.origintype = 'mo' and sm.fk_origin = ".$this->id;
544 
545  $resql = $this->db->query($sql);
546  if ($resql) {
547  $num = $this->db->num_rows($resql);
548 
549  $i = 0;
550  while ($i < $num) {
551  $obj = $this->db->fetch_object($resql);
552  if ($obj) {
553  $result = $obj->nb;
554  }
555 
556  $i++;
557  }
558  } else {
559  $this->error = $this->db->lasterror();
560  }
561 
562  return $result;
563  }
564 
565 
573  public function update(User $user, $notrigger = false)
574  {
575  global $langs;
576 
577  $error = 0;
578 
579  $this->db->begin();
580 
581  $result = $this->updateCommon($user, $notrigger);
582  if ($result <= 0) {
583  $error++;
584  }
585 
586  $result = $this->updateProduction($user, $notrigger);
587  if ($result <= 0) {
588  $error++;
589  }
590 
591  if (!$error) {
592  setEventMessages($langs->trans("RecordModifiedSuccessfully"), null, 'mesgs');
593  $this->db->commit();
594  return 1;
595  } else {
596  setEventMessages($this->error, $this->errors, 'errors');
597  $this->db->rollback();
598  return -1;
599  }
600  }
601 
609  public function updateProduction(User $user, $notrigger = true)
610  {
611  $error = 0;
612 
613  if ($this->status != self::STATUS_DRAFT) {
614  $this->error = 'BadStatus';
615  return -1;
616  }
617 
618  $this->db->begin();
619 
620  // Insert lines in mrp_production table from BOM data
621  if (!$error)
622  {
623  // TODO Check that production has not started. If yes, we stop here.
624 
625  $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.$this->id;
626  $this->db->query($sql);
627 
628  $moline = new MoLine($this->db);
629 
630  // Line to produce
631  $moline->fk_mo = $this->id;
632  $moline->qty = $this->qty;
633  $moline->fk_product = $this->fk_product;
634  $moline->role = 'toproduce';
635  $moline->position = 1;
636 
637  $resultline = $moline->create($user, false); // Never use triggers here
638  if ($resultline <= 0) {
639  $error++;
640  $this->error = $moline->error;
641  $this->errors = $moline->errors;
642  dol_print_error($this->db, $moline->error, $moline->errors);
643  }
644 
645  if ($this->fk_bom > 0) { // If a BOM is defined, we know what to consume.
646  include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
647  $bom = new Bom($this->db);
648  $bom->fetch($this->fk_bom);
649  if ($bom->id > 0)
650  {
651  // Lines to consume
652  if (!$error) {
653  foreach ($bom->lines as $line)
654  {
655  $moline = new MoLine($this->db);
656 
657  $moline->fk_mo = $this->id;
658  if ($line->qty_frozen) {
659  $moline->qty = $line->qty; // Qty to consume does not depends on quantity to produce
660  } else {
661  $moline->qty = price2num(($line->qty / $bom->qty) * $this->qty / $line->efficiency, 'MS'); // Calculate with Qty to produce and more presition
662  }
663  if ($moline->qty <= 0) {
664  $error++;
665  $this->error = "BadValueForquantityToConsume";
666  break;
667  } else {
668  $moline->fk_product = $line->fk_product;
669  $moline->role = 'toconsume';
670  $moline->position = $line->position;
671  $moline->qty_frozen = $line->qty_frozen;
672  $moline->disable_stock_change = $line->disable_stock_change;
673 
674  $resultline = $moline->create($user, false); // Never use triggers here
675  if ($resultline <= 0) {
676  $error++;
677  $this->error = $moline->error;
678  $this->errors = $moline->errors;
679  dol_print_error($this->db, $moline->error, $moline->errors);
680  break;
681  }
682  }
683  }
684  }
685  }
686  }
687  }
688 
689  if (!$error) {
690  $this->db->commit();
691  return 1;
692  } else {
693  $this->db->rollback();
694  return -1;
695  }
696  }
697 
698 
706  public function delete(User $user, $notrigger = false)
707  {
708  return $this->deleteCommon($user, $notrigger);
709  //return $this->deleteCommon($user, $notrigger, 1);
710  }
711 
720  public function deleteLine(User $user, $idline, $notrigger = false)
721  {
722  if ($this->status < 0)
723  {
724  $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
725  return -2;
726  }
727 
728  return $this->deleteLineCommon($user, $idline, $notrigger);
729  }
730 
731 
739  public function getNextNumRef($prod)
740  {
741  global $langs, $conf;
742  $langs->load("mrp");
743 
744  if (!empty($conf->global->MRP_MO_ADDON))
745  {
746  $mybool = false;
747 
748  $file = $conf->global->MRP_MO_ADDON.".php";
749  $classname = $conf->global->MRP_MO_ADDON;
750 
751  // Include file with class
752  $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
753  foreach ($dirmodels as $reldir)
754  {
755  $dir = dol_buildpath($reldir."core/modules/mrp/");
756 
757  // Load file with numbering class (if found)
758  $mybool |= @include_once $dir.$file;
759  }
760 
761  if ($mybool === false)
762  {
763  dol_print_error('', "Failed to include file ".$file);
764  return '';
765  }
766 
767  $obj = new $classname();
768  $numref = $obj->getNextValue($prod, $this);
769 
770  if ($numref != "")
771  {
772  return $numref;
773  } else {
774  $this->error = $obj->error;
775  //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
776  return "";
777  }
778  } else {
779  print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
780  return "";
781  }
782  }
783 
791  public function validate($user, $notrigger = 0)
792  {
793  global $conf, $langs;
794 
795  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
796 
797  $error = 0;
798 
799  // Protection
800  if ($this->status == self::STATUS_VALIDATED)
801  {
802  dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
803  return 0;
804  }
805 
806  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mrp->create))
807  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mrp->mrp_advance->validate))))
808  {
809  $this->error='NotEnoughPermissions';
810  dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
811  return -1;
812  }*/
813 
814  $now = dol_now();
815 
816  $this->db->begin();
817 
818  // Define new ref
819  if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) // empty should not happened, but when it occurs, the test save life
820  {
821  $this->fetch_product();
822  $num = $this->getNextNumRef($this->product);
823  } else {
824  $num = $this->ref;
825  }
826  $this->newref = $num;
827 
828  // Validate
829  $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
830  $sql .= " SET ref = '".$this->db->escape($num)."',";
831  $sql .= " status = ".self::STATUS_VALIDATED.",";
832  $sql .= " date_valid='".$this->db->idate($now)."',";
833  $sql .= " fk_user_valid = ".$user->id;
834  $sql .= " WHERE rowid = ".$this->id;
835 
836  dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
837  $resql = $this->db->query($sql);
838  if (!$resql)
839  {
840  dol_print_error($this->db);
841  $this->error = $this->db->lasterror();
842  $error++;
843  }
844 
845  if (!$error && !$notrigger)
846  {
847  // Call trigger
848  $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
849  if ($result < 0) $error++;
850  // End call triggers
851  }
852 
853  if (!$error)
854  {
855  $this->oldref = $this->ref;
856 
857  // Rename directory if dir was a temporary ref
858  if (preg_match('/^[\(]?PROV/i', $this->ref))
859  {
860  // Now we rename also files into index
861  $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)."'";
862  $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
863  $resql = $this->db->query($sql);
864  if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
865 
866  // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
867  $oldref = dol_sanitizeFileName($this->ref);
868  $newref = dol_sanitizeFileName($num);
869  $dirsource = $conf->mrp->dir_output.'/'.$oldref;
870  $dirdest = $conf->mrp->dir_output.'/'.$newref;
871  if (!$error && file_exists($dirsource))
872  {
873  dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
874 
875  if (@rename($dirsource, $dirdest))
876  {
877  dol_syslog("Rename ok");
878  // Rename docs starting with $oldref with $newref
879  $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
880  foreach ($listoffiles as $fileentry)
881  {
882  $dirsource = $fileentry['name'];
883  $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
884  $dirsource = $fileentry['path'].'/'.$dirsource;
885  $dirdest = $fileentry['path'].'/'.$dirdest;
886  @rename($dirsource, $dirdest);
887  }
888  }
889  }
890  }
891  }
892 
893  // Set new ref and current status
894  if (!$error)
895  {
896  $this->ref = $num;
897  $this->status = self::STATUS_VALIDATED;
898  }
899 
900  if (!$error)
901  {
902  $this->db->commit();
903  return 1;
904  } else {
905  $this->db->rollback();
906  return -1;
907  }
908  }
909 
917  public function setDraft($user, $notrigger = 0)
918  {
919  // Protection
920  if ($this->status <= self::STATUS_DRAFT)
921  {
922  return 0;
923  }
924 
925  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
926  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
927  {
928  $this->error='Permission denied';
929  return -1;
930  }*/
931 
932  return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MRP_MO_UNVALIDATE');
933  }
934 
942  public function cancel($user, $notrigger = 0)
943  {
944  // Protection
945  if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS)
946  {
947  return 0;
948  }
949 
950  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
951  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
952  {
953  $this->error='Permission denied';
954  return -1;
955  }*/
956 
957  return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MRP_MO_CANCEL');
958  }
959 
967  public function reopen($user, $notrigger = 0)
968  {
969  // Protection
970  if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED)
971  {
972  return 0;
973  }
974 
975  /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->write))
976  || (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! empty($user->rights->mymodule->mymodule_advance->validate))))
977  {
978  $this->error='Permission denied';
979  return -1;
980  }*/
981 
982  return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MRP_MO_REOPEN');
983  }
984 
995  public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
996  {
997  global $conf, $langs, $hookmanager;
998 
999  if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
1000 
1001  $result = '';
1002 
1003  $label = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ManufacturingOrder").'</u>';
1004  if (isset($this->status)) {
1005  $label .= ' '.$this->getLibStatut(5);
1006  }
1007  $label .= '<br>';
1008  $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
1009 
1010  $url = dol_buildpath('/mrp/mo_card.php', 1).'?id='.$this->id;
1011  if ($option == 'production') $url = dol_buildpath('/mrp/mo_production.php', 1).'?id='.$this->id;
1012 
1013  if ($option != 'nolink')
1014  {
1015  // Add param to save lastsearch_values or not
1016  $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1017  if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
1018  if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
1019  }
1020 
1021  $linkclose = '';
1022  if (empty($notooltip))
1023  {
1024  if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER))
1025  {
1026  $label = $langs->trans("ShowMo");
1027  $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
1028  }
1029  $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
1030  $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
1031  } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1032 
1033  $linkstart = '<a href="'.$url.'"';
1034  $linkstart .= $linkclose.'>';
1035  $linkend = '</a>';
1036 
1037  $result .= $linkstart;
1038  if ($withpicto) $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);
1039  if ($withpicto != 2) $result .= $this->ref;
1040  $result .= $linkend;
1041  //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1042 
1043  global $action, $hookmanager;
1044  $hookmanager->initHooks(array('modao'));
1045  $parameters = array('id'=>$this->id, 'getnomurl'=>$result);
1046  $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1047  if ($reshook > 0) $result = $hookmanager->resPrint;
1048  else $result .= $hookmanager->resPrint;
1049 
1050  return $result;
1051  }
1052 
1059  public function getLibStatut($mode = 0)
1060  {
1061  return $this->LibStatut($this->status, $mode);
1062  }
1063 
1064  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1072  public function LibStatut($status, $mode = 0)
1073  {
1074  // phpcs:enable
1075  if (empty($this->labelStatus))
1076  {
1077  global $langs;
1078  //$langs->load("mrp");
1079  $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1080  $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatedToProduce');
1081  $this->labelStatus[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1082  $this->labelStatus[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1083  $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1084 
1085  $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1086  $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
1087  $this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1088  $this->labelStatusShort[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1089  $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1090  }
1091 
1092  $statusType = 'status'.$status;
1093  if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
1094  if ($status == self::STATUS_INPROGRESS) $statusType = 'status4';
1095  if ($status == self::STATUS_PRODUCED) $statusType = 'status6';
1096  if ($status == self::STATUS_CANCELED) $statusType = 'status9';
1097 
1098  return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1099  }
1100 
1107  public function info($id)
1108  {
1109  $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1110  $sql .= ' fk_user_creat, fk_user_modif';
1111  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1112  $sql .= ' WHERE t.rowid = '.$id;
1113  $result = $this->db->query($sql);
1114  if ($result)
1115  {
1116  if ($this->db->num_rows($result))
1117  {
1118  $obj = $this->db->fetch_object($result);
1119  $this->id = $obj->rowid;
1120  if ($obj->fk_user_author)
1121  {
1122  $cuser = new User($this->db);
1123  $cuser->fetch($obj->fk_user_author);
1124  $this->user_creation = $cuser;
1125  }
1126 
1127  if ($obj->fk_user_valid)
1128  {
1129  $vuser = new User($this->db);
1130  $vuser->fetch($obj->fk_user_valid);
1131  $this->user_validation = $vuser;
1132  }
1133 
1134  if ($obj->fk_user_cloture)
1135  {
1136  $cluser = new User($this->db);
1137  $cluser->fetch($obj->fk_user_cloture);
1138  $this->user_cloture = $cluser;
1139  }
1140 
1141  $this->date_creation = $this->db->jdate($obj->datec);
1142  $this->date_modification = $this->db->jdate($obj->datem);
1143  $this->date_validation = $this->db->jdate($obj->datev);
1144  }
1145 
1146  $this->db->free($result);
1147  } else {
1148  dol_print_error($this->db);
1149  }
1150  }
1151 
1158  public function initAsSpecimen()
1159  {
1160  $this->initAsSpecimenCommon();
1161  }
1162 
1168  public function getLinesArray()
1169  {
1170  $this->lines = array();
1171 
1172  $objectline = new MoLine($this->db);
1173  $result = $objectline->fetchAll('ASC', 'position', 0, 0, array('customsql'=>'fk_mo = '.$this->id));
1174 
1175  if (is_numeric($result))
1176  {
1177  $this->error = $this->error;
1178  $this->errors = $this->errors;
1179  return $result;
1180  } else {
1181  $this->lines = $result;
1182  return $this->lines;
1183  }
1184  }
1185 
1197  public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1198  {
1199  global $conf, $langs;
1200 
1201  $langs->load("mrp");
1202 
1203  if (!dol_strlen($modele)) {
1204  //$modele = 'standard';
1205  $modele = ''; // Remove this once a pdf_standard.php exists.
1206 
1207  if ($this->model_pdf) {
1208  $modele = $this->model_pdf;
1209  } elseif (!empty($conf->global->MO_ADDON_PDF)) {
1210  $modele = $conf->global->MO_ADDON_PDF;
1211  }
1212  }
1213 
1214  $modelpath = "core/modules/mrp/doc/";
1215 
1216  if (empty($modele)) return 1; // Remove this once a pdf_standard.php exists.
1217 
1218  return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1219  }
1220 
1228  public function doScheduledJob()
1229  {
1230  global $conf, $langs;
1231 
1232  //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlofile.log';
1233 
1234  $error = 0;
1235  $this->output = '';
1236  $this->error = '';
1237 
1238  dol_syslog(__METHOD__, LOG_DEBUG);
1239 
1240  $now = dol_now();
1241 
1242  $this->db->begin();
1243 
1244  // ...
1245 
1246  $this->db->commit();
1247 
1248  return $error;
1249  }
1250 
1261  public function printOriginLinesList($restrictlist = '', $selectedLines = array())
1262  {
1263  global $langs, $hookmanager, $conf, $form;
1264 
1265  print '<tr class="liste_titre">';
1266  print '<td>'.$langs->trans('Ref').'</td>';
1267  print '<td class="right">'.$langs->trans('Qty').' <span class="opacitymedium">('.$langs->trans("ForAQuantityOf", $this->bom->qty).')</span></td>';
1268  print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
1269  print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
1270  //print '<td class="right">'.$langs->trans('Efficiency').'</td>';
1271  //print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
1272  print '<td class="center"></td>';
1273  print '</tr>';
1274  $i = 0;
1275 
1276  if (!empty($this->lines))
1277  {
1278  foreach ($this->lines as $line)
1279  {
1280  /*if (is_object($hookmanager) && (($line->product_type == 9 && !empty($line->special_code)) || !empty($line->fk_parent_line)))
1281  {
1282  if (empty($line->fk_parent_line))
1283  {
1284  $parameters = array('line'=>$line, 'i'=>$i);
1285  $action = '';
1286  $result = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1287  }
1288  }
1289  else
1290  {*/
1291  $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
1292  //}
1293 
1294  $i++;
1295  }
1296  }
1297  }
1298 
1299 
1313  public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
1314  {
1315  global $langs, $conf;
1316 
1317  $this->tpl['id'] = $line->id;
1318 
1319  $this->tpl['label'] = '';
1320  if (!empty($line->fk_product))
1321  {
1322  $productstatic = new Product($this->db);
1323  $productstatic->fetch($line->fk_product);
1324  $this->tpl['label'] .= $productstatic->getNomUrl(1);
1325  //$this->tpl['label'].= ' - '.$productstatic->label;
1326  } else {
1327  // If origin MRP line is not a product, but another MRP
1328  // TODO
1329  }
1330 
1331  $this->tpl['qty_bom'] = 1;
1332  if (is_object($this->bom) && $this->bom->qty > 1) {
1333  $this->tpl['qty_bom'] = $this->bom->qty;
1334  }
1335 
1336  $this->tpl['qty'] = $line->qty;
1337  $this->tpl['qty_frozen'] = $line->qty_frozen;
1338  $this->tpl['disable_stock_change'] = $line->disable_stock_change;
1339  $this->tpl['efficiency'] = $line->efficiency;
1340 
1341  $tpl = DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
1342  $res = include $tpl;
1343  }
1344 
1353  public static function replaceThirdparty($db, $origin_id, $dest_id)
1354  {
1355  $tables = array('mrp_mo');
1356 
1357  return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1358  }
1359 }
1360 
1365 {
1369  public $element = 'mrp_production';
1370 
1374  public $table_element = 'mrp_production';
1375 
1379  public $ismultientitymanaged = 0;
1380 
1384  public $isextrafieldmanaged = 0;
1385 
1386  public $fields = array(
1387  'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10),
1388  'fk_mo' =>array('type'=>'integer', 'label'=>'Mo', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
1389  'position' =>array('type'=>'integer', 'label'=>'Position', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>20),
1390  'fk_product' =>array('type'=>'integer', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
1391  'fk_warehouse' =>array('type'=>'integer', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'position'=>30),
1392  'qty' =>array('type'=>'real', 'label'=>'Qty', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>35),
1393  'qty_frozen' => array('type'=>'smallint', 'label'=>'QuantityFrozen', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>105, 'css'=>'maxwidth50imp', 'help'=>'QuantityConsumedInvariable'),
1394  'disable_stock_change' => array('type'=>'smallint', 'label'=>'DisableStockChange', 'enabled'=>1, 'visible'=>1, 'default'=>0, 'position'=>108, 'css'=>'maxwidth50imp', 'help'=>'DisableStockChangeHelp'),
1395  'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>-1, 'position'=>140),
1396  'role' =>array('type'=>'varchar(10)', 'label'=>'Role', 'enabled'=>1, 'visible'=>-1, 'position'=>145),
1397  'fk_mrp_production' =>array('type'=>'integer', 'label'=>'Fk mrp production', 'enabled'=>1, 'visible'=>-1, 'position'=>150),
1398  'fk_stock_movement' =>array('type'=>'integer', 'label'=>'StockMovement', 'enabled'=>1, 'visible'=>-1, 'position'=>155),
1399  'date_creation' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>160),
1400  'tms' =>array('type'=>'timestamp', 'label'=>'Tms', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>165),
1401  'fk_user_creat' =>array('type'=>'integer', 'label'=>'UserCreation', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>170),
1402  'fk_user_modif' =>array('type'=>'integer', 'label'=>'UserModification', 'enabled'=>1, 'visible'=>-1, 'position'=>175),
1403  'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-1, 'position'=>180),
1404  );
1405 
1406  public $rowid;
1407  public $fk_mo;
1408  public $position;
1409  public $fk_product;
1410  public $fk_warehouse;
1411  public $qty;
1412  public $qty_frozen;
1413  public $disable_stock_change;
1414  public $batch;
1415  public $role;
1416  public $fk_mrp_production;
1417  public $fk_stock_movement;
1418  public $date_creation;
1419  public $tms;
1420  public $fk_user_creat;
1421  public $fk_user_modif;
1422  public $import_key;
1423 
1429  public function __construct(DoliDB $db)
1430  {
1431  global $conf, $langs;
1432 
1433  $this->db = $db;
1434 
1435  if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
1436  if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
1437 
1438  // Unset fields that are disabled
1439  foreach ($this->fields as $key => $val)
1440  {
1441  if (isset($val['enabled']) && empty($val['enabled']))
1442  {
1443  unset($this->fields[$key]);
1444  }
1445  }
1446 
1447  // Translate some data of arrayofkeyval
1448  if (is_object($langs))
1449  {
1450  foreach ($this->fields as $key => $val)
1451  {
1452  if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval']))
1453  {
1454  foreach ($val['arrayofkeyval'] as $key2 => $val2)
1455  {
1456  $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
1457  }
1458  }
1459  }
1460  }
1461  }
1462 
1470  public function create(User $user, $notrigger = false)
1471  {
1472  if (empty($this->qty)) {
1473  $this->error = 'BadValueForQty';
1474  return -1;
1475  }
1476 
1477  return $this->createCommon($user, $notrigger);
1478  }
1479 
1487  public function fetch($id, $ref = null)
1488  {
1489  $result = $this->fetchCommon($id, $ref);
1490  if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
1491  return $result;
1492  }
1493 
1505  public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
1506  {
1507  global $conf;
1508 
1509  dol_syslog(__METHOD__, LOG_DEBUG);
1510 
1511  $records = array();
1512 
1513  $sql = 'SELECT ';
1514  $sql .= $this->getFieldList();
1515  $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1516  if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= ' WHERE t.entity IN ('.getEntity($this->table_element).')';
1517  else $sql .= ' WHERE 1 = 1';
1518  // Manage filter
1519  $sqlwhere = array();
1520  if (count($filter) > 0) {
1521  foreach ($filter as $key => $value) {
1522  if ($key == 't.rowid') {
1523  $sqlwhere[] = $key.'='.$value;
1524  } elseif (strpos($key, 'date') !== false) {
1525  $sqlwhere[] = $key.' = \''.$this->db->idate($value).'\'';
1526  } elseif ($key == 'customsql') {
1527  $sqlwhere[] = $value;
1528  } else {
1529  $sqlwhere[] = $key.' LIKE \'%'.$this->db->escape($value).'%\'';
1530  }
1531  }
1532  }
1533  if (count($sqlwhere) > 0) {
1534  $sql .= ' AND ('.implode(' '.$filtermode.' ', $sqlwhere).')';
1535  }
1536 
1537  if (!empty($sortfield)) {
1538  $sql .= $this->db->order($sortfield, $sortorder);
1539  }
1540  if (!empty($limit)) {
1541  $sql .= ' '.$this->db->plimit($limit, $offset);
1542  }
1543 
1544  $resql = $this->db->query($sql);
1545  if ($resql) {
1546  $num = $this->db->num_rows($resql);
1547  $i = 0;
1548  while ($i < min($limit, $num))
1549  {
1550  $obj = $this->db->fetch_object($resql);
1551 
1552  $record = new self($this->db);
1553  $record->setVarsFromFetchObj($obj);
1554 
1555  $records[$record->id] = $record;
1556 
1557  $i++;
1558  }
1559  $this->db->free($resql);
1560 
1561  return $records;
1562  } else {
1563  $this->errors[] = 'Error '.$this->db->lasterror();
1564  dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
1565 
1566  return -1;
1567  }
1568  }
1569 
1577  public function update(User $user, $notrigger = false)
1578  {
1579  return $this->updateCommon($user, $notrigger);
1580  }
1581 
1589  public function delete(User $user, $notrigger = false)
1590  {
1591  return $this->deleteCommon($user, $notrigger);
1592  //return $this->deleteCommon($user, $notrigger, 1);
1593  }
1594 }
__construct(DoliDB $db)
Constructor.
Definition: mo.class.php:1429
deleteCommon(User $user, $notrigger=false, $forcechilddeletion=0)
Delete object in database.
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:1313
setDraft($user, $notrigger=0)
Set draft status.
Definition: mo.class.php:917
fetchLinesCommon($morewhere= '')
Load object in memory from the database.
updateProduction(User $user, $notrigger=true)
Erase and update the line to consume and to produce.
Definition: mo.class.php:609
fetchLinesLinked($role, $lineid=0)
Get list of lines linked to current line for a defined role.
Definition: mo.class.php:490
deleteLine(User $user, $idline, $notrigger=false)
Delete a line of object in database.
Definition: mo.class.php:720
getLinesArray()
Create an array of lines.
Definition: mo.class.php:1168
foreach($object->fields as $key=> $val) if(is_array($extrafields->attributes[$object->table_element]['label'])&&count($extrafields->attributes[$object->table_element]['label']) > 0) $object fields
Class to manage products or services.
dol_now($mode= 'auto')
Return date for now.
LibStatut($status, $mode=0)
Return the status.
Definition: mo.class.php:1072
getNextNumRef($prod)
Returns the reference to the following non used MO depending on the active numbering module defined i...
Definition: mo.class.php:739
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:1261
Class to manage Dolibarr users.
Definition: user.class.php:44
Class to manage Dolibarr database access.
Class for Mo.
Definition: mo.class.php:34
update(User $user, $notrigger=false)
Update object into database.
Definition: mo.class.php:1577
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
createCommon(User $user, $notrigger=false)
Create object into database.
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:418
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
Class MoLine.
Definition: mo.class.php:1364
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:1505
$conf db
API class for accounts.
Definition: inc.php:54
Parent class for class inheritance lines of business objects This class is useless for the moment so ...
create(User $user, $notrigger=false)
Create object into database.
Definition: mo.class.php:1470
countMovements()
Count number of movement with origin of MO.
Definition: mo.class.php:538
createFromClone(User $user, $fromid)
Clone an object into another one.
Definition: mo.class.php:295
setEventMessages($mesg, $mesgs, $style= 'mesgs', $messagekey= '')
Set event messages in dol_events session object.
getLibStatut($mode=0)
Return label of the status.
Definition: mo.class.php:1059
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
Definition: mo.class.php:1197
dol_strlen($string, $stringencoding= 'UTF-8')
Make a strlen call.
price2num($amount, $rounding= '', $option=0)
Function that return a number with universal decimal format (decimal separator is &#39;...
static commonReplaceThirdparty(DoliDB $db, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
update(User $user, $notrigger=false)
Update object into database.
Definition: mo.class.php:573
img_picto($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0, $alt= '', $morecss= '', $marginleftonlyshort=2)
Show picto whatever it&#39;s its name (generic function)
create(User $user, $notrigger=false)
Create object into database.
Definition: mo.class.php:243
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename= '', $restricttologhandler= '', $logcontext=null)
Write log message into outputs.
fetch($id, $ref=null)
Load object in memory from the database.
Definition: mo.class.php:1487
validate($user, $notrigger=0)
Validate Mo.
Definition: mo.class.php:791
static replaceThirdparty($db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
Definition: mo.class.php:1353
img_object($titlealt, $picto, $moreatt= '', $pictoisfullpath=false, $srconly=0, $notitle=0)
Show a picto called object_picto (generic function)
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:995
fetch($id, $ref=null)
Load object in memory from the database.
Definition: mo.class.php:386
updateCommon(User $user, $notrigger=false)
Update object into database.
dol_sanitizeFileName($str, $newstr= '_', $unaccent=1)
Clean a string to use it as a file name.
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
cancel($user, $notrigger=0)
Set cancel status.
Definition: mo.class.php:942
print $_SERVER["PHP_SELF"]
Edit parameters.
deleteLineCommon(User $user, $idline, $notrigger=false)
Delete a line of object in database.
copy_linked_contact($objFrom, $source= 'internal')
Copy contact from one element to current.
print
Draft customers invoices.
Definition: index.php:89
call_trigger($triggerName, $user)
Call trigger based on this instance.
if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) if(!empty($conf->don->enabled)&&$user->rights->don->lire) if(!empty($conf->tax->enabled)&&$user->rights->tax->charges->lire) if(!empty($conf->facture->enabled)&&!empty($conf->commande->enabled)&&$user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(!empty($conf->facture->enabled)&&$user->rights->facture->lire) if((!empty($conf->fournisseur->enabled)&&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD)||!empty($conf->supplier_invoice->enabled))&&$user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1232
dol_print_error($db= '', $error= '', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
setStatusCommon($user, $status, $notrigger=0, $triggercode= '')
Set to a status.
getFieldList()
Function to concat keys of fields.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Definition: mo.class.php:1158
dolGetStatus($statusLabel= '', $statusLabelShort= '', $html= '', $statusType= 'status0', $displayMode=0, $url= '', $params=array())
Output the badge of a status.
fetch_product()
Load the product with id $this-&gt;fk_product into this-&gt;product.
reopen($user, $notrigger=0)
Set back to validated status.
Definition: mo.class.php:967
info($id)
Load the info information in the object.
Definition: mo.class.php:1107
__construct(DoliDB $db)
Constructor.
Definition: mo.class.php:205
fetchLines()
Load object lines in memory from the database.
Definition: mo.class.php:398
doScheduledJob()
Action executed by scheduler CAN BE A CRON TASK.
Definition: mo.class.php:1228
Parent class of all other business classes (invoices, contracts, proposals, orders, ...)
fetchCommon($id, $ref=null, $morewhere= '')
Load object in memory from the database.