dolibarr 25.0.0-alpha
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) 2023-2026 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2025 Noé Cendrier <noe.cendrier@altairis.fr>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
29require_once DOL_DOCUMENT_ROOT.'/mrp/class/moline.class.php';
30
34class Mo extends CommonObject
35{
39 public $element = 'mo';
40
44 public $table_element = 'mrp_mo';
45
49 public $picto = 'mrp';
50
51
52 const STATUS_DRAFT = 0;
53 const STATUS_VALIDATED = 1; // To produce
54 const STATUS_INPROGRESS = 2;
55 const STATUS_PRODUCED = 3;
56 const STATUS_CANCELED = 9;
57
58
88 public $fields = array(
89 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'position' => 1, 'notnull' => 1, 'index' => 1, 'comment' => "Id",),
90 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'position' => 5, 'notnull' => 1, 'default' => '1', 'index' => 1),
91 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'visible' => 4, 'position' => 10, 'notnull' => 1, 'default' => '(PROV)', 'index' => 1, 'searchall' => 1, 'comment' => "Reference of object", 'showoncombobox' => 1, 'noteditable' => 1),
92 'fk_bom' => array('type' => 'integer:Bom:bom/class/bom.class.php:0:(t.status:=:1)', 'filter' => 'active=1', 'label' => 'BOM', 'enabled' => 'isModEnabled("bom")', 'visible' => 1, 'position' => 33, 'notnull' => -1, 'index' => 1, 'comment' => "Original BOM", 'css' => 'minwidth100 maxwidth500', 'csslist' => 'tdoverflowmax150', 'picto' => 'bom'),
93 'mrptype' => array('type' => 'integer', 'label' => 'Type', 'enabled' => 1, 'visible' => 1, 'position' => 34, 'notnull' => 1, 'default' => '0', 'arrayofkeyval' => array(0 => 'Manufacturing', 1 => 'Disassemble'), 'css' => 'minwidth150', 'csslist' => 'minwidth150 center'),
94 'fk_product' => array('type' => 'integer:Product:product/class/product.class.php:0', 'label' => 'Product', 'enabled' => 'isModEnabled("product")', 'visible' => 1, 'position' => 35, 'notnull' => 1, 'index' => 1, 'comment' => "Product to produce", 'css' => 'maxwidth300', 'csslist' => 'tdoverflowmax100', 'picto' => 'product'),
95 'qty' => array('type' => 'real', 'label' => 'QtyToProduce', 'enabled' => 1, 'visible' => 1, 'position' => 40, 'notnull' => 1, 'comment' => "Qty to produce", 'css' => 'width75', 'default' => '1', 'isameasure' => 1),
96 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => 1, 'position' => 42, 'notnull' => -1, 'searchall' => 1, 'showoncombobox' => 2, 'css' => 'maxwidth300', 'csslist' => 'tdoverflowmax200', 'alwayseditable' => 1),
97 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php:1', 'label' => 'ThirdParty', 'picto' => 'company', 'enabled' => 'isModEnabled("societe")', 'visible' => -1, 'position' => 50, 'notnull' => -1, 'index' => 1, 'css' => 'maxwidth400', 'csslist' => 'tdoverflowmax150'),
98 'fk_project' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'picto' => 'project', 'enabled' => 'isModEnabled("project")', 'visible' => -1, 'position' => 51, 'notnull' => -1, 'index' => 1, 'css' => 'minwidth200 maxwidth400', 'csslist' => 'tdoverflowmax100'),
99 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label' => 'WarehouseForProduction', 'picto' => 'stock', 'enabled' => 'isModEnabled("stock")', 'visible' => 1, 'position' => 52, 'css' => 'maxwidth400', 'csslist' => 'tdoverflowmax200'),
100 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 61, 'notnull' => -1,),
101 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 62, 'notnull' => -1,),
102 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'position' => 500, 'notnull' => 1,),
103 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -2, 'position' => 501, 'notnull' => 1,),
104 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -2, 'position' => 502,),
105 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -2, 'position' => 510, 'notnull' => 1, 'foreignkey' => 'user.rowid', 'csslist' => 'tdoverflowmax100'),
106 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'enabled' => 1, 'visible' => -2, 'position' => 511, 'notnull' => -1, 'csslist' => 'tdoverflowmax100'),
107 'date_start_planned' => array('type' => 'datetime', 'label' => 'DateStartPlannedMo', 'enabled' => 1, 'visible' => 1, 'position' => 55, 'notnull' => -1, 'index' => 1, 'help' => 'KeepEmptyForAsap', 'alwayseditable' => 1, 'csslist' => 'nowraponall'),
108 'date_end_planned' => array('type' => 'datetime', 'label' => 'DateEndPlannedMo', 'enabled' => 1, 'visible' => 1, 'position' => 56, 'notnull' => -1, 'index' => 1, 'alwayseditable' => 1, 'csslist' => 'nowraponall'),
109 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000, 'notnull' => -1,),
110 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 1010),
111 'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'visible' => 2, 'position' => 1000, 'default' => '0', 'notnull' => 1, 'index' => 1, 'arrayofkeyval' => array('0' => 'Draft', '1' => 'Validated', '2' => 'InProgress', '3' => 'StatusMOProduced', '9' => 'Canceled')),
112 'fk_parent_line' => array('type' => 'integer:MoLine:mrp/class/mo.class.php', 'label' => 'ParentMo', 'enabled' => 1, 'visible' => 0, 'position' => 1020, 'default' => '0', 'notnull' => 0, 'index' => 1,'showoncombobox' => 0),
113 );
114
118 public $rowid;
119
123 public $ref;
124
128 public $mrptype;
129
133 public $label;
134
138 public $qty;
139
143 public $fk_warehouse;
144
148 public $fk_soc;
149
153 public $socid;
154
158 public $note_public;
159
163 public $note_private;
164
168 public $date_valid;
169
173 public $fk_user_creat;
177 public $fk_user_modif;
181 public $import_key;
185 public $status;
186
190 public $fk_product;
191
195 public $product;
196
200 public $date_start_planned;
201
205 public $date_end_planned;
206
210 public $fk_bom;
211
215 public $bom;
216
220 public $fk_project;
221
226 public $oldQty;
227
228
229 // If this object has a subtable with lines
230
234 public $table_element_line = 'mrp_production';
235
239 public $fk_element = 'fk_mo';
240
244 public $class_element_line = 'MoLine';
245
249 protected $childtables = array();
250
254 protected $childtablesoncascade = array('mrp_production');
255
259 public $lines = array();
260
264 public $line = null;
265
269 public $fk_parent_line;
270
274 public $tpl = array();
275
282 public $noFlattenBomLineIds = array();
283
284
290 public function __construct(DoliDB $db)
291 {
292 global $langs;
293
294 $this->db = $db;
295
296 $this->ismultientitymanaged = 1;
297 $this->isextrafieldmanaged = 1;
298
299 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
300 $this->fields['rowid']['visible'] = 0;
301 }
302 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
303 $this->fields['entity']['enabled'] = 0;
304 }
305
306 // Unset fields that are disabled
307 foreach ($this->fields as $key => $val) {
308 if (isset($val['enabled']) && empty($val['enabled'])) {
309 unset($this->fields[$key]);
310 }
311 }
312
313 // Translate some data of arrayofkeyval
314 foreach ($this->fields as $key => $val) {
315 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
316 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
317 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
318 }
319 }
320 }
321 }
322
330 public function create(User $user, $notrigger = 0)
331 {
332 $error = 0;
333 $idcreated = 0;
334
335 // If kits feature is enabled and we don't allow kits into BOM and MO, we check that the product is not a kit/virtual product
336 if (getDolGlobalString('PRODUIT_SOUSPRODUITS') && !getDolGlobalString('ALLOW_USE_KITS_INTO_BOM_AND_MO') && $this->fk_product > 0) {
337 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
338 $tmpproduct = new Product($this->db);
339 $tmpproduct->fetch((int) $this->fk_product);
340 if ($tmpproduct->hasFatherOrChild(1) > 0) {
341 $this->error = 'ErrorAVirtualProductCantBeUsedIntoABomOrMo';
342 $this->errors[] = $this->error;
343 return -2;
344 }
345 }
346
347 $this->db->begin();
348
349 if ($this->fk_bom > 0) {
350 // If there is a known BOM, we force the type of MO to the type of BOM
351 include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
352 $tmpbom = new BOM($this->db);
353 $tmpbom->fetch($this->fk_bom);
354
355 $this->mrptype = $tmpbom->bomtype;
356 }
357
358
359 $idcreated = $this->createCommon($user, $notrigger);
360 if ($idcreated <= 0) {
361 $error++;
362 }
363
364 if (!$error) {
365 $result = $this->createProduction($user, $notrigger); // Insert lines from BOM
366 if ($result <= 0) {
367 $error++;
368 }
369 }
370
371 if (!$error) {
372 $this->db->commit();
373 return $idcreated;
374 } else {
375 $this->db->rollback();
376 return -1;
377 }
378 }
379
387 public function createFromClone(User $user, $fromid)
388 {
389 global $langs, $extrafields;
390 $error = 0;
391
392 dol_syslog(__METHOD__, LOG_DEBUG);
393
394 $object = new self($this->db);
395
396 $this->db->begin();
397
398 // Load source object
399 $result = $object->fetchCommon($fromid);
400 if ($result > 0 && !empty($object->table_element_line)) {
401 $object->fetchLines();
402 }
403
404 // get lines so they will be clone
405 //foreach($this->lines as $line)
406 // $line->fetch_optionals();
407
408 // Reset some properties
409 unset($object->id);
410 unset($object->fk_user_creat);
411 unset($object->import_key);
412
413 // We make $object->lines empty to sort it without produced and consumed lines
414 $TLines = $object->lines;
415 $object->lines = array();
416
417 // Remove produced and consumed lines
418 foreach ($TLines as $key => $line) {
419 if (in_array($line->role, array('consumed', 'produced'))) {
420 unset($object->lines[$key]);
421 } else {
422 $object->lines[] = $line;
423 }
424 }
425
426
427 // Clear fields @phan-suppress-next-line PhanTypeMismatchProperty
428 $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default'];
429 // @phan-suppress-next-line PhanTypeInvalidDimOffset
430 $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
431 $object->status = self::STATUS_DRAFT;
432 // ...
433 // Clear extrafields that are unique
434 if (is_array($object->array_options) && count($object->array_options) > 0) {
435 $extrafields->fetch_name_optionals_label($this->table_element);
436 foreach ($object->array_options as $key => $option) {
437 $shortkey = preg_replace('/options_/', '', $key);
438 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
439 //var_dump($key);
440 //var_dump($clonedObj->array_options[$key]); exit;
441 unset($object->array_options[$key]);
442 }
443 }
444 }
445
446 // Create clone
447 $object->context['createfromclone'] = 'createfromclone';
448 $result = $object->createCommon($user);
449 if ($result < 0) {
450 $error++;
451 $this->error = $object->error;
452 $this->errors = $object->errors;
453 }
454
455 if (!$error) {
456 // copy internal contacts
457 if ($this->copy_linked_contact($object, 'internal') < 0) {
458 $error++;
459 }
460 }
461
462 if (!$error) {
463 // copy external contacts if same company
464 if (property_exists($this, 'socid') && $this->socid == $object->socid) {
465 if ($this->copy_linked_contact($object, 'external') < 0) {
466 $error++;
467 }
468 }
469 }
470
471 unset($object->context['createfromclone']);
472
473 // End
474 if (!$error) {
475 $this->db->commit();
476 return $object;
477 } else {
478 $this->db->rollback();
479 return -1;
480 }
481 }
482
490 public function fetch($id, $ref = null)
491 {
492 $result = $this->fetchCommon($id, $ref);
493 if ($result > 0 && !empty($this->table_element_line)) {
494 $this->fetchLines();
495 }
496
497 $this->socid = $this->fk_soc;
498
499 return $result;
500 }
501
507 public function fetchLines()
508 {
509 $this->lines = array();
510
511 $result = $this->fetchLinesCommon();
512 return $result;
513 }
514
515
527 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
528 {
529 dol_syslog(__METHOD__, LOG_DEBUG);
530
531 $records = array();
532
533 $sql = 'SELECT ';
534 $sql .= $this->getFieldList();
535 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
536 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
537 $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
538 } else {
539 $sql .= ' WHERE 1 = 1';
540 }
541
542 // Manage filter
543 if (is_array($filter)) {
544 $sqlwhere = array();
545 if (count($filter) > 0) {
546 foreach ($filter as $key => $value) {
547 if ($key == 't.rowid') {
548 $sqlwhere[] = $this->db->sanitize($key)." = ".((int) $value);
549 } elseif (strpos($key, 'date') !== false) {
550 $sqlwhere[] = $this->db->sanitize($key)." = '".$this->db->idate((int) $value)."'";
551 } else {
552 $sqlwhere[] = $this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike($value))."%'";
553 }
554 }
555 }
556 if (count($sqlwhere) > 0) {
557 $sql .= ' AND ('.implode(' '.$this->db->sanitize($filtermode).' ', $sqlwhere).')';
558 }
559
560 $filter = '';
561 }
562
563 // Manage filter
564 $errormessage = '';
565 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
566 if ($errormessage) {
567 $this->errors[] = $errormessage;
568 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
569 return -1;
570 }
571
572 if (!empty($sortfield)) {
573 $sql .= $this->db->order($sortfield, $sortorder);
574 }
575 if (!empty($limit)) {
576 $sql .= $this->db->plimit($limit, $offset);
577 }
578
579 $resql = $this->db->query($sql);
580 if ($resql) {
581 $num = $this->db->num_rows($resql);
582 $i = 0;
583 while ($i < min($limit, $num)) {
584 $obj = $this->db->fetch_object($resql);
585
586 $record = new self($this->db);
587 $record->setVarsFromFetchObj($obj);
588
589 $records[$record->id] = $record;
590
591 $i++;
592 }
593 $this->db->free($resql);
594
595 return $records;
596 } else {
597 $this->errors[] = 'Error '.$this->db->lasterror();
598 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
599
600 return -1;
601 }
602 }
603
611 public function fetchLinesLinked($role, $lineid = 0)
612 {
613 $resarray = array();
614 $mostatic = new MoLine($this->db);
615
616 $sql = 'SELECT ';
617 $sql .= $mostatic->getFieldList();
618 $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t';
619 $sql .= " WHERE t.role = '".$this->db->escape($role)."'";
620 if ($lineid > 0) {
621 $sql .= ' AND t.fk_mrp_production = '.((int) $lineid);
622 } else {
623 $sql .= 'AND t.fk_mo = '.((int) $this->id);
624 }
625
626 $resql = $this->db->query($sql);
627 if ($resql) {
628 $num = $this->db->num_rows($resql);
629
630 $i = 0;
631 while ($i < $num) {
632 $obj = $this->db->fetch_object($resql);
633 if ($obj) {
634 $resarray[] = array(
635 'rowid' => (int) $obj->rowid,
636 'date' => $this->db->jdate($obj->date_creation),
637 'qty' => (float) $obj->qty,
638 'role' => $obj->role,
639 'fk_product' => $obj->fk_product,
640 'fk_warehouse' => $obj->fk_warehouse,
641 'batch' => $obj->batch,
642 'fk_stock_movement' => $obj->fk_stock_movement,
643 'fk_unit' => $obj->fk_unit
644 );
645 }
646
647 $i++;
648 }
649
650 return $resarray;
651 } else {
652 $this->error = $this->db->lasterror();
653 return array();
654 }
655 }
656
657
663 public function countMovements()
664 {
665 $result = 0;
666
667 $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'stock_mouvement as sm';
668 $sql .= " WHERE sm.origintype = 'mo' and sm.fk_origin = ".((int) $this->id);
669
670 $resql = $this->db->query($sql);
671 if ($resql) {
672 $num = $this->db->num_rows($resql);
673
674 $i = 0;
675 while ($i < $num) {
676 $obj = $this->db->fetch_object($resql);
677 if ($obj) {
678 $result = $obj->nb;
679 }
680
681 $i++;
682 }
683 } else {
684 $this->error = $this->db->lasterror();
685 }
686
687 return $result;
688 }
689
690
698 public function update(User $user, $notrigger = 0)
699 {
700 $error = 0;
701
702 $this->db->begin();
703
704 $result = $this->updateCommon($user, $notrigger);
705 if ($result <= 0) {
706 $error++;
707 }
708
709 // Update the lines (the qty) to consume or to produce
710 $result = $this->updateProduction($user, $notrigger);
711 if ($result <= 0) {
712 $error++;
713 }
714
715 if (!$error) {
716 $this->db->commit();
717 return 1;
718 } else {
719 $this->db->rollback();
720 return -1;
721 }
722 }
723
724
732 public function createProduction(User $user, $notrigger = 0)
733 {
734 $error = 0;
735 $role = "";
736
737 if ($this->status != self::STATUS_DRAFT) {
738 dol_syslog("Bad status for MO object. Can't add production lines. Check that MO has status DRAFT.");
739 $this->error = "Bad status for MO object. Can't add production lines. Check that MO has status DRAFT.";
740 return -1;
741 }
742
743 $this->db->begin();
744
745 // Insert lines in mrp_production table from BOM data
746
747 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.((int) $this->id);
748 $this->db->query($sql);
749
750 $moline = new MoLine($this->db);
751
752 // Line to produce
753 $moline->fk_mo = (int) $this->id;
754 $moline->qty = (float) $this->qty;
755 $moline->fk_product = (int) $this->fk_product;
756 $moline->fk_warehouse = (int) $this->fk_warehouse;
757 $moline->position = 1;
758
759 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
760 $tmpproduct = new Product($this->db);
761 $tmpproduct->fetch((int) $this->fk_product);
762 $moline->fk_unit = $tmpproduct->fk_unit;
763
764 if ($this->fk_bom > 0) { // If a BOM is defined, we know what to produce.
765 include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
766 $bom = new BOM($this->db);
767 $bom->fetch($this->fk_bom);
768 if ($bom->bomtype == 1) {
769 $role = 'toproduce';
770 $moline->role = 'toconsume';
771 } else {
772 $role = 'toconsume';
773 $moline->role = 'toproduce';
774 }
775 } else {
776 $bom = null;
777 if ($this->mrptype == 1) {
778 $moline->role = 'toconsume';
779 } else {
780 $moline->role = 'toproduce';
781 }
782 }
783
784 $resultline = $moline->create($user, 0); // Never use triggers here
785 if ($resultline <= 0) {
786 $error++;
787 $this->setErrorsFromObject($moline);
788 }
789
790 if ($this->fk_bom > 0 && is_object($bom)) { // If a BOM is defined, we know what to consume.
791 if ($bom->id > 0) {
792 // process lines to consume, this needs to recurse through BOM's
793 $error += $this->processBOM($user, $role, $bom, (float) $this->qty);
794 }
795 }
796
797 if (!$error) {
798 $this->db->commit();
799 return 1;
800 } else {
801 $this->db->rollback();
802 return -1;
803 }
804 }
805
806
816 public function processBOM(User $user, $role, $bom, $quantity)
817 {
818 $error = 0;
819
820 $quantity /= $bom->qty;
821 foreach ($bom->lines as $line) {
822 $quantity_line = !$line->qty_frozen ? $line->qty * $quantity / (!empty($line->efficiency) ? $line->efficiency : 1) : $line->qty;
823
824 $tmpproduct = new Product($this->db);
825 $tmpproduct->fetch($line->fk_product);
826 if ($line->fk_bom_child > 0 && !in_array($line->id, $this->noFlattenBomLineIds)) {
827 $bom = new BOM($this->db);
828 $bom->fetch((int) $line->fk_bom_child);
829 $error += $this->processBOM($user, $role, $bom, $quantity_line);
830 } else {
831 $moline = new MoLine($this->db);
832 $moline->fk_mo = $this->id;
833 $moline->origin_id = $line->id;
834 $moline->origin_type = 'bomline';
835 if (!empty($line->fk_unit)) {
836 $moline->fk_unit = $line->fk_unit;
837 }
838
839 $moline->qty = (float) price2num($quantity_line, 'MS'); // Calculate with Qty to produce and more presition
840 if ($moline->qty <= 0) {
841 $error++;
842 $this->error = "BadValueForquantityToConsume";
843 $this->errors[] = $this->error;
844 } else {
845 $moline->fk_product = $line->fk_product;
846 //$moline->fk_warehouse = !empty($line->fk_warehouse) ? $line->fk_warehouse : (!empty($bom->fk_warehouse) ? $bom->fk_warehouse : $this->fk_warehouse);
847 if (in_array($role, array('toconsume', 'consumed'))) {
848 $moline->fk_warehouse = null;
849 } else { // to produce / produced
850 $moline->fk_warehouse = $this->fk_warehouse; // We fill the production warehouse defined in MO. Do not use the one of the BOM, if a BOM has a production warehouse set, it should have been already copied into the MO.
851 }
852 $moline->role = $role;
853 $moline->position = $line->position;
854 $moline->qty_frozen = $line->qty_frozen;
855 $moline->disable_stock_change = $line->disable_stock_change;
856 if (!empty($line->fk_default_workstation)) {
857 $moline->fk_default_workstation = $line->fk_default_workstation;
858 }
859
860 $resultline = $moline->create($user, 0); // Never use triggers here
861 //var_dump($moline);
862 if ($resultline <= 0) {
863 $error++;
864 $this->error = $moline->error;
865 $this->errors[] = $moline->error;
866 $this->errors = array_merge($this->errors, $moline->errors);
867 dol_print_error($this->db, $moline->error, $moline->errors);
868 }
869 }
870 }
871 if ($error) {
872 break;
873 }
874 }
875 return $error;
876 }
877
878
886 public function updateProduction(User $user, $notrigger = 0)
887 {
888 $error = 0;
889
890 if ($this->status != self::STATUS_DRAFT) {
891 return 1;
892 }
893
894 $this->db->begin();
895
896 $oldQty = $this->oldQty;
897 $newQty = $this->qty;
898 if ($newQty != $oldQty && !empty($this->oldQty)) {
899 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "mrp_production WHERE fk_mo = " . (int) $this->id;
900 $resql = $this->db->query($sql);
901 if ($resql) {
902 while ($obj = $this->db->fetch_object($resql)) {
903 $moLine = new MoLine($this->db);
904 $res = $moLine->fetch($obj->rowid);
905 if (!$res) {
906 $error++;
907 }
908
909 if ($moLine->role == 'toconsume' || $moLine->role == 'toproduce') {
910 if (empty($moLine->qty_frozen)) {
911 $qty = $newQty * $moLine->qty / $oldQty;
912 $moLine->qty = (float) price2num($qty, 'MS');
913 $res = $moLine->update($user);
914 if (!$res) {
915 $error++;
916 }
917 }
918 }
919 }
920 }
921 }
922 if (!$error) {
923 $this->db->commit();
924 return 1;
925 } else {
926 $this->db->rollback();
927 return -1;
928 }
929 }
930
931
940 public function delete(User $user, $notrigger = 0, $also_cancel_consumed_and_produced_lines = false)
941 {
942 $error = 0;
943 $this->db->begin();
944
945 if ($also_cancel_consumed_and_produced_lines) {
946 $result = $this->cancelConsumedAndProducedLines($user, 0, false, $notrigger);
947 if ($result < 0) {
948 $error++;
949 }
950 }
951
952 // Remove linked categories.
953 if (!$error) {
954 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_mo";
955 $sql .= " WHERE fk_mo = ".((int) $this->id);
956
957 $result = $this->db->query($sql);
958 if (!$result) {
959 $error++;
960 $this->errors[] = $this->db->lasterror();
961 }
962 }
963
964 if (!$error) {
965 $result = $this->deleteCommon($user, $notrigger);
966 if ($result < 0) {
967 $error++;
968 }
969 }
970
971 if ($error) {
972 $this->db->rollback();
973 return -1;
974 } else {
975 $this->db->commit();
976 return 1;
977 }
978 }
979
989 public function deleteLine(User $user, $idline, $notrigger = 0, $fk_movement = 0)
990 {
991 global $langs;
992 $langs->loadLangs(array('stocks', 'mrp'));
993
994 if ($this->status < 0) {
995 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
996 return -2;
997 }
998
999 // The line must belong to this MO (checked before any stock movement is reversed)
1000 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
1001 $sql .= " WHERE rowid = ".((int) $idline)." AND fk_mo = ".((int) $this->id);
1002 $resql = $this->db->query($sql);
1003 if (!$resql || !$this->db->num_rows($resql)) {
1004 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1005 return -1;
1006 }
1007
1008 $productstatic = new Product($this->db);
1009
1010 $arrayoflines = $this->fetchLinesLinked('consumed', $idline); // Get lines consumed under the one to delete
1011
1012 $result = 0;
1013 $error = 0;
1014
1015 $this->db->begin();
1016
1017 if (!empty($fk_movement)) {
1018 $stockmove = new MouvementStock($this->db);
1019 $stockmove->setOrigin($this->element, $this->id);
1020
1021 // The fk_movement was not recorded so we try to guess the product and quantity to restore.
1022 $moline = new MoLine($this->db);
1023 $TArrayMoLine = $moline->fetchAll('', '', 1, 0, '(fk_stock_movement:=:'.((int) $fk_movement).')');
1024 $moline = is_array($TArrayMoLine) ? array_shift($TArrayMoLine) : null;
1025 if (!is_object($moline) || (int) $moline->fk_mo !== (int) $this->id) {
1026 $this->db->rollback();
1027 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1028 return -1;
1029 }
1030
1031 $movement = new MouvementStock($this->db);
1032 $movement->fetch($fk_movement);
1033 $productstatic->fetch($movement->product_id);
1034 $qtytoprocess = $movement->qty;
1035
1036 // Reverse stock movement
1037 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1038 $codemovementCancel = $langs->trans("StockIncrease");
1039
1040 if (($qtytoprocess >= 0)) {
1041 $idstockmove = $stockmove->reception($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, '', '', $movement->batch, dol_now(), 0, $codemovementCancel);
1042 } else {
1043 $idstockmove = $stockmove->livraison($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $movement->batch, 0, $codemovementCancel);
1044 }
1045 if ($idstockmove < 0) {
1046 $this->setErrorsFromObject($stockmove);
1047 } else {
1048 $result = $moline->delete($user, $notrigger);
1049 }
1050 } elseif (!empty($arrayoflines)) {
1051 $stockmove = new MouvementStock($this->db);
1052 $stockmove->setOrigin($this->element, $this->id);
1053
1054 // Loop on each child lines
1055 foreach ($arrayoflines as $key => $arrayofline) {
1056 $lineDetails = $arrayoflines[$key];
1057 $productstatic->fetch($lineDetails['fk_product']);
1058 $qtytoprocess = $lineDetails['qty'];
1059
1060 // Reverse stock movement
1061 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1062 $codemovementCancel = $langs->trans("StockIncrease");
1063
1064
1065 if ($qtytoprocess >= 0) {
1066 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1067 } else {
1068 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1069 }
1070 if ($idstockmove < 0) {
1071 $error++;
1072 $this->setErrorsFromObject($stockmove);
1073 } else {
1074 $moline = new MoLine($this->db);
1075 $moline->fetch($lineDetails['rowid']);
1076
1077 $resdel = $moline->delete($user, $notrigger);
1078 if ($resdel < 0) {
1079 $error++;
1080 $this->setErrorsFromObject($moline);
1081 }
1082 }
1083
1084 if ($error == 0) {
1085 $result = $this->deleteLineCommon($user, $idline, $notrigger);
1086 }
1087 }
1088 } else {
1089 // No child lines and no associated movement
1090 $result = $this->deleteLineCommon($user, $idline, $notrigger);
1091 }
1092
1093 if ($error != 0 || $result <= 0) {
1094 $this->db->rollback();
1095 } else {
1096 $this->db->commit();
1097 }
1098
1099 return $result;
1100 }
1101
1102
1110 public function getNextNumRef($prod)
1111 {
1112 global $langs, $conf;
1113 $langs->load("mrp");
1114
1115 if (getDolGlobalString('MRP_MO_ADDON')) {
1116 $mybool = false;
1117
1118 $file = getDolGlobalString('MRP_MO_ADDON') . ".php";
1119 $classname = getDolGlobalString('MRP_MO_ADDON');
1120
1121 // Include file with class
1122 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1123 foreach ($dirmodels as $reldir) {
1124 $dir = dol_buildpath($reldir."core/modules/mrp/");
1125
1126 // Load file with numbering class (if found)
1127 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1128 }
1129
1130 if (!$mybool) {
1131 dol_print_error(null, "Failed to include file ".$file);
1132 return '';
1133 }
1134
1135 $obj = new $classname();
1136 '@phan-var-force ModeleNumRefMos $obj';
1137 $numref = $obj->getNextValue($prod, $this);
1138
1139 if ($numref != "") {
1140 return $numref;
1141 } else {
1142 $this->error = $obj->error;
1143 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1144 return "";
1145 }
1146 } else {
1147 print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
1148 return "";
1149 }
1150 }
1151
1159 public function validate($user, $notrigger = 0)
1160 {
1161 global $conf;
1162
1163 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1164
1165 $error = 0;
1166
1167 // Protection
1168 if ($this->status == self::STATUS_VALIDATED) {
1169 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
1170 return 0;
1171 }
1172
1173 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->create))
1174 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->mrp_advance->validate))))
1175 {
1176 $this->error='NotEnoughPermissions';
1177 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1178 return -1;
1179 }*/
1180
1181 $now = dol_now();
1182
1183 $this->db->begin();
1184
1185 // Define new ref
1186 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1187 $this->fetch_product();
1188 $num = $this->getNextNumRef($this->product);
1189 } else {
1190 $num = (string) $this->ref;
1191 }
1192 $this->newref = $num;
1193
1194 // Validate
1195 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1196 $sql .= " SET ref = '".$this->db->escape($num)."',";
1197 $sql .= " status = ".self::STATUS_VALIDATED.",";
1198 $sql .= " date_valid = '".$this->db->idate($now)."',";
1199 $sql .= " fk_user_valid = ".((int) $user->id);
1200 $sql .= " WHERE rowid = ".((int) $this->id);
1201
1202 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
1203 $resql = $this->db->query($sql);
1204 if (!$resql) {
1205 dol_print_error($this->db);
1206 $this->error = $this->db->lasterror();
1207 $error++;
1208 }
1209
1210 if (!$error && !$notrigger) {
1211 // Call trigger
1212 $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
1213 if ($result < 0) {
1214 $error++;
1215 }
1216 // End call triggers
1217 }
1218
1219 if (!$error) {
1220 $this->oldref = $this->ref;
1221
1222 // Rename directory if dir was a temporary ref
1223 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1224 // Now we rename also files into index
1225 $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)."'";
1226 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1227 $resql = $this->db->query($sql);
1228 if (!$resql) {
1229 $error++;
1230 $this->error = $this->db->lasterror();
1231 }
1232 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'mrp/".$this->db->escape($this->newref)."'";
1233 $sql .= " WHERE filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1234 $resql = $this->db->query($sql);
1235 if (!$resql) {
1236 $error++;
1237 $this->error = $this->db->lasterror();
1238 }
1239
1240 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1241 $oldref = dol_sanitizeFileName($this->ref);
1242 $newref = dol_sanitizeFileName($num);
1243 $dirsource = $conf->mrp->dir_output.'/'.$oldref;
1244 $dirdest = $conf->mrp->dir_output.'/'.$newref;
1245 if (!$error && file_exists($dirsource)) {
1246 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
1247
1248 if (@rename($dirsource, $dirdest)) {
1249 dol_syslog("Rename ok");
1250 // Rename docs starting with $oldref with $newref
1251 $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1252 foreach ($listoffiles as $fileentry) {
1253 $dirsource = $fileentry['name'];
1254 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1255 $dirsource = $fileentry['path'].'/'.$dirsource;
1256 $dirdest = $fileentry['path'].'/'.$dirdest;
1257 @rename($dirsource, $dirdest);
1258 }
1259 }
1260 }
1261 }
1262 }
1263
1264 // Set new ref and current status
1265 if (!$error) {
1266 $this->ref = $num;
1267 $this->status = self::STATUS_VALIDATED;
1268 }
1269
1270 if (!$error) {
1271 $this->db->commit();
1272 return 1;
1273 } else {
1274 $this->db->rollback();
1275 return -1;
1276 }
1277 }
1278
1286 public function setDraft($user, $notrigger = 0)
1287 {
1288 // Protection
1289 if ($this->status <= self::STATUS_DRAFT) {
1290 return 0;
1291 }
1292
1293 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1294 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1295 {
1296 $this->error='Permission denied';
1297 return -1;
1298 }*/
1299
1300 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MRP_MO_UNVALIDATE');
1301 }
1302
1311 public function cancel($user, $notrigger = 0, $also_cancel_consumed_and_produced_lines = false)
1312 {
1313 // Protection
1314 if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) {
1315 return 0;
1316 }
1317
1318 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1319 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1320 {
1321 $this->error='Permission denied';
1322 return -1;
1323 }*/
1324
1325 $error = 0;
1326 $this->db->begin();
1327
1328 if ($also_cancel_consumed_and_produced_lines) {
1329 $result = $this->cancelConsumedAndProducedLines($user, 0, true, $notrigger);
1330 if ($result < 0) {
1331 $error++;
1332 }
1333 }
1334
1335 if (!$error) {
1336 $result = $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MRP_MO_CANCEL');
1337 if ($result < 0) {
1338 $error++;
1339 }
1340 }
1341
1342 if ($error) {
1343 $this->db->rollback();
1344 return -1;
1345 } else {
1346 $this->db->commit();
1347 return 1;
1348 }
1349 }
1350
1358 public function reopen($user, $notrigger = 0)
1359 {
1360 // Protection
1361 if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) {
1362 return 0;
1363 }
1364
1365 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1366 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1367 {
1368 $this->error='Permission denied';
1369 return -1;
1370 }*/
1371
1372 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MRP_MO_REOPEN');
1373 }
1374
1386 public function setCategories($categories)
1387 {
1388 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1389 return parent::setCategoriesCommon($categories, Categorie::TYPE_MO);
1390 }
1391
1401 public function cancelConsumedAndProducedLines($user, $mode = 0, $also_delete_lines = false, $notrigger = 0)
1402 {
1403 global $langs;
1404
1405 if (!isModEnabled('stock')) {
1406 return 1;
1407 }
1408
1409 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
1410 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
1411 $error = 0;
1412 $langs->load('stocks');
1413
1414 $this->db->begin();
1415
1416 // Cancel consumed lines
1417 if (empty($mode) || $mode == 1) {
1418 $arrayoflines = $this->fetchLinesLinked('consumed');
1419 if (!empty($arrayoflines)) {
1420 foreach ($arrayoflines as $key => $lineDetails) {
1421 $productstatic = new Product($this->db);
1422 $productstatic->fetch($lineDetails['fk_product']);
1423 $qtytoprocess = $lineDetails['qty'];
1424
1425 // Reverse stock movement
1426 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1427 $codemovementCancel = $langs->trans("StockIncrease");
1428
1429 $stockmove = new MouvementStock($this->db);
1430 $stockmove->setOrigin($this->element, $this->id);
1431 if ($qtytoprocess >= 0) {
1432 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1433 } else {
1434 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1435 }
1436 if ($idstockmove < 0) {
1437 $this->error = $stockmove->error;
1438 $this->errors = $stockmove->errors;
1439 $error++;
1440 break;
1441 }
1442
1443 if ($also_delete_lines) {
1444 $result = $this->deleteLineCommon($user, $lineDetails['rowid'], $notrigger);
1445 if ($result < 0) {
1446 $error++;
1447 break;
1448 }
1449 }
1450 }
1451 }
1452 }
1453
1454 // Cancel produced lines
1455 if (empty($mode) || $mode == 2) {
1456 $arrayoflines = $this->fetchLinesLinked('produced');
1457 if (!empty($arrayoflines)) {
1458 foreach ($arrayoflines as $key => $lineDetails) {
1459 $productstatic = new Product($this->db);
1460 $productstatic->fetch($lineDetails['fk_product']);
1461 $qtytoprocess = $lineDetails['qty'];
1462
1463 // Reverse stock movement
1464 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1465 $codemovementCancel = $langs->trans("StockDecrease");
1466
1467 $stockmove = new MouvementStock($this->db);
1468 $stockmove->setOrigin($this->element, $this->id);
1469 if ($qtytoprocess >= 0) {
1470 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1471 } else {
1472 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1473 }
1474 if ($idstockmove < 0) {
1475 $this->error = $stockmove->error;
1476 $this->errors = $stockmove->errors;
1477 $error++;
1478 break;
1479 }
1480
1481 if ($also_delete_lines) {
1482 $result = $this->deleteLineCommon($user, $lineDetails['rowid'], $notrigger);
1483 if ($result < 0) {
1484 $error++;
1485 break;
1486 }
1487 }
1488 }
1489 }
1490 }
1491
1492 if ($error) {
1493 $this->db->rollback();
1494 return -1;
1495 } else {
1496 $this->db->commit();
1497 return 1;
1498 }
1499 }
1500
1507 public function getTooltipContentArray($params)
1508 {
1509 global $langs;
1510
1511 $langs->loadLangs(['mrp', 'products']);
1512 $nofetch = isset($params['nofetch']);
1513
1514 $datas = [];
1515
1516 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ManufacturingOrder").'</u>';
1517 if (isset($this->status)) {
1518 $datas['picto'] .= ' '.$this->getLibStatut(5);
1519 }
1520 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1521 if (isset($this->label)) {
1522 $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1523 }
1524 if (isset($this->mrptype)) {
1525 $datas['type'] = '<br><b>'.$langs->trans('Type').':</b> '.$this->fields['mrptype']['arrayofkeyval'][$this->mrptype];
1526 }
1527 if (isset($this->qty)) {
1528 $datas['qty'] = '<br><b>'.$langs->trans('QtyToProduce').':</b> '.$this->qty;
1529 }
1530 if (!$nofetch && isset($this->fk_product)) {
1531 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
1532 $product = new Product($this->db);
1533 $product->fetch($this->fk_product);
1534 $datas['product'] = '<br><b>'.$langs->trans('Product').':</b> '.$product->getNomUrl(1, '', 0, -1, 1);
1535 }
1536 if (!$nofetch && isset($this->fk_warehouse)) {
1537 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
1538 $warehouse = new Entrepot($this->db);
1539 $warehouse->fetch($this->fk_warehouse);
1540 $datas['warehouse'] = '<br><b>'.$langs->trans('WarehouseForProduction').':</b> '.$warehouse->getNomUrl(1, '', 0, 1);
1541 }
1542
1543 return $datas;
1544 }
1545
1556 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1557 {
1558 global $conf, $langs, $action, $hookmanager;
1559
1560 if (!empty($conf->dol_no_mouse_hover)) {
1561 $notooltip = 1; // Force disable tooltips
1562 }
1563
1564 $result = '';
1565 $params = [
1566 'id' => $this->id,
1567 'objecttype' => $this->element,
1568 'option' => $option,
1569 'nofetch' => 1,
1570 ];
1571 $classfortooltip = 'classfortooltip';
1572 $dataparams = '';
1573 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1574 $classfortooltip = 'classforajaxtooltip';
1575 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1576 $label = '';
1577 } else {
1578 $label = implode($this->getTooltipContentArray($params));
1579 }
1580
1581 $baseurl = DOL_URL_ROOT.'/mrp/mo_card.php';
1582 if ($option == 'production') {
1583 $baseurl = DOL_URL_ROOT.'/mrp/mo_production.php';
1584 }
1585
1586 $query = ['id' => $this->id];
1587
1588 if ($option != 'nolink') {
1589 // Add param to save lastsearch_values or not
1590 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1591 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1592 $add_save_lastsearch_values = 1;
1593 }
1594 if ($add_save_lastsearch_values) {
1595 $query = array_merge($query, ['save_lastsearch_values' => 1]);
1596 }
1597 }
1598 $url = dolBuildUrl($baseurl, $query);
1599
1600 $linkclose = '';
1601 if (empty($notooltip)) {
1602 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1603 $label = $langs->trans("ShowMo");
1604 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1605 }
1606 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1607 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1608 } else {
1609 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1610 }
1611
1612 $linkstart = '<a href="'.$url.'"';
1613 $linkstart .= $linkclose.'>';
1614 $linkend = '</a>';
1615
1616 $result .= $linkstart;
1617 if ($withpicto) {
1618 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1619 }
1620 if ($withpicto != 2) {
1621 $result .= $this->ref;
1622 }
1623 $result .= $linkend;
1624 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1625
1626 $hookmanager->initHooks(array('modao'));
1627 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1628 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1629 if ($reshook > 0) {
1630 $result = $hookmanager->resPrint;
1631 } else {
1632 $result .= $hookmanager->resPrint;
1633 }
1634
1635 return $result;
1636 }
1637
1644 public function getLibStatut($mode = 0)
1645 {
1646 return $this->LibStatut($this->status, $mode);
1647 }
1648
1649 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1657 public function LibStatut($status, $mode = 0)
1658 {
1659 // phpcs:enable
1660 if (empty($this->labelStatus)) {
1661 global $langs;
1662 //$langs->load("mrp");
1663 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1664 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatedToProduce');
1665 $this->labelStatus[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1666 $this->labelStatus[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1667 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1668
1669 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1670 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
1671 $this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1672 $this->labelStatusShort[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1673 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1674 }
1675
1676 $statusType = 'status'.$status;
1677 if ($status == self::STATUS_VALIDATED) {
1678 $statusType = 'status1';
1679 }
1680 if ($status == self::STATUS_INPROGRESS) {
1681 $statusType = 'status4';
1682 }
1683 if ($status == self::STATUS_PRODUCED) {
1684 $statusType = 'status6';
1685 }
1686 if ($status == self::STATUS_CANCELED) {
1687 $statusType = 'status9';
1688 }
1689
1690 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1691 }
1692
1699 public function info($id)
1700 {
1701 $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1702 $sql .= ' fk_user_creat, fk_user_modif';
1703 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1704 $sql .= ' WHERE t.rowid = '.((int) $id);
1705 $result = $this->db->query($sql);
1706 if ($result) {
1707 if ($this->db->num_rows($result)) {
1708 $obj = $this->db->fetch_object($result);
1709
1710 $this->id = $obj->rowid;
1711
1712 $this->user_creation_id = $obj->fk_user_creat;
1713 $this->user_modification_id = $obj->fk_user_modif;
1714 $this->date_creation = $this->db->jdate($obj->datec);
1715 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1716 }
1717
1718 $this->db->free($result);
1719 } else {
1720 dol_print_error($this->db);
1721 }
1722 }
1723
1730 public function initAsSpecimen()
1731 {
1732 $ret = $this->initAsSpecimenCommon();
1733
1734 $this->lines = array();
1735
1736 return $ret;
1737 }
1738
1745 public function getLinesArray($rolefilter = '')
1746 {
1747 $this->lines = array();
1748
1749 $objectline = new MoLine($this->db);
1750
1751 $filter = '(fk_mo:=:'.((int) $this->id).')';
1752 if (!empty($rolefilter)) {
1753 $filter .= " AND (role:=:'".$this->db->escape($rolefilter)."')";
1754 }
1755 $result = $objectline->fetchAll('ASC', 'position', 0, 0, $filter);
1756
1757 if (is_numeric($result)) {
1758 $this->error = $objectline->error;
1759 $this->errors = $objectline->errors;
1760 return $result;
1761 } else {
1762 $this->lines = $result;
1763 return $this->lines;
1764 }
1765 }
1766
1778 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1779 {
1780 global $langs;
1781
1782 $langs->load("mrp");
1783
1784 if (!dol_strlen($modele)) {
1785 //$modele = 'standard';
1786 $modele = ''; // Remove this once a pdf_standard.php exists.
1787
1788 if ($this->model_pdf) {
1789 $modele = $this->model_pdf;
1790 } elseif (getDolGlobalString('MRP_MO_ADDON_PDF')) {
1791 $modele = getDolGlobalString('MRP_MO_ADDON_PDF');
1792 }
1793 }
1794
1795 $modelpath = "core/modules/mrp/doc/";
1796
1797 if (empty($modele)) {
1798 return 1; // Remove this once a pdf_standard.php exists.
1799 }
1800
1801 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1802 }
1803
1814 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
1815 {
1816 global $langs, $hookmanager, $form, $action;
1817
1818 $langs->load('stocks');
1819 $text_stock_options = $langs->trans("RealStockDesc").'<br>';
1820 $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen").'<br>';
1821 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE') ? '- '.$langs->trans("DeStockOnShipment").'<br>' : '');
1822 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') ? '- '.$langs->trans("DeStockOnValidateOrder").'<br>' : '');
1823 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_BILL') ? '- '.$langs->trans("DeStockOnBill").'<br>' : '');
1824 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') ? '- '.$langs->trans("ReStockOnBill").'<br>' : '');
1825 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER') ? '- '.$langs->trans("ReStockOnValidateOrder").'<br>' : '');
1826 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER') ? '- '.$langs->trans("ReStockOnDispatchOrder").'<br>' : '');
1827 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE') ? '- '.$langs->trans("StockOnReception").'<br>' : '');
1828
1829 print '<tr class="liste_titre">';
1830 // Product or sub-bom
1831 print '<td class="linecoldescription">'.$langs->trans('Ref');
1832 if (getDolGlobalString('BOM_SUB_BOM')) {
1833 print ' &nbsp; <a id="show_all" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a>&nbsp;&nbsp;';
1834 print '<a id="hide_all" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a>&nbsp;';
1835 }
1836 print '</td>';
1837 // Qty
1838 print '<td class="right">'.$langs->trans('Qty');
1839 if ($this->bom->bomtype == 0) {
1840 print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityOf", (string) $this->bom->qty).')</span>';
1841 } else {
1842 print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityToConsumeOf", (string) $this->bom->qty).')</span>';
1843 }
1844 // Unit
1845 print '<td class="right">'.$langs->trans('Unit');
1846
1847 print '</td>';
1848 print '<td class="center">'.$form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1).'</td>';
1849 print '<td class="center">'.$form->textwithpicto($langs->trans("VirtualStock"), $langs->trans("VirtualStockDesc")).'</td>';
1850 print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
1851 print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
1852 print '<td class="center">'.$langs->trans('MoChildGenerate').'</td>';
1853 //print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
1854 //print '<td class="center"></td>';
1855 print '</tr>';
1856 $i = 0;
1857
1858 if (!empty($this->lines)) {
1859 foreach ($this->lines as $line) {
1860 $reshook = 0;
1861 if (is_object($hookmanager)) {
1862 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
1863 if (!empty($line->fk_parent_line)) {
1864 $parameters['fk_parent_line'] = $line->fk_parent_line;
1865 }
1866 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1867 }
1868 if (empty($reshook)) {
1869 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
1870 }
1871
1872 $i++;
1873 }
1874 }
1875 }
1876
1877
1891 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
1892 {
1893 if (!$line instanceof MoLine) {
1894 dol_syslog(__METHOD__.'::pringOriginLine $line is '.get_class($line).'<>MoLine', LOG_WARNING);
1895 parent::printOriginLine($line, $var, $restrictlist, $defaulttpldir, $selectedLines);
1896 return;
1897 }
1898 $productstatic = new Product($this->db);
1899
1900 $this->tpl['id'] = $line->id;
1901
1902 $this->tpl['label'] = '';
1903 if (!empty($line->fk_product) && $line->fk_product > 0) {
1904 $productstatic->fetch($line->fk_product);
1905 $productstatic->load_stock(); // load_virtual_stock() is done in load_stock()
1906 $this->tpl['label'] .= $productstatic->getNomUrl(1);
1907 //$this->tpl['label'].= ' - '.$productstatic->label;
1908 } else {
1909 // If origin MO line is not a product, but another MO
1910 // TODO
1911 }
1912
1913 $this->tpl['qty_bom'] = 1;
1914 if (is_object($this->bom) && $this->bom->qty > 1) {
1915 $this->tpl['qty_bom'] = $this->bom->qty;
1916 }
1917
1918 $this->tpl['stock'] = $productstatic->stock_reel;
1919 $this->tpl['seuil_stock_alerte'] = $productstatic->seuil_stock_alerte;
1920 $this->tpl['virtual_stock'] = $productstatic->stock_theorique;
1921 $this->tpl['qty'] = $line->qty;
1922 $this->tpl['fk_unit'] = $line->fk_unit;
1923 $this->tpl['qty_frozen'] = $line->qty_frozen;
1924 $this->tpl['disable_stock_change'] = $line->disable_stock_change;
1925 $this->tpl['efficiency'] = $line->efficiency;
1926
1927
1928 global $conf; // used into template
1929 include DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
1930 }
1931
1940 public static function replaceThirdparty($db, $origin_id, $dest_id)
1941 {
1942 $tables = array('mrp_mo');
1943
1944 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
1945 }
1946
1947
1953 public function getMoChilds()
1954 {
1955 $TMoChilds = array();
1956 $error = 0;
1957
1958 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_mo as mo_child";
1959 $sql .= " WHERE fk_parent_line IN ";
1960 $sql .= " (SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_production as line_parent";
1961 $sql .= " WHERE fk_mo=".((int) $this->id).")";
1962
1963 $resql = $this->db->query($sql);
1964
1965 if ($resql) {
1966 if ($this->db->num_rows($resql) > 0) {
1967 while ($obj = $this->db->fetch_object($resql)) {
1968 $MoChild = new Mo($this->db);
1969 $res = $MoChild->fetch($obj->rowid);
1970 if ($res > 0) {
1971 $TMoChilds[$MoChild->id] = $MoChild;
1972 } else {
1973 $error++;
1974 }
1975 }
1976 }
1977 } else {
1978 $error++;
1979 }
1980
1981 if ($error) {
1982 return -1;
1983 } else {
1984 return $TMoChilds;
1985 }
1986 }
1987
1994 public function getAllMoChilds($depth = 0)
1995 {
1996 if ($depth > 1000) {
1997 return -1;
1998 }
1999
2000 $TMoChilds = array();
2001 $error = 0;
2002
2003 $childMoList = $this->getMoChilds();
2004
2005 if ($childMoList == -1) {
2006 return -1;
2007 }
2008
2009 foreach ($childMoList as $childMo) {
2010 $TMoChilds[$childMo->id] = $childMo;
2011 }
2012
2013 foreach ($childMoList as $childMo) {
2014 $childMoChildren = $childMo->getAllMoChilds($depth + 1);
2015
2016 if ($childMoChildren == -1) {
2017 $error++;
2018 } else {
2019 foreach ($childMoChildren as $child) {
2020 $TMoChilds[$child->id] = $child;
2021 }
2022 }
2023 }
2024
2025 if ($error) {
2026 return -1;
2027 } else {
2028 return $TMoChilds;
2029 }
2030 }
2031
2032
2033
2039 public function getMoParent()
2040 {
2041 $MoParent = new Mo($this->db);
2042 $error = 0;
2043
2044 $sql = "SELECT lineparent.fk_mo as id_moparent FROM ".MAIN_DB_PREFIX."mrp_mo as mo";
2045 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."mrp_production lineparent ON mo.fk_parent_line = lineparent.rowid";
2046 $sql .= " WHERE mo.rowid = ".((int) $this->id);
2047
2048 $resql = $this->db->query($sql);
2049
2050 if ($resql) {
2051 if ($this->db->num_rows($resql) > 0) {
2052 $obj = $this->db->fetch_object($resql);
2053 $res = $MoParent->fetch($obj->id_moparent);
2054 if ($res < 0) {
2055 $error++;
2056 }
2057 } else {
2058 return 0;
2059 }
2060 } else {
2061 $error++;
2062 }
2063
2064 if ($error) {
2065 return -1;
2066 } else {
2067 return $MoParent;
2068 }
2069 }
2070
2071 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2078 public function load_board($user)
2079 {
2080 // phpcs:enable
2081 global $conf, $langs;
2082 if ($user->socid) {
2083 return -1; // Security to prohibit this function for an external user
2084 }
2085
2086 $now = dol_now();
2087 $warning_delay = $conf->mrp->progress->warning_delay;
2088
2089 // The count and the number of late MO are computed by the database instead of reading every MO. A MO is late when it has
2090 // a planned end date and that date is before now minus the warning delay.
2091 $sql = "SELECT COUNT(rowid) as nb,";
2092 $sql .= " SUM(CASE WHEN date_end_planned IS NOT NULL AND date_end_planned < '".$this->db->idate($now - $warning_delay)."' THEN 1 ELSE 0 END) as nblate";
2093 $sql .= " FROM ".$this->db->prefix()."mrp_mo";
2094 $sql .= " WHERE status IN (" . self::STATUS_VALIDATED . ", " . self::STATUS_INPROGRESS .")"; // 1 = Ouvert, 2 = En cours
2095 $sql .= " AND entity IN (".getEntity('mrp_mo').")";
2096
2097 $resql = $this->db->query($sql);
2098 if ($resql) {
2099 $langs->load("mrp");
2100 $response = new WorkboardResponse();
2101 $response->warning_delay = $warning_delay / 86400;
2102 $response->label = $langs->trans("MOProgress");
2103 $response->labelShort = $langs->trans("MOProgress");
2104 $response->url = DOL_URL_ROOT.'/mrp/mo_list.php?search_status=-2';
2105 $response->img = img_object('', "mrp");
2106
2107
2108 $obj = $this->db->fetch_object($resql);
2109 if ($obj) {
2110 $response->nbtodo = (int) $obj->nb;
2111 $response->nbtodolate = (int) $obj->nblate;
2112 if ($response->nbtodolate > 0) {
2113 $response->url_late = DOL_URL_ROOT.'/mrp/mo_list.php?search_status=-2&search_option=late';
2114 }
2115 }
2116
2117 return $response;
2118 } else {
2119 dol_print_error($this->db);
2120 $this->error = $this->db->error();
2121 return -1;
2122 }
2123 }
2124
2130 public function hasDelay()
2131 {
2132 global $conf;
2133
2134 if ($this->status != Mo::STATUS_VALIDATED && $this->status != Mo::STATUS_INPROGRESS) {
2135 return false;
2136 }
2137 if (empty($this->date_end_planned)) {
2138 return false;
2139 }
2140 return (dol_now() > ((int) $this->date_end_planned + $conf->mrp->progress->warning_delay));
2141 }
2142
2143
2151 public function getKanbanView($option = '', $arraydata = null)
2152 {
2153 global $langs;
2154 '@phan-var-force array{selected?:int<0,1>,bom?:Bom,product?:product} $arraydata';
2155
2156 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2157
2158 $return = '<div class="box-flex-item box-flex-grow-zero">';
2159 $return .= '<div class="info-box info-box-sm">';
2160 $return .= '<span class="info-box-icon bg-infobox-action">';
2161 $return .= img_picto('', $this->picto);
2162 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2163 $return .= '</span>';
2164 $return .= '<div class="info-box-content">';
2165 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2166 if ($selected >= 0) {
2167 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2168 }
2169 if (!empty($arraydata['bom'])) {
2170 $return .= '<br><span class="info-box-label">'.$arraydata['bom']->getNomUrl(1).'</span>';
2171 }
2172 if (!empty($arraydata['product'])) {
2173 $return .= '<br><span class="info-box-label">'.$arraydata['product']->getNomUrl(1).'</span>';
2174 if (property_exists($this, 'qty')) {
2175 $return .= ' <span class="info-box-label">('.$langs->trans("Qty").' '.$this->qty.')</span>';
2176 }
2177 } else {
2178 if (property_exists($this, 'qty')) {
2179 $return .= '<br><span class="info-box-label">'.$langs->trans('Quantity').' : '.$this->qty.'</span>';
2180 }
2181 }
2182 if (method_exists($this, 'getLibStatut')) {
2183 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2184 }
2185 $return .= '</div>';
2186 $return .= '</div>';
2187 $return .= '</div>';
2188 return $return;
2189 }
2190}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Class for BOM.
Definition bom.class.php:42
deleteLineCommon(User $user, $idline, $notrigger=0)
Delete a line of object in database.
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
createCommon(User $user, $notrigger=0)
Create object in the database.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
updateCommon(User $user, $notrigger=0)
Update object into database.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
static commonReplaceThirdparty(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a thirdparty id with another one.
fetch_product()
Load the product with id $this->fk_product into this->product.
fetchLinesCommon($morewhere='', $noextrafields=0)
Load object in memory from the database.
fetchCommon($id, $ref=null, $morewhere='', $noextrafields=0)
Load object in memory from the database.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
Class to manage Dolibarr database access.
Class to manage warehouses.
Class for Mo.
Definition mo.class.php:35
__construct(DoliDB $db)
Constructor.
Definition mo.class.php:290
fetchLinesLinked($role, $lineid=0)
Get list of lines linked to current line for a defined role.
Definition mo.class.php:611
getMoChilds()
Function used to return children of Mo.
static replaceThirdparty($db, $origin_id, $dest_id)
Function used to replace a thirdparty id with another one.
printOriginLinesList($restrictlist='', $selectedLines=array())
Return HTML table table of source object lines TODO Move this and previous function into output html ...
fetchLines()
Load object lines in memory from the database.
Definition mo.class.php:507
getNextNumRef($prod)
Returns the reference to the following non used MO depending on the active numbering module defined i...
create(User $user, $notrigger=0)
Create object into database.
Definition mo.class.php:330
fetch($id, $ref=null)
Load object in memory from the database.
Definition mo.class.php:490
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load list of objects in memory from the database.
Definition mo.class.php:527
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
processBOM(User $user, $role, $bom, $quantity)
Recurse through BOM only adding products to the list of lines to consume/produce.
Definition mo.class.php:816
reopen($user, $notrigger=0)
Set back to validated status.
hasDelay()
Is the manufactured delayed?
setCategories($categories)
Sets object to given categories.
getMoParent()
Function used to return children of Mo.
getLinesArray($rolefilter='')
Create an array of lines.
updateProduction(User $user, $notrigger=0)
Update quantities in lines to consume and/or lines to produce.
Definition mo.class.php:886
LibStatut($status, $mode=0)
Return the status.
cancel($user, $notrigger=0, $also_cancel_consumed_and_produced_lines=false)
Set cancel status.
setDraft($user, $notrigger=0)
Set draft status.
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...
update(User $user, $notrigger=0)
Update object into database.
Definition mo.class.php:698
getAllMoChilds($depth=0)
Function used to return all child MOs recursively.
createProduction(User $user, $notrigger=0)
Erase and update the line to consume and to produce.
Definition mo.class.php:732
deleteLine(User $user, $idline, $notrigger=0, $fk_movement=0)
Delete a line of object in database.
Definition mo.class.php:989
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
validate($user, $notrigger=0)
Validate Mo.
cancelConsumedAndProducedLines($user, $mode=0, $also_delete_lines=false, $notrigger=0)
Cancel consumed and produced lines (movement stocks)
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
getTooltipContentArray($params)
getTooltipContentArray
load_board($user)
Load indicators for dashboard (this->nbtodo and this->nbtodolate)
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
getLibStatut($mode=0)
Return label of the status.
info($id)
Load the info information in the object.
countMovements()
Count number of movement with origin of MO.
Definition mo.class.php:663
createFromClone(User $user, $fromid)
Clone an object into another one.
Definition mo.class.php:387
Class MoLine.
Class to manage stock movements.
Class to manage products or services.
Class to manage Dolibarr users.
print $langs trans("Ref").' m titre as m m statut as status
Or an array listing all the potential status of the object: array: int of the status => translated la...
Definition index.php:169
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_dir_list($utf8_path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0, $nbsecondsold=0)
Scan a directory and return a list of files/directories.
Definition files.lib.php:65
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dolBuildUrl($url, $params=[], $addtoken=false, $anchor='')
Return path of url.
dol_sanitizeFileName($str, $newstr='_', $unaccent=1, $includequotes=0, $allowdash=0)
Clean a string to use it as a file name.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.