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 if (is_object($langs)) {
315 foreach ($this->fields as $key => $val) {
316 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
317 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
318 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
319 }
320 }
321 }
322 }
323 }
324
332 public function create(User $user, $notrigger = 0)
333 {
334 $error = 0;
335 $idcreated = 0;
336
337 // 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
338 if (getDolGlobalString('PRODUIT_SOUSPRODUITS') && !getDolGlobalString('ALLOW_USE_KITS_INTO_BOM_AND_MO') && $this->fk_product > 0) {
339 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
340 $tmpproduct = new Product($this->db);
341 $tmpproduct->fetch((int) $this->fk_product);
342 if ($tmpproduct->hasFatherOrChild(1) > 0) {
343 $this->error = 'ErrorAVirtualProductCantBeUsedIntoABomOrMo';
344 $this->errors[] = $this->error;
345 return -2;
346 }
347 }
348
349 $this->db->begin();
350
351 if ($this->fk_bom > 0) {
352 // If there is a known BOM, we force the type of MO to the type of BOM
353 include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
354 $tmpbom = new BOM($this->db);
355 $tmpbom->fetch($this->fk_bom);
356
357 $this->mrptype = $tmpbom->bomtype;
358 }
359
360
361 $idcreated = $this->createCommon($user, $notrigger);
362 if ($idcreated <= 0) {
363 $error++;
364 }
365
366 if (!$error) {
367 $result = $this->createProduction($user, $notrigger); // Insert lines from BOM
368 if ($result <= 0) {
369 $error++;
370 }
371 }
372
373 if (!$error) {
374 $this->db->commit();
375 return $idcreated;
376 } else {
377 $this->db->rollback();
378 return -1;
379 }
380 }
381
389 public function createFromClone(User $user, $fromid)
390 {
391 global $langs, $extrafields;
392 $error = 0;
393
394 dol_syslog(__METHOD__, LOG_DEBUG);
395
396 $object = new self($this->db);
397
398 $this->db->begin();
399
400 // Load source object
401 $result = $object->fetchCommon($fromid);
402 if ($result > 0 && !empty($object->table_element_line)) {
403 $object->fetchLines();
404 }
405
406 // get lines so they will be clone
407 //foreach($this->lines as $line)
408 // $line->fetch_optionals();
409
410 // Reset some properties
411 unset($object->id);
412 unset($object->fk_user_creat);
413 unset($object->import_key);
414
415 // We make $object->lines empty to sort it without produced and consumed lines
416 $TLines = $object->lines;
417 $object->lines = array();
418
419 // Remove produced and consumed lines
420 foreach ($TLines as $key => $line) {
421 if (in_array($line->role, array('consumed', 'produced'))) {
422 unset($object->lines[$key]);
423 } else {
424 $object->lines[] = $line;
425 }
426 }
427
428
429 // Clear fields @phan-suppress-next-line PhanTypeMismatchProperty
430 $object->ref = empty($this->fields['ref']['default']) ? "copy_of_".$object->ref : $this->fields['ref']['default'];
431 // @phan-suppress-next-line PhanTypeInvalidDimOffset
432 $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
433 $object->status = self::STATUS_DRAFT;
434 // ...
435 // Clear extrafields that are unique
436 if (is_array($object->array_options) && count($object->array_options) > 0) {
437 $extrafields->fetch_name_optionals_label($this->table_element);
438 foreach ($object->array_options as $key => $option) {
439 $shortkey = preg_replace('/options_/', '', $key);
440 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
441 //var_dump($key);
442 //var_dump($clonedObj->array_options[$key]); exit;
443 unset($object->array_options[$key]);
444 }
445 }
446 }
447
448 // Create clone
449 $object->context['createfromclone'] = 'createfromclone';
450 $result = $object->createCommon($user);
451 if ($result < 0) {
452 $error++;
453 $this->error = $object->error;
454 $this->errors = $object->errors;
455 }
456
457 if (!$error) {
458 // copy internal contacts
459 if ($this->copy_linked_contact($object, 'internal') < 0) {
460 $error++;
461 }
462 }
463
464 if (!$error) {
465 // copy external contacts if same company
466 if (property_exists($this, 'socid') && $this->socid == $object->socid) {
467 if ($this->copy_linked_contact($object, 'external') < 0) {
468 $error++;
469 }
470 }
471 }
472
473 unset($object->context['createfromclone']);
474
475 // End
476 if (!$error) {
477 $this->db->commit();
478 return $object;
479 } else {
480 $this->db->rollback();
481 return -1;
482 }
483 }
484
492 public function fetch($id, $ref = null)
493 {
494 $result = $this->fetchCommon($id, $ref);
495 if ($result > 0 && !empty($this->table_element_line)) {
496 $this->fetchLines();
497 }
498
499 $this->socid = $this->fk_soc;
500
501 return $result;
502 }
503
509 public function fetchLines()
510 {
511 $this->lines = array();
512
513 $result = $this->fetchLinesCommon();
514 return $result;
515 }
516
517
529 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
530 {
531 dol_syslog(__METHOD__, LOG_DEBUG);
532
533 $records = array();
534
535 $sql = 'SELECT ';
536 $sql .= $this->getFieldList();
537 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
538 if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
539 $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
540 } else {
541 $sql .= ' WHERE 1 = 1';
542 }
543
544 // Manage filter
545 if (is_array($filter)) {
546 $sqlwhere = array();
547 if (count($filter) > 0) {
548 foreach ($filter as $key => $value) {
549 if ($key == 't.rowid') {
550 $sqlwhere[] = $this->db->sanitize($key)." = ".((int) $value);
551 } elseif (strpos($key, 'date') !== false) {
552 $sqlwhere[] = $this->db->sanitize($key)." = '".$this->db->idate((int) $value)."'";
553 } else {
554 $sqlwhere[] = $this->db->sanitize($key)." LIKE '%".$this->db->escape($this->db->escapeforlike($value))."%'";
555 }
556 }
557 }
558 if (count($sqlwhere) > 0) {
559 $sql .= ' AND ('.implode(' '.$this->db->sanitize($filtermode).' ', $sqlwhere).')';
560 }
561
562 $filter = '';
563 }
564
565 // Manage filter
566 $errormessage = '';
567 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
568 if ($errormessage) {
569 $this->errors[] = $errormessage;
570 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
571 return -1;
572 }
573
574 if (!empty($sortfield)) {
575 $sql .= $this->db->order($sortfield, $sortorder);
576 }
577 if (!empty($limit)) {
578 $sql .= $this->db->plimit($limit, $offset);
579 }
580
581 $resql = $this->db->query($sql);
582 if ($resql) {
583 $num = $this->db->num_rows($resql);
584 $i = 0;
585 while ($i < min($limit, $num)) {
586 $obj = $this->db->fetch_object($resql);
587
588 $record = new self($this->db);
589 $record->setVarsFromFetchObj($obj);
590
591 $records[$record->id] = $record;
592
593 $i++;
594 }
595 $this->db->free($resql);
596
597 return $records;
598 } else {
599 $this->errors[] = 'Error '.$this->db->lasterror();
600 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
601
602 return -1;
603 }
604 }
605
613 public function fetchLinesLinked($role, $lineid = 0)
614 {
615 $resarray = array();
616 $mostatic = new MoLine($this->db);
617
618 $sql = 'SELECT ';
619 $sql .= $mostatic->getFieldList();
620 $sql .= ' FROM '.MAIN_DB_PREFIX.$mostatic->table_element.' as t';
621 $sql .= " WHERE t.role = '".$this->db->escape($role)."'";
622 if ($lineid > 0) {
623 $sql .= ' AND t.fk_mrp_production = '.((int) $lineid);
624 } else {
625 $sql .= 'AND t.fk_mo = '.((int) $this->id);
626 }
627
628 $resql = $this->db->query($sql);
629 if ($resql) {
630 $num = $this->db->num_rows($resql);
631
632 $i = 0;
633 while ($i < $num) {
634 $obj = $this->db->fetch_object($resql);
635 if ($obj) {
636 $resarray[] = array(
637 'rowid' => (int) $obj->rowid,
638 'date' => $this->db->jdate($obj->date_creation),
639 'qty' => (float) $obj->qty,
640 'role' => $obj->role,
641 'fk_product' => $obj->fk_product,
642 'fk_warehouse' => $obj->fk_warehouse,
643 'batch' => $obj->batch,
644 'fk_stock_movement' => $obj->fk_stock_movement,
645 'fk_unit' => $obj->fk_unit
646 );
647 }
648
649 $i++;
650 }
651
652 return $resarray;
653 } else {
654 $this->error = $this->db->lasterror();
655 return array();
656 }
657 }
658
666 {
667 global $langs;
668
669 if (count($this->fetchLinesLinked('consumed')) || count($this->fetchLinesLinked('produced'))) {
670 $langs->load('mrp');
671 $this->error = $langs->trans('ErrorMoConsumptionOrProductionStarted');
672 return true;
673 }
674
675 return false;
676 }
677
683 public function countMovements()
684 {
685 $result = 0;
686
687 $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'stock_mouvement as sm';
688 $sql .= " WHERE sm.origintype = 'mo' and sm.fk_origin = ".((int) $this->id);
689
690 $resql = $this->db->query($sql);
691 if ($resql) {
692 $num = $this->db->num_rows($resql);
693
694 $i = 0;
695 while ($i < $num) {
696 $obj = $this->db->fetch_object($resql);
697 if ($obj) {
698 $result = $obj->nb;
699 }
700
701 $i++;
702 }
703 } else {
704 $this->error = $this->db->lasterror();
705 }
706
707 return $result;
708 }
709
710
718 public function update(User $user, $notrigger = 0)
719 {
720 $error = 0;
721
722 $this->db->begin();
723
724 $result = $this->updateCommon($user, $notrigger);
725 if ($result <= 0) {
726 $error++;
727 }
728
729 // Update the lines (the qty) to consume or to produce
730 $result = $this->updateProduction($user, $notrigger);
731 if ($result <= 0) {
732 $error++;
733 }
734
735 if (!$error) {
736 $this->db->commit();
737 return 1;
738 } else {
739 $this->db->rollback();
740 return -1;
741 }
742 }
743
744
752 public function createProduction(User $user, $notrigger = 0)
753 {
754 $error = 0;
755 $role = "";
756
757 // The consumed and produced lines can't be deleted here, their stock movements would not be reversed
758 if ($this->hasConsumedOrProducedLines()) {
759 return -1;
760 }
761
762 if ($this->status != self::STATUS_DRAFT) {
763 dol_syslog("Bad status for MO object. Can't add production lines. Check that MO has status DRAFT.");
764 $this->error = "Bad status for MO object. Can't add production lines. Check that MO has status DRAFT.";
765 return -1;
766 }
767
768 $this->db->begin();
769
770 // Insert lines in mrp_production table from BOM data
771
772 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.((int) $this->id);
773 $this->db->query($sql);
774
775 $moline = new MoLine($this->db);
776
777 // Line to produce
778 $moline->fk_mo = (int) $this->id;
779 $moline->qty = (float) $this->qty;
780 $moline->fk_product = (int) $this->fk_product;
781 $moline->fk_warehouse = (int) $this->fk_warehouse;
782 $moline->position = 1;
783
784 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
785 $tmpproduct = new Product($this->db);
786 $tmpproduct->fetch((int) $this->fk_product);
787 $moline->fk_unit = $tmpproduct->fk_unit;
788
789 if ($this->fk_bom > 0) { // If a BOM is defined, we know what to produce.
790 include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
791 $bom = new BOM($this->db);
792 $bom->fetch($this->fk_bom);
793 if ($bom->bomtype == 1) {
794 $role = 'toproduce';
795 $moline->role = 'toconsume';
796 } else {
797 $role = 'toconsume';
798 $moline->role = 'toproduce';
799 }
800 } else {
801 $bom = null;
802 if ($this->mrptype == 1) {
803 $moline->role = 'toconsume';
804 } else {
805 $moline->role = 'toproduce';
806 }
807 }
808
809 $resultline = $moline->create($user, 0); // Never use triggers here
810 if ($resultline <= 0) {
811 $error++;
812 $this->setErrorsFromObject($moline);
813 }
814
815 if ($this->fk_bom > 0 && is_object($bom)) { // If a BOM is defined, we know what to consume.
816 if ($bom->id > 0) {
817 // process lines to consume, this needs to recurse through BOM's
818 $error += $this->processBOM($user, $role, $bom, (float) $this->qty);
819 }
820 }
821
822 if (!$error) {
823 $this->db->commit();
824 return 1;
825 } else {
826 $this->db->rollback();
827 return -1;
828 }
829 }
830
831
841 public function processBOM(User $user, $role, $bom, $quantity)
842 {
843 $error = 0;
844
845 $quantity /= $bom->qty;
846 foreach ($bom->lines as $line) {
847 $quantity_line = !$line->qty_frozen ? $line->qty * $quantity / (!empty($line->efficiency) ? $line->efficiency : 1) : $line->qty;
848
849 $tmpproduct = new Product($this->db);
850 $tmpproduct->fetch($line->fk_product);
851 if ($line->fk_bom_child > 0 && !in_array($line->id, $this->noFlattenBomLineIds)) {
852 $bom = new BOM($this->db);
853 $bom->fetch((int) $line->fk_bom_child);
854 $error += $this->processBOM($user, $role, $bom, $quantity_line);
855 } else {
856 $moline = new MoLine($this->db);
857 $moline->fk_mo = $this->id;
858 $moline->origin_id = $line->id;
859 $moline->origin_type = 'bomline';
860 if (!empty($line->fk_unit)) {
861 $moline->fk_unit = $line->fk_unit;
862 }
863
864 $moline->qty = (float) price2num($quantity_line, 'MS'); // Calculate with Qty to produce and more presition
865 if ($moline->qty <= 0) {
866 $error++;
867 $this->error = "BadValueForquantityToConsume";
868 $this->errors[] = $this->error;
869 } else {
870 $moline->fk_product = $line->fk_product;
871 //$moline->fk_warehouse = !empty($line->fk_warehouse) ? $line->fk_warehouse : (!empty($bom->fk_warehouse) ? $bom->fk_warehouse : $this->fk_warehouse);
872 if (in_array($role, array('toconsume', 'consumed'))) {
873 $moline->fk_warehouse = null;
874 } else { // to produce / produced
875 $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.
876 }
877 $moline->role = $role;
878 $moline->position = $line->position;
879 $moline->qty_frozen = $line->qty_frozen;
880 $moline->disable_stock_change = $line->disable_stock_change;
881 if (!empty($line->fk_default_workstation)) {
882 $moline->fk_default_workstation = $line->fk_default_workstation;
883 }
884
885 $resultline = $moline->create($user, 0); // Never use triggers here
886 //var_dump($moline);
887 if ($resultline <= 0) {
888 $error++;
889 $this->error = $moline->error;
890 $this->errors[] = $moline->error;
891 $this->errors = array_merge($this->errors, $moline->errors);
892 dol_print_error($this->db, $moline->error, $moline->errors);
893 }
894 }
895 }
896 if ($error) {
897 break;
898 }
899 }
900 return $error;
901 }
902
903
911 public function updateProduction(User $user, $notrigger = 0)
912 {
913 $error = 0;
914
915 if ($this->status != self::STATUS_DRAFT) {
916 return 1;
917 }
918
919 $this->db->begin();
920
921 $oldQty = $this->oldQty;
922 $newQty = $this->qty;
923 if ($newQty != $oldQty && !empty($this->oldQty)) {
924 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "mrp_production WHERE fk_mo = " . (int) $this->id;
925 $resql = $this->db->query($sql);
926 if ($resql) {
927 while ($obj = $this->db->fetch_object($resql)) {
928 $moLine = new MoLine($this->db);
929 $res = $moLine->fetch($obj->rowid);
930 if (!$res) {
931 $error++;
932 }
933
934 if ($moLine->role == 'toconsume' || $moLine->role == 'toproduce') {
935 if (empty($moLine->qty_frozen)) {
936 $qty = $newQty * $moLine->qty / $oldQty;
937 $moLine->qty = (float) price2num($qty, 'MS');
938 $res = $moLine->update($user);
939 if (!$res) {
940 $error++;
941 }
942 }
943 }
944 }
945 }
946 }
947 if (!$error) {
948 $this->db->commit();
949 return 1;
950 } else {
951 $this->db->rollback();
952 return -1;
953 }
954 }
955
956
965 public function delete(User $user, $notrigger = 0, $also_cancel_consumed_and_produced_lines = false)
966 {
967 $error = 0;
968 $this->db->begin();
969
970 if ($also_cancel_consumed_and_produced_lines) {
971 $result = $this->cancelConsumedAndProducedLines($user, 0, false, $notrigger);
972 if ($result < 0) {
973 $error++;
974 }
975 }
976
977 // Remove linked categories.
978 if (!$error) {
979 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_mo";
980 $sql .= " WHERE fk_mo = ".((int) $this->id);
981
982 $result = $this->db->query($sql);
983 if (!$result) {
984 $error++;
985 $this->errors[] = $this->db->lasterror();
986 }
987 }
988
989 if (!$error) {
990 $result = $this->deleteCommon($user, $notrigger);
991 if ($result < 0) {
992 $error++;
993 }
994 }
995
996 if ($error) {
997 $this->db->rollback();
998 return -1;
999 } else {
1000 $this->db->commit();
1001 return 1;
1002 }
1003 }
1004
1014 public function deleteLine(User $user, $idline, $notrigger = 0, $fk_movement = 0)
1015 {
1016 global $langs;
1017 $langs->loadLangs(array('stocks', 'mrp'));
1018
1019 if ($this->status < 0) {
1020 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1021 return -2;
1022 }
1023
1024 // The line must belong to this MO (checked before any stock movement is reversed)
1025 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
1026 $sql .= " WHERE rowid = ".((int) $idline)." AND fk_mo = ".((int) $this->id);
1027 $resql = $this->db->query($sql);
1028 if (!$resql || !$this->db->num_rows($resql)) {
1029 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1030 return -1;
1031 }
1032
1033 $productstatic = new Product($this->db);
1034
1035 $arrayoflines = $this->fetchLinesLinked('consumed', $idline); // Get lines consumed under the one to delete
1036
1037 // A line to produce can't be deleted once something was produced from it (the production would stay in stock)
1038 $arrayofproducedlines = $this->fetchLinesLinked('produced', $idline);
1039 if (!empty($arrayofproducedlines)) {
1040 $langs->load('errors');
1041 $this->error = $langs->trans('ErrorRecordHasChildren');
1042 return -1;
1043 }
1044
1045 $result = 0;
1046 $error = 0;
1047
1048 $this->db->begin();
1049
1050 if (!empty($fk_movement)) {
1051 $stockmove = new MouvementStock($this->db);
1052 $stockmove->setOrigin($this->element, $this->id);
1053
1054 // The fk_movement was not recorded so we try to guess the product and quantity to restore.
1055 $moline = new MoLine($this->db);
1056 $TArrayMoLine = $moline->fetchAll('', '', 1, 0, '(fk_stock_movement:=:'.((int) $fk_movement).')');
1057 $moline = is_array($TArrayMoLine) ? array_shift($TArrayMoLine) : null;
1058 if (!is_object($moline) || (int) $moline->fk_mo !== (int) $this->id) {
1059 $this->db->rollback();
1060 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1061 return -1;
1062 }
1063
1064 $movement = new MouvementStock($this->db);
1065 $movement->fetch($fk_movement);
1066 $productstatic->fetch($movement->product_id);
1067 $qtytoprocess = 0 - $movement->qty; // The value of the movement is the stock change, the reversal must apply the opposite
1068
1069 // Reverse stock movement
1070 $labelmovementCancel = $langs->transnoentitiesnoconv("CancelProductionForRef", $productstatic->ref);
1071 $codemovementCancel = $langs->transnoentitiesnoconv("StockIncrease");
1072
1073 if (($qtytoprocess >= 0)) {
1074 $idstockmove = $stockmove->reception($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, '', '', $movement->batch, dol_now(), 0, $codemovementCancel);
1075 } else {
1076 $idstockmove = $stockmove->livraison($user, $movement->product_id, $movement->warehouse_id, abs($qtytoprocess), 0, $labelmovementCancel, dol_now(), '', '', $movement->batch, 0, $codemovementCancel);
1077 }
1078 if ($idstockmove < 0) {
1079 $this->setErrorsFromObject($stockmove);
1080 } else {
1081 $result = $moline->delete($user, $notrigger);
1082 }
1083 } elseif (!empty($arrayoflines)) {
1084 $stockmove = new MouvementStock($this->db);
1085 $stockmove->setOrigin($this->element, $this->id);
1086
1087 // Loop on each child lines
1088 foreach ($arrayoflines as $key => $arrayofline) {
1089 $lineDetails = $arrayoflines[$key];
1090 $productstatic->fetch($lineDetails['fk_product']);
1091 $qtytoprocess = $lineDetails['qty'];
1092
1093 // Reverse stock movement
1094 $labelmovementCancel = $langs->transnoentitiesnoconv("CancelProductionForRef", $productstatic->ref);
1095 $codemovementCancel = $langs->transnoentitiesnoconv("StockIncrease");
1096
1097
1098 if ($qtytoprocess >= 0) {
1099 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1100 } else {
1101 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], abs($qtytoprocess), 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1102 }
1103 if ($idstockmove < 0) {
1104 $error++;
1105 $this->setErrorsFromObject($stockmove);
1106 } else {
1107 $moline = new MoLine($this->db);
1108 $moline->fetch($lineDetails['rowid']);
1109
1110 $resdel = $moline->delete($user, $notrigger);
1111 if ($resdel < 0) {
1112 $error++;
1113 $this->setErrorsFromObject($moline);
1114 }
1115 }
1116
1117 if ($error == 0) {
1118 $result = $this->deleteLineCommon($user, $idline, $notrigger);
1119 }
1120 }
1121 } else {
1122 // No child lines and no associated movement
1123 $result = $this->deleteLineCommon($user, $idline, $notrigger);
1124 }
1125
1126 if ($error != 0 || $result <= 0) {
1127 $this->db->rollback();
1128 } else {
1129 $this->db->commit();
1130 }
1131
1132 return $result;
1133 }
1134
1135
1143 public function getNextNumRef($prod)
1144 {
1145 global $langs, $conf;
1146 $langs->load("mrp");
1147
1148 if (getDolGlobalString('MRP_MO_ADDON')) {
1149 $mybool = false;
1150
1151 $file = getDolGlobalString('MRP_MO_ADDON') . ".php";
1152 $classname = getDolGlobalString('MRP_MO_ADDON');
1153
1154 // Include file with class
1155 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1156 foreach ($dirmodels as $reldir) {
1157 $dir = dol_buildpath($reldir."core/modules/mrp/");
1158
1159 // Load file with numbering class (if found)
1160 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1161 }
1162
1163 if (!$mybool) {
1164 dol_print_error(null, "Failed to include file ".$file);
1165 return '';
1166 }
1167
1168 $obj = new $classname();
1169 '@phan-var-force ModeleNumRefMos $obj';
1170 $numref = $obj->getNextValue($prod, $this);
1171
1172 if ($numref != "") {
1173 return $numref;
1174 } else {
1175 $this->error = $obj->error;
1176 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1177 return "";
1178 }
1179 } else {
1180 print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
1181 return "";
1182 }
1183 }
1184
1192 public function validate($user, $notrigger = 0)
1193 {
1194 global $conf;
1195
1196 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1197
1198 $error = 0;
1199
1200 // Protection
1201 if ($this->status == self::STATUS_VALIDATED) {
1202 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
1203 return 0;
1204 }
1205
1206 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->create))
1207 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->mrp_advance->validate))))
1208 {
1209 $this->error='NotEnoughPermissions';
1210 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1211 return -1;
1212 }*/
1213
1214 $now = dol_now();
1215
1216 $this->db->begin();
1217
1218 // Define new ref
1219 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1220 $this->fetch_product();
1221 $num = $this->getNextNumRef($this->product);
1222 } else {
1223 $num = (string) $this->ref;
1224 }
1225 $this->newref = $num;
1226
1227 // Validate
1228 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1229 $sql .= " SET ref = '".$this->db->escape($num)."',";
1230 $sql .= " status = ".self::STATUS_VALIDATED.",";
1231 $sql .= " date_valid = '".$this->db->idate($now)."',";
1232 $sql .= " fk_user_valid = ".((int) $user->id).",";
1233 $sql .= " fk_user_modif = ".((int) $user->id);
1234 $sql .= " WHERE rowid = ".((int) $this->id);
1235
1236 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
1237 $resql = $this->db->query($sql);
1238 if (!$resql) {
1239 dol_print_error($this->db);
1240 $this->error = $this->db->lasterror();
1241 $error++;
1242 }
1243
1244 if (!$error && !$notrigger) {
1245 // Call trigger
1246 $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
1247 if ($result < 0) {
1248 $error++;
1249 }
1250 // End call triggers
1251 }
1252
1253 if (!$error) {
1254 $this->oldref = $this->ref;
1255
1256 // Rename directory if dir was a temporary ref
1257 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1258 // Now we rename also files into index
1259 $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)."'";
1260 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1261 $resql = $this->db->query($sql);
1262 if (!$resql) {
1263 $error++;
1264 $this->error = $this->db->lasterror();
1265 }
1266 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'mrp/".$this->db->escape($this->newref)."'";
1267 $sql .= " WHERE filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1268 $resql = $this->db->query($sql);
1269 if (!$resql) {
1270 $error++;
1271 $this->error = $this->db->lasterror();
1272 }
1273
1274 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1275 $oldref = dol_sanitizeFileName($this->ref);
1276 $newref = dol_sanitizeFileName($num);
1277 $dirsource = $conf->mrp->dir_output.'/'.$oldref;
1278 $dirdest = $conf->mrp->dir_output.'/'.$newref;
1279 if (!$error && file_exists($dirsource)) {
1280 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
1281
1282 if (@rename($dirsource, $dirdest)) {
1283 dol_syslog("Rename ok");
1284 // Rename docs starting with $oldref with $newref
1285 $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1286 foreach ($listoffiles as $fileentry) {
1287 $dirsource = $fileentry['name'];
1288 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1289 $dirsource = $fileentry['path'].'/'.$dirsource;
1290 $dirdest = $fileentry['path'].'/'.$dirdest;
1291 @rename($dirsource, $dirdest);
1292 }
1293 }
1294 }
1295 }
1296 }
1297
1298 // Set new ref and current status
1299 if (!$error) {
1300 $this->ref = $num;
1301 $this->status = self::STATUS_VALIDATED;
1302 }
1303
1304 if (!$error) {
1305 $this->db->commit();
1306 return 1;
1307 } else {
1308 $this->db->rollback();
1309 return -1;
1310 }
1311 }
1312
1323 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = 'fk_statut')
1324 {
1325 global $user;
1326
1327 $result = parent::setStatut($status, $elementId, $elementType, $trigkey, $fieldstatus);
1328 if ($result > 0 && empty($elementId) && empty($elementType)) {
1329 $this->setUserModif($user);
1330 }
1331
1332 return $result;
1333 }
1334
1344 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
1345 {
1346 $result = parent::setStatusCommon($user, $status, $notrigger, $triggercode);
1347 if ($result > 0) {
1348 $this->setUserModif($user);
1349 }
1350
1351 return $result;
1352 }
1353
1360 private function setUserModif($user)
1361 {
1362 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
1363 $sql .= " SET fk_user_modif = ".((int) $user->id);
1364 $sql .= " WHERE rowid = ".((int) $this->id);
1365 if ($this->db->query($sql)) {
1366 $this->fk_user_modif = $user->id;
1367 }
1368 }
1369
1377 public function setDraft($user, $notrigger = 0)
1378 {
1379 // Protection
1380 if ($this->status <= self::STATUS_DRAFT) {
1381 return 0;
1382 }
1383 // Once consumption or production has started, the lines can't be changed or reset any more
1384 if ($this->hasConsumedOrProducedLines()) {
1385 return -1;
1386 }
1387
1388 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1389 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1390 {
1391 $this->error='Permission denied';
1392 return -1;
1393 }*/
1394
1395 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MRP_MO_UNVALIDATE');
1396 }
1397
1406 public function cancel($user, $notrigger = 0, $also_cancel_consumed_and_produced_lines = false)
1407 {
1408 // Protection
1409 if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) {
1410 return 0;
1411 }
1412
1413 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1414 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1415 {
1416 $this->error='Permission denied';
1417 return -1;
1418 }*/
1419
1420 $error = 0;
1421 $this->db->begin();
1422
1423 if ($also_cancel_consumed_and_produced_lines) {
1424 $result = $this->cancelConsumedAndProducedLines($user, 0, true, $notrigger);
1425 if ($result < 0) {
1426 $error++;
1427 }
1428 }
1429
1430 if (!$error) {
1431 $result = $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MRP_MO_CANCEL');
1432 if ($result < 0) {
1433 $error++;
1434 }
1435 }
1436
1437 if ($error) {
1438 $this->db->rollback();
1439 return -1;
1440 } else {
1441 $this->db->commit();
1442 return 1;
1443 }
1444 }
1445
1453 public function reopen($user, $notrigger = 0)
1454 {
1455 // Protection
1456 if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) {
1457 return 0;
1458 }
1459
1460 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1461 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1462 {
1463 $this->error='Permission denied';
1464 return -1;
1465 }*/
1466
1467 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MRP_MO_REOPEN');
1468 }
1469
1481 public function setCategories($categories)
1482 {
1483 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1484 return parent::setCategoriesCommon($categories, Categorie::TYPE_MO);
1485 }
1486
1496 public function cancelConsumedAndProducedLines($user, $mode = 0, $also_delete_lines = false, $notrigger = 0)
1497 {
1498 global $langs;
1499
1500 if (!isModEnabled('stock')) {
1501 return 1;
1502 }
1503
1504 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
1505 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
1506 $error = 0;
1507 $langs->load('stocks');
1508
1509 $this->db->begin();
1510
1511 // Cancel consumed lines
1512 if (empty($mode) || $mode == 1) {
1513 $arrayoflines = $this->fetchLinesLinked('consumed');
1514 if (!empty($arrayoflines)) {
1515 foreach ($arrayoflines as $key => $lineDetails) {
1516 $productstatic = new Product($this->db);
1517 $productstatic->fetch($lineDetails['fk_product']);
1518 $qtytoprocess = $lineDetails['qty'];
1519
1520 // Reverse stock movement
1521 $labelmovementCancel = $langs->transnoentitiesnoconv("CancelProductionForRef", $productstatic->ref);
1522 $codemovementCancel = $langs->transnoentitiesnoconv("StockIncrease");
1523
1524 $stockmove = new MouvementStock($this->db);
1525 $stockmove->setOrigin($this->element, $this->id);
1526 if ($qtytoprocess >= 0) {
1527 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1528 } else {
1529 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], abs($qtytoprocess), 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1530 }
1531 if ($idstockmove < 0) {
1532 $this->error = $stockmove->error;
1533 $this->errors = $stockmove->errors;
1534 $error++;
1535 break;
1536 }
1537
1538 if ($also_delete_lines) {
1539 $result = $this->deleteLineCommon($user, $lineDetails['rowid'], $notrigger);
1540 if ($result < 0) {
1541 $error++;
1542 break;
1543 }
1544 }
1545 }
1546 }
1547 }
1548
1549 // Cancel produced lines
1550 if (empty($mode) || $mode == 2) {
1551 $arrayoflines = $this->fetchLinesLinked('produced');
1552 if (!empty($arrayoflines)) {
1553 foreach ($arrayoflines as $key => $lineDetails) {
1554 $productstatic = new Product($this->db);
1555 $productstatic->fetch($lineDetails['fk_product']);
1556 $qtytoprocess = $lineDetails['qty'];
1557
1558 // Reverse stock movement
1559 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1560 $codemovementCancel = $langs->trans("StockDecrease");
1561
1562 $stockmove = new MouvementStock($this->db);
1563 $stockmove->setOrigin($this->element, $this->id);
1564 if ($qtytoprocess >= 0) {
1565 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1566 } else {
1567 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], abs($qtytoprocess), 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1568 }
1569 if ($idstockmove < 0) {
1570 $this->error = $stockmove->error;
1571 $this->errors = $stockmove->errors;
1572 $error++;
1573 break;
1574 }
1575
1576 if ($also_delete_lines) {
1577 $result = $this->deleteLineCommon($user, $lineDetails['rowid'], $notrigger);
1578 if ($result < 0) {
1579 $error++;
1580 break;
1581 }
1582 }
1583 }
1584 }
1585 }
1586
1587 if ($error) {
1588 $this->db->rollback();
1589 return -1;
1590 } else {
1591 $this->db->commit();
1592 return 1;
1593 }
1594 }
1595
1602 public function getTooltipContentArray($params)
1603 {
1604 global $langs;
1605
1606 $langs->loadLangs(['mrp', 'products']);
1607 $nofetch = isset($params['nofetch']);
1608
1609 $datas = [];
1610
1611 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ManufacturingOrder").'</u>';
1612 if (isset($this->status)) {
1613 $datas['picto'] .= ' '.$this->getLibStatut(5);
1614 }
1615 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1616 if (isset($this->label)) {
1617 $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1618 }
1619 if (isset($this->mrptype)) {
1620 $datas['type'] = '<br><b>'.$langs->trans('Type').':</b> '.$this->fields['mrptype']['arrayofkeyval'][$this->mrptype];
1621 }
1622 if (isset($this->qty)) {
1623 $datas['qty'] = '<br><b>'.$langs->trans('QtyToProduce').':</b> '.$this->qty;
1624 }
1625 if (!$nofetch && isset($this->fk_product)) {
1626 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
1627 $product = new Product($this->db);
1628 $product->fetch($this->fk_product);
1629 $datas['product'] = '<br><b>'.$langs->trans('Product').':</b> '.$product->getNomUrl(1, '', 0, -1, 1);
1630 }
1631 if (!$nofetch && isset($this->fk_warehouse)) {
1632 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
1633 $warehouse = new Entrepot($this->db);
1634 $warehouse->fetch($this->fk_warehouse);
1635 $datas['warehouse'] = '<br><b>'.$langs->trans('WarehouseForProduction').':</b> '.$warehouse->getNomUrl(1, '', 0, 1);
1636 }
1637
1638 return $datas;
1639 }
1640
1651 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1652 {
1653 global $conf, $langs, $action, $hookmanager;
1654
1655 if (!empty($conf->dol_no_mouse_hover)) {
1656 $notooltip = 1; // Force disable tooltips
1657 }
1658
1659 $result = '';
1660 $params = [
1661 'id' => $this->id,
1662 'objecttype' => $this->element,
1663 'option' => $option,
1664 'nofetch' => 1,
1665 ];
1666 $classfortooltip = 'classfortooltip';
1667 $dataparams = '';
1668 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1669 $classfortooltip = 'classforajaxtooltip';
1670 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1671 $label = '';
1672 } else {
1673 $label = implode($this->getTooltipContentArray($params));
1674 }
1675
1676 $baseurl = DOL_URL_ROOT.'/mrp/mo_card.php';
1677 if ($option == 'production') {
1678 $baseurl = DOL_URL_ROOT.'/mrp/mo_production.php';
1679 }
1680
1681 $query = ['id' => $this->id];
1682
1683 if ($option != 'nolink') {
1684 // Add param to save lastsearch_values or not
1685 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1686 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1687 $add_save_lastsearch_values = 1;
1688 }
1689 if ($add_save_lastsearch_values) {
1690 $query = array_merge($query, ['save_lastsearch_values' => 1]);
1691 }
1692 }
1693 $url = dolBuildUrl($baseurl, $query);
1694
1695 $linkclose = '';
1696 if (empty($notooltip)) {
1697 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1698 $label = $langs->trans("ShowMo");
1699 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1700 }
1701 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1702 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1703 } else {
1704 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1705 }
1706
1707 $linkstart = '<a href="'.$url.'"';
1708 $linkstart .= $linkclose.'>';
1709 $linkend = '</a>';
1710
1711 $result .= $linkstart;
1712 if ($withpicto) {
1713 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1714 }
1715 if ($withpicto != 2) {
1716 $result .= $this->ref;
1717 }
1718 $result .= $linkend;
1719 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1720
1721 $hookmanager->initHooks(array('modao'));
1722 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1723 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1724 if ($reshook > 0) {
1725 $result = $hookmanager->resPrint;
1726 } else {
1727 $result .= $hookmanager->resPrint;
1728 }
1729
1730 return $result;
1731 }
1732
1739 public function getLibStatut($mode = 0)
1740 {
1741 return $this->LibStatut($this->status, $mode);
1742 }
1743
1744 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1752 public function LibStatut($status, $mode = 0)
1753 {
1754 // phpcs:enable
1755 if (empty($this->labelStatus)) {
1756 global $langs;
1757 //$langs->load("mrp");
1758 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1759 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatedToProduce');
1760 $this->labelStatus[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1761 $this->labelStatus[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1762 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1763
1764 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1765 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
1766 $this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1767 $this->labelStatusShort[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1768 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1769 }
1770
1771 $statusType = 'status'.$status;
1772 if ($status == self::STATUS_VALIDATED) {
1773 $statusType = 'status1';
1774 }
1775 if ($status == self::STATUS_INPROGRESS) {
1776 $statusType = 'status4';
1777 }
1778 if ($status == self::STATUS_PRODUCED) {
1779 $statusType = 'status6';
1780 }
1781 if ($status == self::STATUS_CANCELED) {
1782 $statusType = 'status9';
1783 }
1784
1785 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1786 }
1787
1794 public function info($id)
1795 {
1796 $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1797 $sql .= ' fk_user_creat, fk_user_modif';
1798 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1799 $sql .= ' WHERE t.rowid = '.((int) $id);
1800 $result = $this->db->query($sql);
1801 if ($result) {
1802 if ($this->db->num_rows($result)) {
1803 $obj = $this->db->fetch_object($result);
1804
1805 $this->id = $obj->rowid;
1806
1807 $this->user_creation_id = $obj->fk_user_creat;
1808 $this->user_modification_id = $obj->fk_user_modif;
1809 $this->date_creation = $this->db->jdate($obj->datec);
1810 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1811 }
1812
1813 $this->db->free($result);
1814 } else {
1815 dol_print_error($this->db);
1816 }
1817 }
1818
1825 public function initAsSpecimen()
1826 {
1827 $ret = $this->initAsSpecimenCommon();
1828
1829 $this->lines = array();
1830
1831 return $ret;
1832 }
1833
1840 public function getLinesArray($rolefilter = '')
1841 {
1842 $this->lines = array();
1843
1844 $objectline = new MoLine($this->db);
1845
1846 $filter = '(fk_mo:=:'.((int) $this->id).')';
1847 if (!empty($rolefilter)) {
1848 $filter .= " AND (role:=:'".$this->db->escape($rolefilter)."')";
1849 }
1850 $result = $objectline->fetchAll('ASC', 'position', 0, 0, $filter);
1851
1852 if (is_numeric($result)) {
1853 $this->error = $objectline->error;
1854 $this->errors = $objectline->errors;
1855 return $result;
1856 } else {
1857 $this->lines = $result;
1858 return $this->lines;
1859 }
1860 }
1861
1873 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1874 {
1875 global $langs;
1876
1877 $langs->load("mrp");
1878
1879 if (!dol_strlen($modele)) {
1880 //$modele = 'standard';
1881 $modele = ''; // Remove this once a pdf_standard.php exists.
1882
1883 if ($this->model_pdf) {
1884 $modele = $this->model_pdf;
1885 } elseif (getDolGlobalString('MRP_MO_ADDON_PDF')) {
1886 $modele = getDolGlobalString('MRP_MO_ADDON_PDF');
1887 }
1888 }
1889
1890 $modelpath = "core/modules/mrp/doc/";
1891
1892 if (empty($modele)) {
1893 return 1; // Remove this once a pdf_standard.php exists.
1894 }
1895
1896 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1897 }
1898
1909 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
1910 {
1911 global $langs, $hookmanager, $form, $action;
1912
1913 $langs->load('stocks');
1914 $text_stock_options = $langs->trans("RealStockDesc").'<br>';
1915 $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen").'<br>';
1916 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE') ? '- '.$langs->trans("DeStockOnShipment").'<br>' : '');
1917 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') ? '- '.$langs->trans("DeStockOnValidateOrder").'<br>' : '');
1918 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_BILL') ? '- '.$langs->trans("DeStockOnBill").'<br>' : '');
1919 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') ? '- '.$langs->trans("ReStockOnBill").'<br>' : '');
1920 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER') ? '- '.$langs->trans("ReStockOnValidateOrder").'<br>' : '');
1921 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER') ? '- '.$langs->trans("ReStockOnDispatchOrder").'<br>' : '');
1922 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE') ? '- '.$langs->trans("StockOnReception").'<br>' : '');
1923
1924 print '<tr class="liste_titre">';
1925 // Product or sub-bom
1926 print '<td class="linecoldescription">'.$langs->trans('Ref');
1927 if (getDolGlobalString('BOM_SUB_BOM')) {
1928 print ' &nbsp; <a id="show_all" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a>&nbsp;&nbsp;';
1929 print '<a id="hide_all" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a>&nbsp;';
1930 }
1931 print '</td>';
1932 // Qty
1933 print '<td class="right">'.$langs->trans('Qty');
1934 if ($this->bom->bomtype == 0) {
1935 print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityOf", (string) $this->bom->qty).')</span>';
1936 } else {
1937 print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityToConsumeOf", (string) $this->bom->qty).')</span>';
1938 }
1939 // Unit
1940 print '<td class="right">'.$langs->trans('Unit');
1941
1942 print '</td>';
1943 print '<td class="center">'.$form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1).'</td>';
1944 print '<td class="center">'.$form->textwithpicto($langs->trans("VirtualStock"), $langs->trans("VirtualStockDesc")).'</td>';
1945 print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
1946 print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
1947 print '<td class="center">'.$langs->trans('MoChildGenerate').'</td>';
1948 //print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
1949 //print '<td class="center"></td>';
1950 print '</tr>';
1951 $i = 0;
1952
1953 if (!empty($this->lines)) {
1954 foreach ($this->lines as $line) {
1955 $reshook = 0;
1956 if (is_object($hookmanager)) {
1957 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
1958 if (!empty($line->fk_parent_line)) {
1959 $parameters['fk_parent_line'] = $line->fk_parent_line;
1960 }
1961 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1962 }
1963 if (empty($reshook)) {
1964 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
1965 }
1966
1967 $i++;
1968 }
1969 }
1970 }
1971
1972
1986 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
1987 {
1988 if (!$line instanceof MoLine) {
1989 dol_syslog(__METHOD__.'::pringOriginLine $line is '.get_class($line).'<>MoLine', LOG_WARNING);
1990 parent::printOriginLine($line, $var, $restrictlist, $defaulttpldir, $selectedLines);
1991 return;
1992 }
1993 $productstatic = new Product($this->db);
1994
1995 $this->tpl['id'] = $line->id;
1996
1997 $this->tpl['label'] = '';
1998 if (!empty($line->fk_product) && $line->fk_product > 0) {
1999 $productstatic->fetch($line->fk_product);
2000 $productstatic->load_stock(); // load_virtual_stock() is done in load_stock()
2001 $this->tpl['label'] .= $productstatic->getNomUrl(1);
2002 //$this->tpl['label'].= ' - '.$productstatic->label;
2003 } else {
2004 // If origin MO line is not a product, but another MO
2005 // TODO
2006 }
2007
2008 $this->tpl['qty_bom'] = 1;
2009 if (is_object($this->bom) && $this->bom->qty > 1) {
2010 $this->tpl['qty_bom'] = $this->bom->qty;
2011 }
2012
2013 $this->tpl['stock'] = $productstatic->stock_reel;
2014 $this->tpl['seuil_stock_alerte'] = $productstatic->seuil_stock_alerte;
2015 $this->tpl['virtual_stock'] = $productstatic->stock_theorique;
2016 $this->tpl['qty'] = $line->qty;
2017 $this->tpl['fk_unit'] = $line->fk_unit;
2018 $this->tpl['qty_frozen'] = $line->qty_frozen;
2019 $this->tpl['disable_stock_change'] = $line->disable_stock_change;
2020 $this->tpl['efficiency'] = $line->efficiency;
2021
2022
2023 global $conf; // used into template
2024 include DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
2025 }
2026
2035 public static function replaceThirdparty($db, $origin_id, $dest_id)
2036 {
2037 $tables = array('mrp_mo');
2038
2039 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2040 }
2041
2050 public static function replaceProduct($db, $origin_id, $dest_id)
2051 {
2052 $tables = array('mrp_mo', 'mrp_production');
2053
2054 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
2055 }
2056
2057
2063 public function getMoChilds()
2064 {
2065 $TMoChilds = array();
2066 $error = 0;
2067
2068 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_mo as mo_child";
2069 $sql .= " WHERE fk_parent_line IN ";
2070 $sql .= " (SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_production as line_parent";
2071 $sql .= " WHERE fk_mo=".((int) $this->id).")";
2072
2073 $resql = $this->db->query($sql);
2074
2075 if ($resql) {
2076 if ($this->db->num_rows($resql) > 0) {
2077 while ($obj = $this->db->fetch_object($resql)) {
2078 $MoChild = new Mo($this->db);
2079 $res = $MoChild->fetch($obj->rowid);
2080 if ($res > 0) {
2081 $TMoChilds[$MoChild->id] = $MoChild;
2082 } else {
2083 $error++;
2084 }
2085 }
2086 }
2087 } else {
2088 $error++;
2089 }
2090
2091 if ($error) {
2092 return -1;
2093 } else {
2094 return $TMoChilds;
2095 }
2096 }
2097
2104 public function getAllMoChilds($depth = 0)
2105 {
2106 if ($depth > 1000) {
2107 return -1;
2108 }
2109
2110 $TMoChilds = array();
2111 $error = 0;
2112
2113 $childMoList = $this->getMoChilds();
2114
2115 if ($childMoList == -1) {
2116 return -1;
2117 }
2118
2119 foreach ($childMoList as $childMo) {
2120 $TMoChilds[$childMo->id] = $childMo;
2121 }
2122
2123 foreach ($childMoList as $childMo) {
2124 $childMoChildren = $childMo->getAllMoChilds($depth + 1);
2125
2126 if ($childMoChildren == -1) {
2127 $error++;
2128 } else {
2129 foreach ($childMoChildren as $child) {
2130 $TMoChilds[$child->id] = $child;
2131 }
2132 }
2133 }
2134
2135 if ($error) {
2136 return -1;
2137 } else {
2138 return $TMoChilds;
2139 }
2140 }
2141
2142
2143
2149 public function getMoParent()
2150 {
2151 $MoParent = new Mo($this->db);
2152 $error = 0;
2153
2154 $sql = "SELECT lineparent.fk_mo as id_moparent FROM ".MAIN_DB_PREFIX."mrp_mo as mo";
2155 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."mrp_production lineparent ON mo.fk_parent_line = lineparent.rowid";
2156 $sql .= " WHERE mo.rowid = ".((int) $this->id);
2157
2158 $resql = $this->db->query($sql);
2159
2160 if ($resql) {
2161 if ($this->db->num_rows($resql) > 0) {
2162 $obj = $this->db->fetch_object($resql);
2163 $res = $MoParent->fetch($obj->id_moparent);
2164 if ($res < 0) {
2165 $error++;
2166 }
2167 } else {
2168 return 0;
2169 }
2170 } else {
2171 $error++;
2172 }
2173
2174 if ($error) {
2175 return -1;
2176 } else {
2177 return $MoParent;
2178 }
2179 }
2180
2181 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2188 public function load_board($user)
2189 {
2190 // phpcs:enable
2191 global $conf, $langs;
2192 if ($user->socid) {
2193 return -1; // Security to prohibit this function for an external user
2194 }
2195
2196 $now = dol_now();
2197 $warning_delay = $conf->mrp->progress->warning_delay;
2198
2199 // 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
2200 // a planned end date and that date is before now minus the warning delay.
2201 $sql = "SELECT COUNT(rowid) as nb,";
2202 $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";
2203 $sql .= " FROM ".$this->db->prefix()."mrp_mo";
2204 $sql .= " WHERE status IN (" . self::STATUS_VALIDATED . ", " . self::STATUS_INPROGRESS .")"; // 1 = Ouvert, 2 = En cours
2205 $sql .= " AND entity IN (".getEntity('mrp_mo').")";
2206
2207 $resql = $this->db->query($sql);
2208 if ($resql) {
2209 $langs->load("mrp");
2210 $response = new WorkboardResponse();
2211 $response->warning_delay = $warning_delay / 86400;
2212 $response->label = $langs->trans("MOProgress");
2213 $response->labelShort = $langs->trans("MOProgress");
2214 $response->url = DOL_URL_ROOT.'/mrp/mo_list.php?search_status=-2';
2215 $response->img = img_object('', "mrp");
2216
2217
2218 $obj = $this->db->fetch_object($resql);
2219 if ($obj) {
2220 $response->nbtodo = (int) $obj->nb;
2221 $response->nbtodolate = (int) $obj->nblate;
2222 if ($response->nbtodolate > 0) {
2223 $response->url_late = DOL_URL_ROOT.'/mrp/mo_list.php?search_status=-2&search_option=late';
2224 }
2225 }
2226
2227 return $response;
2228 } else {
2229 dol_print_error($this->db);
2230 $this->error = $this->db->error();
2231 return -1;
2232 }
2233 }
2234
2240 public function hasDelay()
2241 {
2242 global $conf;
2243
2244 if ($this->status != Mo::STATUS_VALIDATED && $this->status != Mo::STATUS_INPROGRESS) {
2245 return false;
2246 }
2247 if (empty($this->date_end_planned)) {
2248 return false;
2249 }
2250 return (dol_now() > ((int) $this->date_end_planned + $conf->mrp->progress->warning_delay));
2251 }
2252
2253
2261 public function getKanbanView($option = '', $arraydata = null)
2262 {
2263 global $langs;
2264 '@phan-var-force array{selected?:int<0,1>,bom?:Bom,product?:product} $arraydata';
2265
2266 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2267
2268 $return = '<div class="box-flex-item box-flex-grow-zero">';
2269 $return .= '<div class="info-box info-box-sm">';
2270 $return .= '<span class="info-box-icon bg-infobox-action">';
2271 $return .= img_picto('', $this->picto);
2272 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2273 $return .= '</span>';
2274 $return .= '<div class="info-box-content">';
2275 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2276 if ($selected >= 0) {
2277 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2278 }
2279 if (!empty($arraydata['bom'])) {
2280 $return .= '<br><span class="info-box-label">'.$arraydata['bom']->getNomUrl(1).'</span>';
2281 }
2282 if (!empty($arraydata['product'])) {
2283 $return .= '<br><span class="info-box-label">'.$arraydata['product']->getNomUrl(1).'</span>';
2284 if (property_exists($this, 'qty')) {
2285 $return .= ' <span class="info-box-label">('.$langs->trans("Qty").' '.$this->qty.')</span>';
2286 }
2287 } else {
2288 if (property_exists($this, 'qty')) {
2289 $return .= '<br><span class="info-box-label">'.$langs->trans('Quantity').' : '.$this->qty.'</span>';
2290 }
2291 }
2292 if (method_exists($this, 'getLibStatut')) {
2293 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2294 }
2295 $return .= '</div>';
2296 $return .= '</div>';
2297 $return .= '</div>';
2298 return $return;
2299 }
2300}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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.
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.
static commonReplaceProduct(DoliDB $dbs, $origin_id, $dest_id, array $tables, $ignoreerrors=0)
Function used to replace a product id with another one.
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
hasConsumedOrProducedLines()
Return if consumption or production has started on the MO (it has consumed or produced lines).
Definition mo.class.php:665
fetchLinesLinked($role, $lineid=0)
Get list of lines linked to current line for a defined role.
Definition mo.class.php:613
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 ...
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set status of the MO and record the user who changed it.
fetchLines()
Load object lines in memory from the database.
Definition mo.class.php:509
getNextNumRef($prod)
Returns the reference to the following non used MO depending on the active numbering module defined i...
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='fk_statut')
Set status of the MO and record the user who changed it.
create(User $user, $notrigger=0)
Create object into database.
Definition mo.class.php:332
fetch($id, $ref=null)
Load object in memory from the database.
Definition mo.class.php:492
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load list of objects in memory from the database.
Definition mo.class.php:529
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:841
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:911
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:718
setUserModif($user)
Record the user of the last change, as the generic status setters only update the status.
static replaceProduct($db, $origin_id, $dest_id)
Function used to replace a product id with another one.
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:752
deleteLine(User $user, $idline, $notrigger=0, $fk_movement=0)
Delete a line of object in database.
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:683
createFromClone(User $user, $fromid)
Clone an object into another one.
Definition mo.class.php:389
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
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:66
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
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.
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.