dolibarr 24.0.3
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
664 {
665 global $langs;
666
667 if (count($this->fetchLinesLinked('consumed')) || count($this->fetchLinesLinked('produced'))) {
668 $langs->load('mrp');
669 $this->error = $langs->trans('ErrorMoConsumptionOrProductionStarted');
670 return true;
671 }
672
673 return false;
674 }
675
681 public function countMovements()
682 {
683 $result = 0;
684
685 $sql = 'SELECT COUNT(rowid) as nb FROM '.MAIN_DB_PREFIX.'stock_mouvement as sm';
686 $sql .= " WHERE sm.origintype = 'mo' and sm.fk_origin = ".((int) $this->id);
687
688 $resql = $this->db->query($sql);
689 if ($resql) {
690 $num = $this->db->num_rows($resql);
691
692 $i = 0;
693 while ($i < $num) {
694 $obj = $this->db->fetch_object($resql);
695 if ($obj) {
696 $result = $obj->nb;
697 }
698
699 $i++;
700 }
701 } else {
702 $this->error = $this->db->lasterror();
703 }
704
705 return $result;
706 }
707
708
716 public function update(User $user, $notrigger = 0)
717 {
718 $error = 0;
719
720 $this->db->begin();
721
722 $result = $this->updateCommon($user, $notrigger);
723 if ($result <= 0) {
724 $error++;
725 }
726
727 // Update the lines (the qty) to consume or to produce
728 $result = $this->updateProduction($user, $notrigger);
729 if ($result <= 0) {
730 $error++;
731 }
732
733 if (!$error) {
734 $this->db->commit();
735 return 1;
736 } else {
737 $this->db->rollback();
738 return -1;
739 }
740 }
741
742
750 public function createProduction(User $user, $notrigger = 0)
751 {
752 $error = 0;
753 $role = "";
754
755 // The consumed and produced lines can't be deleted here, their stock movements would not be reversed
756 if ($this->hasConsumedOrProducedLines()) {
757 return -1;
758 }
759
760 if ($this->status != self::STATUS_DRAFT) {
761 dol_syslog("Bad status for MO object. Can't add production lines. Check that MO has status DRAFT.");
762 $this->error = "Bad status for MO object. Can't add production lines. Check that MO has status DRAFT.";
763 return -1;
764 }
765
766 $this->db->begin();
767
768 // Insert lines in mrp_production table from BOM data
769
770 $sql = 'DELETE FROM '.MAIN_DB_PREFIX.'mrp_production WHERE fk_mo = '.((int) $this->id);
771 $this->db->query($sql);
772
773 $moline = new MoLine($this->db);
774
775 // Line to produce
776 $moline->fk_mo = (int) $this->id;
777 $moline->qty = (float) $this->qty;
778 $moline->fk_product = (int) $this->fk_product;
779 $moline->fk_warehouse = (int) $this->fk_warehouse;
780 $moline->position = 1;
781
782 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
783 $tmpproduct = new Product($this->db);
784 $tmpproduct->fetch((int) $this->fk_product);
785 $moline->fk_unit = $tmpproduct->fk_unit;
786
787 if ($this->fk_bom > 0) { // If a BOM is defined, we know what to produce.
788 include_once DOL_DOCUMENT_ROOT.'/bom/class/bom.class.php';
789 $bom = new BOM($this->db);
790 $bom->fetch($this->fk_bom);
791 if ($bom->bomtype == 1) {
792 $role = 'toproduce';
793 $moline->role = 'toconsume';
794 } else {
795 $role = 'toconsume';
796 $moline->role = 'toproduce';
797 }
798 } else {
799 $bom = null;
800 if ($this->mrptype == 1) {
801 $moline->role = 'toconsume';
802 } else {
803 $moline->role = 'toproduce';
804 }
805 }
806
807 $resultline = $moline->create($user, 0); // Never use triggers here
808 if ($resultline <= 0) {
809 $error++;
810 $this->setErrorsFromObject($moline);
811 }
812
813 if ($this->fk_bom > 0 && is_object($bom)) { // If a BOM is defined, we know what to consume.
814 if ($bom->id > 0) {
815 // process lines to consume, this needs to recurse through BOM's
816 $error += $this->processBOM($user, $role, $bom, (float) $this->qty);
817 }
818 }
819
820 if (!$error) {
821 $this->db->commit();
822 return 1;
823 } else {
824 $this->db->rollback();
825 return -1;
826 }
827 }
828
829
839 public function processBOM(User $user, $role, $bom, $quantity)
840 {
841 $error = 0;
842
843 $quantity /= $bom->qty;
844 foreach ($bom->lines as $line) {
845 $quantity_line = !$line->qty_frozen ? $line->qty * $quantity / (!empty($line->efficiency) ? $line->efficiency : 1) : $line->qty;
846
847 $tmpproduct = new Product($this->db);
848 $tmpproduct->fetch($line->fk_product);
849 if ($line->fk_bom_child > 0 && !in_array($line->id, $this->noFlattenBomLineIds)) {
850 $bom = new BOM($this->db);
851 $bom->fetch((int) $line->fk_bom_child);
852 $error += $this->processBOM($user, $role, $bom, $quantity_line);
853 } else {
854 $moline = new MoLine($this->db);
855 $moline->fk_mo = $this->id;
856 $moline->origin_id = $line->id;
857 $moline->origin_type = 'bomline';
858 if (!empty($line->fk_unit)) {
859 $moline->fk_unit = $line->fk_unit;
860 }
861
862 $moline->qty = (float) price2num($quantity_line, 'MS'); // Calculate with Qty to produce and more presition
863 if ($moline->qty <= 0) {
864 $error++;
865 $this->error = "BadValueForquantityToConsume";
866 $this->errors[] = $this->error;
867 } else {
868 $moline->fk_product = $line->fk_product;
869 //$moline->fk_warehouse = !empty($line->fk_warehouse) ? $line->fk_warehouse : (!empty($bom->fk_warehouse) ? $bom->fk_warehouse : $this->fk_warehouse);
870 if (in_array($role, array('toconsume', 'consumed'))) {
871 $moline->fk_warehouse = null;
872 } else { // to produce / produced
873 $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.
874 }
875 $moline->role = $role;
876 $moline->position = $line->position;
877 $moline->qty_frozen = $line->qty_frozen;
878 $moline->disable_stock_change = $line->disable_stock_change;
879 if (!empty($line->fk_default_workstation)) {
880 $moline->fk_default_workstation = $line->fk_default_workstation;
881 }
882
883 $resultline = $moline->create($user, 0); // Never use triggers here
884 //var_dump($moline);
885 if ($resultline <= 0) {
886 $error++;
887 $this->error = $moline->error;
888 $this->errors[] = $moline->error;
889 $this->errors = array_merge($this->errors, $moline->errors);
890 dol_print_error($this->db, $moline->error, $moline->errors);
891 }
892 }
893 }
894 if ($error) {
895 break;
896 }
897 }
898 return $error;
899 }
900
901
909 public function updateProduction(User $user, $notrigger = 0)
910 {
911 $error = 0;
912
913 if ($this->status != self::STATUS_DRAFT) {
914 return 1;
915 }
916
917 $this->db->begin();
918
919 $oldQty = $this->oldQty;
920 $newQty = $this->qty;
921 if ($newQty != $oldQty && !empty($this->oldQty)) {
922 $sql = "SELECT rowid FROM " . MAIN_DB_PREFIX . "mrp_production WHERE fk_mo = " . (int) $this->id;
923 $resql = $this->db->query($sql);
924 if ($resql) {
925 while ($obj = $this->db->fetch_object($resql)) {
926 $moLine = new MoLine($this->db);
927 $res = $moLine->fetch($obj->rowid);
928 if (!$res) {
929 $error++;
930 }
931
932 if ($moLine->role == 'toconsume' || $moLine->role == 'toproduce') {
933 if (empty($moLine->qty_frozen)) {
934 $qty = $newQty * $moLine->qty / $oldQty;
935 $moLine->qty = (float) price2num($qty, 'MS');
936 $res = $moLine->update($user);
937 if (!$res) {
938 $error++;
939 }
940 }
941 }
942 }
943 }
944 }
945 if (!$error) {
946 $this->db->commit();
947 return 1;
948 } else {
949 $this->db->rollback();
950 return -1;
951 }
952 }
953
954
963 public function delete(User $user, $notrigger = 0, $also_cancel_consumed_and_produced_lines = false)
964 {
965 $error = 0;
966 $this->db->begin();
967
968 if ($also_cancel_consumed_and_produced_lines) {
969 $result = $this->cancelConsumedAndProducedLines($user, 0, false, $notrigger);
970 if ($result < 0) {
971 $error++;
972 }
973 }
974
975 // Remove linked categories.
976 if (!$error) {
977 $sql = "DELETE FROM ".MAIN_DB_PREFIX."categorie_mo";
978 $sql .= " WHERE fk_mo = ".((int) $this->id);
979
980 $result = $this->db->query($sql);
981 if (!$result) {
982 $error++;
983 $this->errors[] = $this->db->lasterror();
984 }
985 }
986
987 if (!$error) {
988 $result = $this->deleteCommon($user, $notrigger);
989 if ($result < 0) {
990 $error++;
991 }
992 }
993
994 if ($error) {
995 $this->db->rollback();
996 return -1;
997 } else {
998 $this->db->commit();
999 return 1;
1000 }
1001 }
1002
1012 public function deleteLine(User $user, $idline, $notrigger = 0, $fk_movement = 0)
1013 {
1014 global $langs;
1015 $langs->loadLangs(array('stocks', 'mrp'));
1016
1017 if ($this->status < 0) {
1018 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
1019 return -2;
1020 }
1021
1022 // The line must belong to this MO (checked before any stock movement is reversed)
1023 $sql = "SELECT rowid FROM ".$this->db->prefix().$this->table_element_line;
1024 $sql .= " WHERE rowid = ".((int) $idline)." AND fk_mo = ".((int) $this->id);
1025 $resql = $this->db->query($sql);
1026 if (!$resql || !$this->db->num_rows($resql)) {
1027 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1028 return -1;
1029 }
1030
1031 $productstatic = new Product($this->db);
1032
1033 $arrayoflines = $this->fetchLinesLinked('consumed', $idline); // Get lines consumed under the one to delete
1034
1035 // A line to produce can't be deleted once something was produced from it (the production would stay in stock)
1036 $arrayofproducedlines = $this->fetchLinesLinked('produced', $idline);
1037 if (!empty($arrayofproducedlines)) {
1038 $langs->load('errors');
1039 $this->error = $langs->trans('ErrorRecordHasChildren');
1040 return -1;
1041 }
1042
1043 $result = 0;
1044 $error = 0;
1045
1046 $this->db->begin();
1047
1048 if (!empty($fk_movement)) {
1049 $stockmove = new MouvementStock($this->db);
1050 $stockmove->setOrigin($this->element, $this->id);
1051
1052 // The fk_movement was not recorded so we try to guess the product and quantity to restore.
1053 $moline = new MoLine($this->db);
1054 $TArrayMoLine = $moline->fetchAll('', '', 1, 0, '(fk_stock_movement:=:'.((int) $fk_movement).')');
1055 $moline = is_array($TArrayMoLine) ? array_shift($TArrayMoLine) : null;
1056 if (!is_object($moline) || (int) $moline->fk_mo !== (int) $this->id) {
1057 $this->db->rollback();
1058 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
1059 return -1;
1060 }
1061
1062 $movement = new MouvementStock($this->db);
1063 $movement->fetch($fk_movement);
1064 $productstatic->fetch($movement->product_id);
1065 $qtytoprocess = 0 - $movement->qty; // The value of the movement is the stock change, the reversal must apply the opposite
1066
1067 // Reverse stock movement
1068 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1069 $codemovementCancel = $langs->trans("StockIncrease");
1070
1071 if (($qtytoprocess >= 0)) {
1072 $idstockmove = $stockmove->reception($user, $movement->product_id, $movement->warehouse_id, $qtytoprocess, 0, $labelmovementCancel, '', '', $movement->batch, dol_now(), 0, $codemovementCancel);
1073 } else {
1074 $idstockmove = $stockmove->livraison($user, $movement->product_id, $movement->warehouse_id, abs($qtytoprocess), 0, $labelmovementCancel, dol_now(), '', '', $movement->batch, 0, $codemovementCancel);
1075 }
1076 if ($idstockmove < 0) {
1077 $this->setErrorsFromObject($stockmove);
1078 } else {
1079 $result = $moline->delete($user, $notrigger);
1080 }
1081 } elseif (!empty($arrayoflines)) {
1082 $stockmove = new MouvementStock($this->db);
1083 $stockmove->setOrigin($this->element, $this->id);
1084
1085 // Loop on each child lines
1086 foreach ($arrayoflines as $key => $arrayofline) {
1087 $lineDetails = $arrayoflines[$key];
1088 $productstatic->fetch($lineDetails['fk_product']);
1089 $qtytoprocess = $lineDetails['qty'];
1090
1091 // Reverse stock movement
1092 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1093 $codemovementCancel = $langs->trans("StockIncrease");
1094
1095
1096 if ($qtytoprocess >= 0) {
1097 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1098 } else {
1099 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], abs($qtytoprocess), 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1100 }
1101 if ($idstockmove < 0) {
1102 $error++;
1103 $this->setErrorsFromObject($stockmove);
1104 } else {
1105 $moline = new MoLine($this->db);
1106 $moline->fetch($lineDetails['rowid']);
1107
1108 $resdel = $moline->delete($user, $notrigger);
1109 if ($resdel < 0) {
1110 $error++;
1111 $this->setErrorsFromObject($moline);
1112 }
1113 }
1114
1115 if ($error == 0) {
1116 $result = $this->deleteLineCommon($user, $idline, $notrigger);
1117 }
1118 }
1119 } else {
1120 // No child lines and no associated movement
1121 $result = $this->deleteLineCommon($user, $idline, $notrigger);
1122 }
1123
1124 if ($error != 0 || $result <= 0) {
1125 $this->db->rollback();
1126 } else {
1127 $this->db->commit();
1128 }
1129
1130 return $result;
1131 }
1132
1133
1141 public function getNextNumRef($prod)
1142 {
1143 global $langs, $conf;
1144 $langs->load("mrp");
1145
1146 if (getDolGlobalString('MRP_MO_ADDON')) {
1147 $mybool = false;
1148
1149 $file = getDolGlobalString('MRP_MO_ADDON') . ".php";
1150 $classname = getDolGlobalString('MRP_MO_ADDON');
1151
1152 // Include file with class
1153 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
1154 foreach ($dirmodels as $reldir) {
1155 $dir = dol_buildpath($reldir."core/modules/mrp/");
1156
1157 // Load file with numbering class (if found)
1158 $mybool = ((bool) @include_once $dir.$file) || $mybool;
1159 }
1160
1161 if (!$mybool) {
1162 dol_print_error(null, "Failed to include file ".$file);
1163 return '';
1164 }
1165
1166 $obj = new $classname();
1167 '@phan-var-force ModeleNumRefMos $obj';
1168 $numref = $obj->getNextValue($prod, $this);
1169
1170 if ($numref != "") {
1171 return $numref;
1172 } else {
1173 $this->error = $obj->error;
1174 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
1175 return "";
1176 }
1177 } else {
1178 print $langs->trans("Error")." ".$langs->trans("Error_MRP_MO_ADDON_NotDefined");
1179 return "";
1180 }
1181 }
1182
1190 public function validate($user, $notrigger = 0)
1191 {
1192 global $conf;
1193
1194 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1195
1196 $error = 0;
1197
1198 // Protection
1199 if ($this->status == self::STATUS_VALIDATED) {
1200 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
1201 return 0;
1202 }
1203
1204 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->create))
1205 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mrp->mrp_advance->validate))))
1206 {
1207 $this->error='NotEnoughPermissions';
1208 dol_syslog(get_class($this)."::valid ".$this->error, LOG_ERR);
1209 return -1;
1210 }*/
1211
1212 $now = dol_now();
1213
1214 $this->db->begin();
1215
1216 // Define new ref
1217 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
1218 $this->fetch_product();
1219 $num = $this->getNextNumRef($this->product);
1220 } else {
1221 $num = (string) $this->ref;
1222 }
1223 $this->newref = $num;
1224
1225 // Validate
1226 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
1227 $sql .= " SET ref = '".$this->db->escape($num)."',";
1228 $sql .= " status = ".self::STATUS_VALIDATED.",";
1229 $sql .= " date_valid = '".$this->db->idate($now)."',";
1230 $sql .= " fk_user_valid = ".((int) $user->id).",";
1231 $sql .= " fk_user_modif = ".((int) $user->id);
1232 $sql .= " WHERE rowid = ".((int) $this->id);
1233
1234 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
1235 $resql = $this->db->query($sql);
1236 if (!$resql) {
1237 dol_print_error($this->db);
1238 $this->error = $this->db->lasterror();
1239 $error++;
1240 }
1241
1242 if (!$error && !$notrigger) {
1243 // Call trigger
1244 $result = $this->call_trigger('MRP_MO_VALIDATE', $user);
1245 if ($result < 0) {
1246 $error++;
1247 }
1248 // End call triggers
1249 }
1250
1251 if (!$error) {
1252 $this->oldref = $this->ref;
1253
1254 // Rename directory if dir was a temporary ref
1255 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
1256 // Now we rename also files into index
1257 $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)."'";
1258 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1259 $resql = $this->db->query($sql);
1260 if (!$resql) {
1261 $error++;
1262 $this->error = $this->db->lasterror();
1263 }
1264 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'mrp/".$this->db->escape($this->newref)."'";
1265 $sql .= " WHERE filepath = 'mrp/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1266 $resql = $this->db->query($sql);
1267 if (!$resql) {
1268 $error++;
1269 $this->error = $this->db->lasterror();
1270 }
1271
1272 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1273 $oldref = dol_sanitizeFileName($this->ref);
1274 $newref = dol_sanitizeFileName($num);
1275 $dirsource = $conf->mrp->dir_output.'/'.$oldref;
1276 $dirdest = $conf->mrp->dir_output.'/'.$newref;
1277 if (!$error && file_exists($dirsource)) {
1278 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
1279
1280 if (@rename($dirsource, $dirdest)) {
1281 dol_syslog("Rename ok");
1282 // Rename docs starting with $oldref with $newref
1283 $listoffiles = dol_dir_list($conf->mrp->dir_output.'/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1284 foreach ($listoffiles as $fileentry) {
1285 $dirsource = $fileentry['name'];
1286 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1287 $dirsource = $fileentry['path'].'/'.$dirsource;
1288 $dirdest = $fileentry['path'].'/'.$dirdest;
1289 @rename($dirsource, $dirdest);
1290 }
1291 }
1292 }
1293 }
1294 }
1295
1296 // Set new ref and current status
1297 if (!$error) {
1298 $this->ref = $num;
1299 $this->status = self::STATUS_VALIDATED;
1300 }
1301
1302 if (!$error) {
1303 $this->db->commit();
1304 return 1;
1305 } else {
1306 $this->db->rollback();
1307 return -1;
1308 }
1309 }
1310
1321 public function setStatut($status, $elementId = null, $elementType = '', $trigkey = '', $fieldstatus = '')
1322 {
1323 global $user;
1324
1325 $result = parent::setStatut($status, $elementId, $elementType, $trigkey, $fieldstatus);
1326 if ($result > 0 && empty($elementId) && empty($elementType)) {
1327 $this->setUserModif($user);
1328 }
1329
1330 return $result;
1331 }
1332
1342 public function setStatusCommon($user, $status, $notrigger = 0, $triggercode = '')
1343 {
1344 $result = parent::setStatusCommon($user, $status, $notrigger, $triggercode);
1345 if ($result > 0) {
1346 $this->setUserModif($user);
1347 }
1348
1349 return $result;
1350 }
1351
1358 private function setUserModif($user)
1359 {
1360 $sql = "UPDATE ".$this->db->prefix().$this->table_element;
1361 $sql .= " SET fk_user_modif = ".((int) $user->id);
1362 $sql .= " WHERE rowid = ".((int) $this->id);
1363 if ($this->db->query($sql)) {
1364 $this->fk_user_modif = $user->id;
1365 }
1366 }
1367
1375 public function setDraft($user, $notrigger = 0)
1376 {
1377 // Protection
1378 if ($this->status <= self::STATUS_DRAFT) {
1379 return 0;
1380 }
1381 // Once consumption or production has started, the lines can't be changed or reset any more
1382 if ($this->hasConsumedOrProducedLines()) {
1383 return -1;
1384 }
1385
1386 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1387 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1388 {
1389 $this->error='Permission denied';
1390 return -1;
1391 }*/
1392
1393 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'MRP_MO_UNVALIDATE');
1394 }
1395
1404 public function cancel($user, $notrigger = 0, $also_cancel_consumed_and_produced_lines = false)
1405 {
1406 // Protection
1407 if ($this->status != self::STATUS_VALIDATED && $this->status != self::STATUS_INPROGRESS) {
1408 return 0;
1409 }
1410
1411 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1412 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1413 {
1414 $this->error='Permission denied';
1415 return -1;
1416 }*/
1417
1418 $error = 0;
1419 $this->db->begin();
1420
1421 if ($also_cancel_consumed_and_produced_lines) {
1422 $result = $this->cancelConsumedAndProducedLines($user, 0, true, $notrigger);
1423 if ($result < 0) {
1424 $error++;
1425 }
1426 }
1427
1428 if (!$error) {
1429 $result = $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'MRP_MO_CANCEL');
1430 if ($result < 0) {
1431 $error++;
1432 }
1433 }
1434
1435 if ($error) {
1436 $this->db->rollback();
1437 return -1;
1438 } else {
1439 $this->db->commit();
1440 return 1;
1441 }
1442 }
1443
1451 public function reopen($user, $notrigger = 0)
1452 {
1453 // Protection
1454 if ($this->status != self::STATUS_PRODUCED && $this->status != self::STATUS_CANCELED) {
1455 return 0;
1456 }
1457
1458 /*if (! ((empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->write))
1459 || (!empty($conf->global->MAIN_USE_ADVANCED_PERMS) && !empty($user->rights->mymodule->mymodule_advance->validate))))
1460 {
1461 $this->error='Permission denied';
1462 return -1;
1463 }*/
1464
1465 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'MRP_MO_REOPEN');
1466 }
1467
1479 public function setCategories($categories)
1480 {
1481 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
1482 return parent::setCategoriesCommon($categories, Categorie::TYPE_MO);
1483 }
1484
1494 public function cancelConsumedAndProducedLines($user, $mode = 0, $also_delete_lines = false, $notrigger = 0)
1495 {
1496 global $langs;
1497
1498 if (!isModEnabled('stock')) {
1499 return 1;
1500 }
1501
1502 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
1503 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/mouvementstock.class.php';
1504 $error = 0;
1505 $langs->load('stocks');
1506
1507 $this->db->begin();
1508
1509 // Cancel consumed lines
1510 if (empty($mode) || $mode == 1) {
1511 $arrayoflines = $this->fetchLinesLinked('consumed');
1512 if (!empty($arrayoflines)) {
1513 foreach ($arrayoflines as $key => $lineDetails) {
1514 $productstatic = new Product($this->db);
1515 $productstatic->fetch($lineDetails['fk_product']);
1516 $qtytoprocess = $lineDetails['qty'];
1517
1518 // Reverse stock movement
1519 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1520 $codemovementCancel = $langs->trans("StockIncrease");
1521
1522 $stockmove = new MouvementStock($this->db);
1523 $stockmove->setOrigin($this->element, $this->id);
1524 if ($qtytoprocess >= 0) {
1525 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1526 } else {
1527 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], abs($qtytoprocess), 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1528 }
1529 if ($idstockmove < 0) {
1530 $this->error = $stockmove->error;
1531 $this->errors = $stockmove->errors;
1532 $error++;
1533 break;
1534 }
1535
1536 if ($also_delete_lines) {
1537 $result = $this->deleteLineCommon($user, $lineDetails['rowid'], $notrigger);
1538 if ($result < 0) {
1539 $error++;
1540 break;
1541 }
1542 }
1543 }
1544 }
1545 }
1546
1547 // Cancel produced lines
1548 if (empty($mode) || $mode == 2) {
1549 $arrayoflines = $this->fetchLinesLinked('produced');
1550 if (!empty($arrayoflines)) {
1551 foreach ($arrayoflines as $key => $lineDetails) {
1552 $productstatic = new Product($this->db);
1553 $productstatic->fetch($lineDetails['fk_product']);
1554 $qtytoprocess = $lineDetails['qty'];
1555
1556 // Reverse stock movement
1557 $labelmovementCancel = $langs->trans("CancelProductionForRef", $productstatic->ref);
1558 $codemovementCancel = $langs->trans("StockDecrease");
1559
1560 $stockmove = new MouvementStock($this->db);
1561 $stockmove->setOrigin($this->element, $this->id);
1562 if ($qtytoprocess >= 0) {
1563 $idstockmove = $stockmove->livraison($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], $qtytoprocess, 0, $labelmovementCancel, dol_now(), '', '', $lineDetails['batch'], 0, $codemovementCancel);
1564 } else {
1565 $idstockmove = $stockmove->reception($user, $lineDetails['fk_product'], $lineDetails['fk_warehouse'], abs($qtytoprocess), 0, $labelmovementCancel, '', '', $lineDetails['batch'], dol_now(), 0, $codemovementCancel);
1566 }
1567 if ($idstockmove < 0) {
1568 $this->error = $stockmove->error;
1569 $this->errors = $stockmove->errors;
1570 $error++;
1571 break;
1572 }
1573
1574 if ($also_delete_lines) {
1575 $result = $this->deleteLineCommon($user, $lineDetails['rowid'], $notrigger);
1576 if ($result < 0) {
1577 $error++;
1578 break;
1579 }
1580 }
1581 }
1582 }
1583 }
1584
1585 if ($error) {
1586 $this->db->rollback();
1587 return -1;
1588 } else {
1589 $this->db->commit();
1590 return 1;
1591 }
1592 }
1593
1600 public function getTooltipContentArray($params)
1601 {
1602 global $langs;
1603
1604 $langs->loadLangs(['mrp', 'products']);
1605 $nofetch = isset($params['nofetch']);
1606
1607 $datas = [];
1608
1609 $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("ManufacturingOrder").'</u>';
1610 if (isset($this->status)) {
1611 $datas['picto'] .= ' '.$this->getLibStatut(5);
1612 }
1613 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1614 if (isset($this->label)) {
1615 $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1616 }
1617 if (isset($this->mrptype)) {
1618 $datas['type'] = '<br><b>'.$langs->trans('Type').':</b> '.$this->fields['mrptype']['arrayofkeyval'][$this->mrptype];
1619 }
1620 if (isset($this->qty)) {
1621 $datas['qty'] = '<br><b>'.$langs->trans('QtyToProduce').':</b> '.$this->qty;
1622 }
1623 if (!$nofetch && isset($this->fk_product)) {
1624 require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
1625 $product = new Product($this->db);
1626 $product->fetch($this->fk_product);
1627 $datas['product'] = '<br><b>'.$langs->trans('Product').':</b> '.$product->getNomUrl(1, '', 0, -1, 1);
1628 }
1629 if (!$nofetch && isset($this->fk_warehouse)) {
1630 require_once DOL_DOCUMENT_ROOT . '/product/stock/class/entrepot.class.php';
1631 $warehouse = new Entrepot($this->db);
1632 $warehouse->fetch($this->fk_warehouse);
1633 $datas['warehouse'] = '<br><b>'.$langs->trans('WarehouseForProduction').':</b> '.$warehouse->getNomUrl(1, '', 0, 1);
1634 }
1635
1636 return $datas;
1637 }
1638
1649 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1650 {
1651 global $conf, $langs, $action, $hookmanager;
1652
1653 if (!empty($conf->dol_no_mouse_hover)) {
1654 $notooltip = 1; // Force disable tooltips
1655 }
1656
1657 $result = '';
1658 $params = [
1659 'id' => $this->id,
1660 'objecttype' => $this->element,
1661 'option' => $option,
1662 'nofetch' => 1,
1663 ];
1664 $classfortooltip = 'classfortooltip';
1665 $dataparams = '';
1666 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1667 $classfortooltip = 'classforajaxtooltip';
1668 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1669 $label = '';
1670 } else {
1671 $label = implode($this->getTooltipContentArray($params));
1672 }
1673
1674 $baseurl = DOL_URL_ROOT.'/mrp/mo_card.php';
1675 if ($option == 'production') {
1676 $baseurl = DOL_URL_ROOT.'/mrp/mo_production.php';
1677 }
1678
1679 $query = ['id' => $this->id];
1680
1681 if ($option != 'nolink') {
1682 // Add param to save lastsearch_values or not
1683 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1684 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1685 $add_save_lastsearch_values = 1;
1686 }
1687 if ($add_save_lastsearch_values) {
1688 $query = array_merge($query, ['save_lastsearch_values' => 1]);
1689 }
1690 }
1691 $url = dolBuildUrl($baseurl, $query);
1692
1693 $linkclose = '';
1694 if (empty($notooltip)) {
1695 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1696 $label = $langs->trans("ShowMo");
1697 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1698 }
1699 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1700 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1701 } else {
1702 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1703 }
1704
1705 $linkstart = '<a href="'.$url.'"';
1706 $linkstart .= $linkclose.'>';
1707 $linkend = '</a>';
1708
1709 $result .= $linkstart;
1710 if ($withpicto) {
1711 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1712 }
1713 if ($withpicto != 2) {
1714 $result .= $this->ref;
1715 }
1716 $result .= $linkend;
1717 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1718
1719 $hookmanager->initHooks(array('modao'));
1720 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1721 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1722 if ($reshook > 0) {
1723 $result = $hookmanager->resPrint;
1724 } else {
1725 $result .= $hookmanager->resPrint;
1726 }
1727
1728 return $result;
1729 }
1730
1737 public function getLibStatut($mode = 0)
1738 {
1739 return $this->LibStatut($this->status, $mode);
1740 }
1741
1742 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1750 public function LibStatut($status, $mode = 0)
1751 {
1752 // phpcs:enable
1753 if (empty($this->labelStatus)) {
1754 global $langs;
1755 //$langs->load("mrp");
1756 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1757 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('ValidatedToProduce');
1758 $this->labelStatus[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1759 $this->labelStatus[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1760 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1761
1762 $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1763 $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated');
1764 $this->labelStatusShort[self::STATUS_INPROGRESS] = $langs->transnoentitiesnoconv('InProgress');
1765 $this->labelStatusShort[self::STATUS_PRODUCED] = $langs->transnoentitiesnoconv('StatusMOProduced');
1766 $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
1767 }
1768
1769 $statusType = 'status'.$status;
1770 if ($status == self::STATUS_VALIDATED) {
1771 $statusType = 'status1';
1772 }
1773 if ($status == self::STATUS_INPROGRESS) {
1774 $statusType = 'status4';
1775 }
1776 if ($status == self::STATUS_PRODUCED) {
1777 $statusType = 'status6';
1778 }
1779 if ($status == self::STATUS_CANCELED) {
1780 $statusType = 'status9';
1781 }
1782
1783 return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
1784 }
1785
1792 public function info($id)
1793 {
1794 $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1795 $sql .= ' fk_user_creat, fk_user_modif';
1796 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1797 $sql .= ' WHERE t.rowid = '.((int) $id);
1798 $result = $this->db->query($sql);
1799 if ($result) {
1800 if ($this->db->num_rows($result)) {
1801 $obj = $this->db->fetch_object($result);
1802
1803 $this->id = $obj->rowid;
1804
1805 $this->user_creation_id = $obj->fk_user_creat;
1806 $this->user_modification_id = $obj->fk_user_modif;
1807 $this->date_creation = $this->db->jdate($obj->datec);
1808 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1809 }
1810
1811 $this->db->free($result);
1812 } else {
1813 dol_print_error($this->db);
1814 }
1815 }
1816
1823 public function initAsSpecimen()
1824 {
1825 $ret = $this->initAsSpecimenCommon();
1826
1827 $this->lines = array();
1828
1829 return $ret;
1830 }
1831
1838 public function getLinesArray($rolefilter = '')
1839 {
1840 $this->lines = array();
1841
1842 $objectline = new MoLine($this->db);
1843
1844 $filter = '(fk_mo:=:'.((int) $this->id).')';
1845 if (!empty($rolefilter)) {
1846 $filter .= " AND (role:=:'".$this->db->escape($rolefilter)."')";
1847 }
1848 $result = $objectline->fetchAll('ASC', 'position', 0, 0, $filter);
1849
1850 if (is_numeric($result)) {
1851 $this->error = $objectline->error;
1852 $this->errors = $objectline->errors;
1853 return $result;
1854 } else {
1855 $this->lines = $result;
1856 return $this->lines;
1857 }
1858 }
1859
1871 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1872 {
1873 global $langs;
1874
1875 $langs->load("mrp");
1876
1877 if (!dol_strlen($modele)) {
1878 //$modele = 'standard';
1879 $modele = ''; // Remove this once a pdf_standard.php exists.
1880
1881 if ($this->model_pdf) {
1882 $modele = $this->model_pdf;
1883 } elseif (getDolGlobalString('MRP_MO_ADDON_PDF')) {
1884 $modele = getDolGlobalString('MRP_MO_ADDON_PDF');
1885 }
1886 }
1887
1888 $modelpath = "core/modules/mrp/doc/";
1889
1890 if (empty($modele)) {
1891 return 1; // Remove this once a pdf_standard.php exists.
1892 }
1893
1894 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1895 }
1896
1907 public function printOriginLinesList($restrictlist = '', $selectedLines = array())
1908 {
1909 global $langs, $hookmanager, $form, $action;
1910
1911 $langs->load('stocks');
1912 $text_stock_options = $langs->trans("RealStockDesc").'<br>';
1913 $text_stock_options .= $langs->trans("RealStockWillAutomaticallyWhen").'<br>';
1914 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT') || getDolGlobalString('STOCK_CALCULATE_ON_SHIPMENT_CLOSE') ? '- '.$langs->trans("DeStockOnShipment").'<br>' : '');
1915 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_VALIDATE_ORDER') ? '- '.$langs->trans("DeStockOnValidateOrder").'<br>' : '');
1916 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_BILL') ? '- '.$langs->trans("DeStockOnBill").'<br>' : '');
1917 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_BILL') ? '- '.$langs->trans("ReStockOnBill").'<br>' : '');
1918 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_VALIDATE_ORDER') ? '- '.$langs->trans("ReStockOnValidateOrder").'<br>' : '');
1919 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_SUPPLIER_DISPATCH_ORDER') ? '- '.$langs->trans("ReStockOnDispatchOrder").'<br>' : '');
1920 $text_stock_options .= (getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION') || getDolGlobalString('STOCK_CALCULATE_ON_RECEPTION_CLOSE') ? '- '.$langs->trans("StockOnReception").'<br>' : '');
1921
1922 print '<tr class="liste_titre">';
1923 // Product or sub-bom
1924 print '<td class="linecoldescription">'.$langs->trans('Ref');
1925 if (getDolGlobalString('BOM_SUB_BOM')) {
1926 print ' &nbsp; <a id="show_all" href="#">'.img_picto('', 'folder-open', 'class="paddingright"').$langs->trans("ExpandAll").'</a>&nbsp;&nbsp;';
1927 print '<a id="hide_all" href="#">'.img_picto('', 'folder', 'class="paddingright"').$langs->trans("UndoExpandAll").'</a>&nbsp;';
1928 }
1929 print '</td>';
1930 // Qty
1931 print '<td class="right">'.$langs->trans('Qty');
1932 if ($this->bom->bomtype == 0) {
1933 print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityOf", (string) $this->bom->qty).')</span>';
1934 } else {
1935 print ' <span class="opacitymedium">('.$langs->trans("ForAQuantityToConsumeOf", (string) $this->bom->qty).')</span>';
1936 }
1937 // Unit
1938 print '<td class="right">'.$langs->trans('Unit');
1939
1940 print '</td>';
1941 print '<td class="center">'.$form->textwithpicto($langs->trans("PhysicalStock"), $text_stock_options, 1).'</td>';
1942 print '<td class="center">'.$form->textwithpicto($langs->trans("VirtualStock"), $langs->trans("VirtualStockDesc")).'</td>';
1943 print '<td class="center">'.$langs->trans('QtyFrozen').'</td>';
1944 print '<td class="center">'.$langs->trans('DisableStockChange').'</td>';
1945 print '<td class="center">'.$langs->trans('MoChildGenerate').'</td>';
1946 //print '<td class="center">'.$form->showCheckAddButtons('checkforselect', 1).'</td>';
1947 //print '<td class="center"></td>';
1948 print '</tr>';
1949 $i = 0;
1950
1951 if (!empty($this->lines)) {
1952 foreach ($this->lines as $line) {
1953 $reshook = 0;
1954 if (is_object($hookmanager)) {
1955 $parameters = array('line' => $line, 'i' => $i, 'restrictlist' => $restrictlist, 'selectedLines' => $selectedLines);
1956 if (!empty($line->fk_parent_line)) {
1957 $parameters['fk_parent_line'] = $line->fk_parent_line;
1958 }
1959 $reshook = $hookmanager->executeHooks('printOriginObjectLine', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1960 }
1961 if (empty($reshook)) {
1962 $this->printOriginLine($line, '', $restrictlist, '/core/tpl', $selectedLines);
1963 }
1964
1965 $i++;
1966 }
1967 }
1968 }
1969
1970
1984 public function printOriginLine($line, $var, $restrictlist = '', $defaulttpldir = '/core/tpl', $selectedLines = array())
1985 {
1986 if (!$line instanceof MoLine) {
1987 dol_syslog(__METHOD__.'::pringOriginLine $line is '.get_class($line).'<>MoLine', LOG_WARNING);
1988 parent::printOriginLine($line, $var, $restrictlist, $defaulttpldir, $selectedLines);
1989 return;
1990 }
1991 $productstatic = new Product($this->db);
1992
1993 $this->tpl['id'] = $line->id;
1994
1995 $this->tpl['label'] = '';
1996 if (!empty($line->fk_product) && $line->fk_product > 0) {
1997 $productstatic->fetch($line->fk_product);
1998 $productstatic->load_stock(); // load_virtual_stock() is done in load_stock()
1999 $this->tpl['label'] .= $productstatic->getNomUrl(1);
2000 //$this->tpl['label'].= ' - '.$productstatic->label;
2001 } else {
2002 // If origin MO line is not a product, but another MO
2003 // TODO
2004 }
2005
2006 $this->tpl['qty_bom'] = 1;
2007 if (is_object($this->bom) && $this->bom->qty > 1) {
2008 $this->tpl['qty_bom'] = $this->bom->qty;
2009 }
2010
2011 $this->tpl['stock'] = $productstatic->stock_reel;
2012 $this->tpl['seuil_stock_alerte'] = $productstatic->seuil_stock_alerte;
2013 $this->tpl['virtual_stock'] = $productstatic->stock_theorique;
2014 $this->tpl['qty'] = $line->qty;
2015 $this->tpl['fk_unit'] = $line->fk_unit;
2016 $this->tpl['qty_frozen'] = $line->qty_frozen;
2017 $this->tpl['disable_stock_change'] = $line->disable_stock_change;
2018 $this->tpl['efficiency'] = $line->efficiency;
2019
2020
2021 global $conf; // used into template
2022 include DOL_DOCUMENT_ROOT.'/mrp/tpl/originproductline.tpl.php';
2023 }
2024
2033 public static function replaceThirdparty($db, $origin_id, $dest_id)
2034 {
2035 $tables = array('mrp_mo');
2036
2037 return CommonObject::commonReplaceThirdparty($db, $origin_id, $dest_id, $tables);
2038 }
2039
2040
2046 public function getMoChilds()
2047 {
2048 $TMoChilds = array();
2049 $error = 0;
2050
2051 $sql = "SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_mo as mo_child";
2052 $sql .= " WHERE fk_parent_line IN ";
2053 $sql .= " (SELECT rowid FROM ".MAIN_DB_PREFIX."mrp_production as line_parent";
2054 $sql .= " WHERE fk_mo=".((int) $this->id).")";
2055
2056 $resql = $this->db->query($sql);
2057
2058 if ($resql) {
2059 if ($this->db->num_rows($resql) > 0) {
2060 while ($obj = $this->db->fetch_object($resql)) {
2061 $MoChild = new Mo($this->db);
2062 $res = $MoChild->fetch($obj->rowid);
2063 if ($res > 0) {
2064 $TMoChilds[$MoChild->id] = $MoChild;
2065 } else {
2066 $error++;
2067 }
2068 }
2069 }
2070 } else {
2071 $error++;
2072 }
2073
2074 if ($error) {
2075 return -1;
2076 } else {
2077 return $TMoChilds;
2078 }
2079 }
2080
2087 public function getAllMoChilds($depth = 0)
2088 {
2089 if ($depth > 1000) {
2090 return -1;
2091 }
2092
2093 $TMoChilds = array();
2094 $error = 0;
2095
2096 $childMoList = $this->getMoChilds();
2097
2098 if ($childMoList == -1) {
2099 return -1;
2100 }
2101
2102 foreach ($childMoList as $childMo) {
2103 $TMoChilds[$childMo->id] = $childMo;
2104 }
2105
2106 foreach ($childMoList as $childMo) {
2107 $childMoChildren = $childMo->getAllMoChilds($depth + 1);
2108
2109 if ($childMoChildren == -1) {
2110 $error++;
2111 } else {
2112 foreach ($childMoChildren as $child) {
2113 $TMoChilds[$child->id] = $child;
2114 }
2115 }
2116 }
2117
2118 if ($error) {
2119 return -1;
2120 } else {
2121 return $TMoChilds;
2122 }
2123 }
2124
2125
2126
2132 public function getMoParent()
2133 {
2134 $MoParent = new Mo($this->db);
2135 $error = 0;
2136
2137 $sql = "SELECT lineparent.fk_mo as id_moparent FROM ".MAIN_DB_PREFIX."mrp_mo as mo";
2138 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."mrp_production lineparent ON mo.fk_parent_line = lineparent.rowid";
2139 $sql .= " WHERE mo.rowid = ".((int) $this->id);
2140
2141 $resql = $this->db->query($sql);
2142
2143 if ($resql) {
2144 if ($this->db->num_rows($resql) > 0) {
2145 $obj = $this->db->fetch_object($resql);
2146 $res = $MoParent->fetch($obj->id_moparent);
2147 if ($res < 0) {
2148 $error++;
2149 }
2150 } else {
2151 return 0;
2152 }
2153 } else {
2154 $error++;
2155 }
2156
2157 if ($error) {
2158 return -1;
2159 } else {
2160 return $MoParent;
2161 }
2162 }
2163
2164 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2171 public function load_board($user)
2172 {
2173 // phpcs:enable
2174 global $conf, $langs;
2175 if ($user->socid) {
2176 return -1; // Security to prohibit this function for an external user
2177 }
2178
2179 $now = dol_now();
2180
2181 $sql = "SELECT rowid, date_end_planned FROM ".$this->db->prefix()."mrp_mo";
2182 $sql .= " WHERE status IN (" . self::STATUS_VALIDATED . ", " . self::STATUS_INPROGRESS .")"; // 1 = Ouvert, 2 = En cours
2183 $sql .= " AND entity IN (".getEntity('mrp_mo').")";
2184
2185 $resql = $this->db->query($sql);
2186 if ($resql) {
2187 $langs->load("mrp");
2188 $response = new WorkboardResponse();
2189 $warning_delay = $conf->mrp->progress->warning_delay ;
2190 $response->warning_delay = $warning_delay / 86400;
2191 $response->label = $langs->trans("MOProgress");
2192 $response->labelShort = $langs->trans("MOProgress");
2193 $response->url = DOL_URL_ROOT.'/mrp/mo_list.php?search_status=-2';
2194 $response->img = img_object('', "mrp");
2195
2196
2197 while ($obj = $this->db->fetch_object($resql)) {
2198 $response->nbtodo++;
2199
2200 if (!empty($obj->date_end_planned)) {
2201 $date_end_planned = $this->db->jdate($obj->date_end_planned);
2202 if ($now > ($date_end_planned + $warning_delay)) {
2203 $response->nbtodolate++;
2204 $response->url_late = DOL_URL_ROOT.'/mrp/mo_list.php?search_status=-2&search_option=late';
2205 }
2206 }
2207 }
2208
2209 return $response;
2210 } else {
2211 dol_print_error($this->db);
2212 $this->error = $this->db->error();
2213 return -1;
2214 }
2215 }
2216
2222 public function hasDelay()
2223 {
2224 global $conf;
2225
2226 if ($this->status != Mo::STATUS_VALIDATED && $this->status != Mo::STATUS_INPROGRESS) {
2227 return false;
2228 }
2229 if (empty($this->date_end_planned)) {
2230 return false;
2231 }
2232 return (dol_now() > ((int) $this->date_end_planned + $conf->mrp->progress->warning_delay));
2233 }
2234
2235
2243 public function getKanbanView($option = '', $arraydata = null)
2244 {
2245 global $langs;
2246 '@phan-var-force array{selected?:int<0,1>,bom?:Bom,product?:product} $arraydata';
2247
2248 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
2249
2250 $return = '<div class="box-flex-item box-flex-grow-zero">';
2251 $return .= '<div class="info-box info-box-sm">';
2252 $return .= '<span class="info-box-icon bg-infobox-action">';
2253 $return .= img_picto('', $this->picto);
2254 //$return .= '<i class="fa fa-dol-action"></i>'; // Can be image
2255 $return .= '</span>';
2256 $return .= '<div class="info-box-content">';
2257 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
2258 if ($selected >= 0) {
2259 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
2260 }
2261 if (!empty($arraydata['bom'])) {
2262 $return .= '<br><span class="info-box-label">'.$arraydata['bom']->getNomUrl(1).'</span>';
2263 }
2264 if (!empty($arraydata['product'])) {
2265 $return .= '<br><span class="info-box-label">'.$arraydata['product']->getNomUrl(1).'</span>';
2266 if (property_exists($this, 'qty')) {
2267 $return .= ' <span class="info-box-label">('.$langs->trans("Qty").' '.$this->qty.')</span>';
2268 }
2269 } else {
2270 if (property_exists($this, 'qty')) {
2271 $return .= '<br><span class="info-box-label">'.$langs->trans('Quantity').' : '.$this->qty.'</span>';
2272 }
2273 }
2274 if (method_exists($this, 'getLibStatut')) {
2275 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
2276 }
2277 $return .= '</div>';
2278 $return .= '</div>';
2279 $return .= '</div>';
2280 return $return;
2281 }
2282}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
$object ref
Definition info.php:90
Class for BOM.
Definition bom.class.php:42
Parent class of all other business classes (invoices, contracts, proposals, orders,...
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.
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:663
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 ...
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: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:839
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:909
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:716
setUserModif($user)
Record the user of the last change, as the generic status setters only update the status.
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:750
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)
setStatut($status, $elementId=null, $elementType='', $trigkey='', $fieldstatus='')
Set status of the MO and record the user who changed it.
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:681
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:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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:64
dol_now($mode='gmt')
Return date for now.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
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.
img_object($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $allowothertags=array())
Show a picto called object_picto (generic function)
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
dolGetStatus($statusLabel='', $statusLabelShort='', $html='', $statusType='status0', $displayMode=0, $url='', $params=array())
Output the badge of a status.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
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.
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php