dolibarr 25.0.0-alpha
bom.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2019 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2023 Benjamin Falière <benjamin.faliere@altairis.fr>
4 * Copyright (C) 2023 Charlene Benke <charlene@patas-monkey.com>
5 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
6 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
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
28// Put here all includes required by your class file
29require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
30require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php';
31require_once DOL_DOCUMENT_ROOT.'/bom/class/bomline.class.php';
32
33if (isModEnabled('workstation')) {
34 require_once DOL_DOCUMENT_ROOT.'/workstation/class/workstation.class.php';
35}
36
37
41class BOM extends CommonObject
42{
46 public $module = 'bom';
47
51 public $element = 'bom';
52
57 public $TRIGGER_PREFIX = 'BOM';
58
62 public $table_element = 'bom_bom';
63
67 public $picto = 'bom';
68
72 public $product;
73
74
75 const STATUS_DRAFT = 0;
76 const STATUS_VALIDATED = 1;
77 const STATUS_CANCELED = 9;
78
79
106 // BEGIN MODULEBUILDER PROPERTIES
110 public $fields = array(
111 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -2, 'position' => 1, 'notnull' => 1, 'index' => 1, 'comment' => "Id",),
112 'entity' => array('type' => 'integer', 'label' => 'Entity', 'enabled' => 1, 'visible' => 0, 'notnull' => 1, 'default' => '1', 'index' => 1, 'position' => 5),
113 'ref' => array('type' => 'varchar(128)', 'label' => 'Ref', 'enabled' => 1, 'noteditable' => 1, 'visible' => 4, 'position' => 10, 'notnull' => 1, 'default' => '(PROV)', 'index' => 1, 'searchall' => 1, 'comment' => "Reference of BOM", 'showoncombobox' => 1, 'csslist' => 'nowraponall'),
114 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => 1, 'position' => 30, 'notnull' => 1, 'searchall' => 1, 'showoncombobox' => 2, 'autofocusoncreate' => 1, 'alwayseditable' => 1, 'css' => 'minwidth300 maxwidth400', 'csslist' => 'tdoverflowmax200'),
115 'bomtype' => array('type' => 'integer', 'label' => 'Type', 'enabled' => 1, 'visible' => 1, 'position' => 33, 'notnull' => 1, 'default' => '0', 'arrayofkeyval' => array(0 => 'Manufacturing', 1 => 'Disassemble'), 'css' => 'minwidth175', 'csslist' => 'minwidth175 center'),
116 //'bomtype' => array('type'=>'integer', 'label'=>'Type', 'enabled'=>1, 'visible'=>-1, 'position'=>32, 'notnull'=>1, 'default'=>'0', 'arrayofkeyval'=>array(0=>'Manufacturing')),
117 'fk_product' => array('type' => 'integer:Product:product/class/product.class.php:1:((finished:is:null) or (finished:!=:0))', 'label' => 'Product', 'picto' => 'product', 'enabled' => 1, 'visible' => 1, 'position' => 35, 'notnull' => 1, 'index' => 1, 'help' => 'ProductBOMHelp', 'css' => 'maxwidth500', 'csslist' => 'tdoverflowmax100'),
118 'description' => array('type' => 'text', 'label' => 'Description', 'enabled' => 1, 'visible' => -1, 'position' => 60, 'notnull' => -1,),
119 'qty' => array('type' => 'real', 'label' => 'Quantity', 'enabled' => 1, 'visible' => 1, 'default' => '1', 'position' => 55, 'notnull' => 1, 'isameasure' => 1, 'css' => 'maxwidth50imp right'),
120 //'efficiency' => array('type'=>'real', 'label'=>'ManufacturingEfficiency', 'enabled'=>1, 'visible'=>-1, 'default'=>'1', 'position'=>100, 'notnull'=>0, 'css'=>'maxwidth50imp', 'help'=>'ValueOfMeansLossForProductProduced'),
121 'duration' => array('type' => 'duration', 'label' => 'EstimatedDuration', 'enabled' => 1, 'visible' => -1, 'position' => 101, 'notnull' => -1, 'css' => 'maxwidth50imp', 'help' => 'EstimatedDurationDesc'),
122 'fk_warehouse' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php:0', 'label' => 'WarehouseForProduction', 'picto' => 'stock', 'enabled' => 1, 'visible' => -1, 'position' => 102, 'css' => 'maxwidth500', 'csslist' => 'tdoverflowmax100'),
123 'note_public' => array('type' => 'html', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => -2, 'position' => 161, 'notnull' => -1,),
124 'note_private' => array('type' => 'html', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => -2, 'position' => 162, 'notnull' => -1,),
125 'date_creation' => array('type' => 'datetime', 'label' => 'DateCreation', 'enabled' => 1, 'visible' => -2, 'position' => 300, 'notnull' => 1,),
126 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -2, 'position' => 501, 'notnull' => 1,),
127 'date_valid' => array('type' => 'datetime', 'label' => 'DateValidation', 'enabled' => 1, 'visible' => -2, 'position' => 502, 'notnull' => 0,),
128 'fk_user_creat' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserCreation', 'picto' => 'user', 'enabled' => 1, 'visible' => -2, 'position' => 510, 'notnull' => 1, 'foreignkey' => 'user.rowid', 'csslist' => 'tdoverflowmax100'),
129 'fk_user_modif' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserModif', 'picto' => 'user', 'enabled' => 1, 'visible' => -2, 'position' => 511, 'notnull' => -1, 'csslist' => 'tdoverflowmax100'),
130 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'picto' => 'user', 'enabled' => 1, 'visible' => -2, 'position' => 512, 'notnull' => 0, 'csslist' => 'tdoverflowmax100'),
131 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 1000, 'notnull' => -1,),
132 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 1010),
133 'status' => array('type' => 'integer', 'label' => 'Status', 'enabled' => 1, 'visible' => 2, 'position' => 1000, 'notnull' => 1, 'default' => '0', 'index' => 1, 'arrayofkeyval' => array(0 => 'Draft', 1 => 'Enabled', 9 => 'Disabled')),
134 );
135
139 public $rowid;
140
144 public $ref;
145
149 public $label;
150
154 public $bomtype;
155
159 public $description;
160
164 public $date_valid;
165
169 public $fk_user_creat;
170
174 public $fk_user_modif;
175
179 public $fk_user_valid;
180
184 public $fk_warehouse;
185
189 public $import_key;
190
194 public $status;
195
199 public $fk_product;
200
204 public $qty;
205
209 public $duration;
210
214 public $efficiency;
215 // END MODULEBUILDER PROPERTIES
216
217
218 // If this object has a subtable with lines
219
223 public $table_element_line = 'bom_bomline';
224
228 public $fk_element = 'fk_bom';
229
233 public $class_element_line = 'BOMLine';
234
235 // /**
236 // * @var array List of child tables. To test if we can delete object.
237 // */
238 // protected $childtables=array();
239
243 protected $childtablesoncascade = array('bom_bomline');
244
248 public $lines = array();
249
253 public $total_cost = 0;
254
258 public $unit_cost = 0;
259
260
266 public function __construct(DoliDB $db)
267 {
268 global $langs;
269
270 $this->db = $db;
271
272 $this->ismultientitymanaged = 1;
273 $this->isextrafieldmanaged = 1;
274
275 if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
276 $this->fields['rowid']['visible'] = 0;
277 }
278 if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
279 $this->fields['entity']['enabled'] = 0;
280 }
281
282 // Unset fields that are disabled
283 foreach ($this->fields as $key => $val) {
284 if (isset($val['enabled']) && empty($val['enabled'])) {
285 unset($this->fields[$key]);
286 }
287 }
288
289 // Translate some data of arrayofkeyval
290 if (is_object($langs)) {
291 foreach ($this->fields as $key => $val) {
292 if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
293 foreach ($val['arrayofkeyval'] as $key2 => $val2) {
294 $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
295 }
296 }
297 }
298 }
299 }
300
308 public function create(User $user, $notrigger = 0)
309 {
310 if ($this->efficiency <= 0 || $this->efficiency > 1) {
311 $this->efficiency = 1;
312 }
313
314 return $this->createCommon($user, $notrigger);
315 }
316
324 public function createFromClone(User $user, $fromid)
325 {
326 global $langs, $extrafields;
327 $error = 0;
328
329 dol_syslog(__METHOD__, LOG_DEBUG);
330
331 $object = new self($this->db);
332
333 $this->db->begin();
334
335 // Load source object
336 $result = $object->fetchCommon($fromid);
337 if ($result > 0 && !empty($object->table_element_line)) {
338 $object->fetchLines();
339 }
340
341 // Get lines so they will be clone
342 //foreach ($object->lines as $line)
343 // $line->fetch_optionals();
344
345 // Reset some properties
346 unset($object->id);
347 unset($object->fk_user_creat);
348 unset($object->import_key);
349 unset($object->date_creation);
350 // Clear fields
351 $default_ref = $this->fields['ref']['default'] ?? null;
352 $object->ref = empty($default_ref) ? $langs->trans("copy_of_").$object->ref : $default_ref;
353 // @phan-suppress-next-line PhanTypeInvalidDimOffset
354 $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
355 $object->status = self::STATUS_DRAFT;
356 // ...
357 // Clear extrafields that are unique
358 if (is_array($object->array_options) && count($object->array_options) > 0) {
359 $extrafields->fetch_name_optionals_label($object->table_element);
360 foreach ($object->array_options as $key => $option) {
361 $shortkey = preg_replace('/options_/', '', $key);
362 if (!empty($extrafields->attributes[$this->element]['unique'][$shortkey])) {
363 //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
364 unset($object->array_options[$key]);
365 }
366 }
367 }
368
369 // Create clone
370 $object->context['createfromclone'] = 'createfromclone';
371 $result = $object->createCommon($user);
372 if ($result < 0) {
373 $error++;
375 }
376
377 if (!$error) {
378 // copy internal contacts
379 if ($this->copy_linked_contact($object, 'internal') < 0) {
380 $error++;
381 }
382 }
383
384 if (!$error) {
385 // copy external contacts if same company
386 // @phan-suppress-next-line PhanUndeclaredProperty
387 if (property_exists($this, 'socid') && $this->socid == $object->socid) {
388 if ($this->copy_linked_contact($object, 'external') < 0) {
389 $error++;
390 }
391 }
392 }
393
394 // If there is lines, create lines too from ->lines
395 // TODO
396
397 unset($object->context['createfromclone']);
398
399 // End
400 if (!$error) {
401 $this->db->commit();
402 return $object;
403 } else {
404 $this->db->rollback();
405 return -1;
406 }
407 }
408
416 public function fetch($id, $ref = null)
417 {
418 $result = $this->fetchCommon($id, $ref);
419
420 if ($result > 0 && !empty($this->table_element_line)) {
421 $this->fetchLines();
422 }
423 //$this->calculateCosts(); // This consume a high number of subrequests. Do not call it into fetch but when you need it.
424
425 return $result;
426 }
427
433 public function fetchLines()
434 {
435 $this->lines = array();
436
437 $result = $this->fetchLinesCommon();
438 return $result;
439 }
440
447 public function fetchLinesbytypeproduct($typeproduct = 0)
448 {
449 $this->lines = array();
450
451 $objectlineclassname = $this->class_element_line;
452 if (!class_exists($objectlineclassname)) {
453 $this->error = 'Error, class BOMLine not found during call of fetchLinesCommon';
454 return -1;
455 }
456
457 $objectline = new BOMLine($this->db);
458
459 '@phan-var-force BOMLine $objectline';
460
461 $sql = "SELECT ".$objectline->getFieldList('l');
462 $sql .= " FROM ".$this->db->prefix().$objectline->table_element." as l";
463 $sql .= " LEFT JOIN ".$this->db->prefix()."product as p ON p.rowid = l.fk_product";
464 $sql .= " WHERE l.fk_".$this->db->sanitize($this->element)." = ".((int) $this->id);
465 $sql .= " AND p.fk_product_type = ". ((int) $typeproduct);
466 if (isset($objectline->fields['position'])) {
467 $sql .= $this->db->order('position', 'ASC');
468 }
469
470 $resql = $this->db->query($sql);
471 if ($resql) {
472 $num_rows = $this->db->num_rows($resql);
473 $i = 0;
474 while ($i < $num_rows) {
475 $obj = $this->db->fetch_object($resql);
476 if ($obj) {
477 $newline = new BOMLine($this->db);
478 '@phan-var-force BOMLine $newline';
479 $newline->setVarsFromFetchObj($obj);
480
481 // Load also extrafields for the line
482 //if (empty($noextrafields)) {
483 $newline->fetch_optionals();
484 //}
485
486 $this->lines[] = $newline;
487 }
488 $i++;
489 }
490
491 return $num_rows;
492 } else {
493 $this->error = $this->db->lasterror();
494 $this->errors[] = $this->error;
495 return -1;
496 }
497 }
498
499
511 public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, $filter = '', $filtermode = 'AND')
512 {
513 dol_syslog(__METHOD__, LOG_DEBUG);
514
515 $records = array();
516
517 $sql = 'SELECT ';
518 $sql .= $this->getFieldList();
519 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
520 if ($this->ismultientitymanaged) {
521 $sql .= ' WHERE t.entity IN ('.getEntity($this->element).')';
522 } else {
523 $sql .= ' WHERE 1 = 1';
524 }
525
526 // Manage filter
527 $errormessage = '';
528 $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
529 if ($errormessage) {
530 $this->errors[] = $errormessage;
531 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
532 return -1;
533 }
534
535 if (!empty($sortfield)) {
536 $sql .= $this->db->order($sortfield, $sortorder);
537 }
538 if (!empty($limit)) {
539 $sql .= $this->db->plimit($limit, $offset);
540 }
541
542 $resql = $this->db->query($sql);
543 if ($resql) {
544 $num = $this->db->num_rows($resql);
545
546 while ($obj = $this->db->fetch_object($resql)) {
547 $record = new self($this->db);
548 $record->setVarsFromFetchObj($obj);
549
550 $records[$record->id] = $record;
551 }
552 $this->db->free($resql);
553
554 return $records;
555 } else {
556 $this->errors[] = 'Error '.$this->db->lasterror();
557 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
558
559 return -1;
560 }
561 }
562
570 public function update(User $user, $notrigger = 0)
571 {
572 if ($this->efficiency <= 0 || $this->efficiency > 1) {
573 $this->efficiency = 1;
574 }
575
576 return $this->updateCommon($user, $notrigger);
577 }
578
586 public function delete(User $user, $notrigger = 0)
587 {
588 return $this->deleteCommon($user, $notrigger);
589 //return $this->deleteCommon($user, $notrigger, 1);
590 }
591
608 public function addLine($fk_product, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $fk_bom_child = null, $import_key = null, $fk_unit = 0, $array_options = array(), $fk_default_workstation = null)
609 {
610 global $user;
611
612 $logtext = "::addLine bomid=$this->id, qty=$qty, fk_product=$fk_product, qty_frozen=$qty_frozen, disable_stock_change=$disable_stock_change, efficiency=$efficiency";
613 $logtext .= ", fk_bom_child=$fk_bom_child, import_key=$import_key";
614 dol_syslog(get_class($this).$logtext, LOG_DEBUG);
615
616 if ($this->status == self::STATUS_DRAFT) {
617 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
618
619 // Clean parameters
620 if (empty($qty)) {
621 $qty = 0;
622 }
623 if (empty($qty_frozen)) {
624 $qty_frozen = 0;
625 }
626 if (empty($disable_stock_change)) {
627 $disable_stock_change = 0;
628 }
629 if (empty($efficiency)) {
630 $efficiency = 1.0;
631 }
632 if (empty($fk_bom_child)) {
633 $fk_bom_child = null;
634 }
635 if (empty($import_key)) {
636 $import_key = '';
637 }
638 if (empty($position)) {
639 $position = -1;
640 }
641
642 $qty = (float) price2num($qty);
643 $efficiency = (float) price2num($efficiency);
644 $position = (float) price2num($position);
645
646 $this->db->begin();
647
648 // Rank to use
649 $rangMax = $this->line_max();
650 $rankToUse = $position;
651 if ($rankToUse <= 0 or $rankToUse > $rangMax) { // New line after existing lines
652 $rankToUse = $rangMax + 1;
653 } else { // New line between the existing lines
654 foreach ($this->lines as $bl) {
655 if ($bl->position >= $rankToUse) {
656 $bl->position++;
657 $bl->update($user);
658 }
659 }
660 }
661
662 // Insert line
663 $line = new BOMLine($this->db);
664
665 $line->context = $this->context;
666
667 $line->fk_bom = $this->id;
668 $line->fk_product = $fk_product;
669 $line->qty = $qty;
670 $line->qty_frozen = $qty_frozen;
671 $line->disable_stock_change = $disable_stock_change;
672 $line->efficiency = $efficiency;
673 $line->fk_bom_child = $fk_bom_child;
674 $line->import_key = $import_key;
675 $line->position = $rankToUse;
676 $line->fk_unit = $fk_unit;
677 $line->fk_default_workstation = $fk_default_workstation;
678
679 if (is_array($array_options) && count($array_options) > 0) {
680 $line->array_options = $array_options;
681 }
682
683 $result = $line->create($user);
684
685 if ($result > 0) {
686 $this->calculateCosts();
687 $this->db->commit();
688 return $result;
689 } else {
690 $this->setErrorsFromObject($line);
691 dol_syslog(get_class($this)."::addLine error=".$this->error, LOG_ERR);
692 $this->db->rollback();
693 return -2;
694 }
695 } else {
696 dol_syslog(get_class($this)."::addLine status of BOM must be Draft to allow use of ->addLine()", LOG_ERR);
697 return -3;
698 }
699 }
700
716 public function updateLine($rowid, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $import_key = null, $fk_unit = 0, $array_options = array(), $fk_default_workstation = null)
717 {
718 global $user;
719
720 if (!$this->isLineOfObject($rowid)) {
721 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
722 return -1;
723 }
724
725 $logtext = "::updateLine bomid=$this->id, qty=$qty, qty_frozen=$qty_frozen, disable_stock_change=$disable_stock_change, efficiency=$efficiency";
726 $logtext .= ", import_key=$import_key";
727 dol_syslog(get_class($this).$logtext, LOG_DEBUG);
728
729 if ($this->status == self::STATUS_DRAFT) {
730 include_once DOL_DOCUMENT_ROOT.'/core/lib/price.lib.php';
731
732 // Clean parameters
733 if (empty($qty)) {
734 $qty = 0;
735 }
736 if (empty($qty_frozen)) {
737 $qty_frozen = 0;
738 }
739 if (empty($disable_stock_change)) {
740 $disable_stock_change = 0;
741 }
742 if (empty($efficiency)) {
743 $efficiency = 1.0;
744 }
745 if (empty($import_key)) {
746 $import_key = '';
747 }
748 if (empty($position)) {
749 $position = -1;
750 }
751
752 $qty = (float) price2num($qty);
753 $efficiency = (float) price2num($efficiency);
754 $position = (float) price2num($position);
755
756 $this->db->begin();
757
758 // Fetch current line from the database and then clone the object and set it in $oldline property
759 $line = new BOMLine($this->db);
760 $line->fetch($rowid);
761 $line->fetch_optionals();
762
763 $staticLine = clone $line;
764 $line->oldcopy = $staticLine;
765 $line->context = $this->context;
766
767 // Rank to use
768 $rankToUse = (int) $position;
769 if ($rankToUse != $line->oldcopy->position) { // check if position have a new value
770 foreach ($this->lines as $bl) {
771 if ($bl->position >= $rankToUse and $bl->position < ($line->oldcopy->position + 1)) { // move rank up
772 $bl->position++;
773 $bl->update($user);
774 }
775 if ($bl->position <= $rankToUse and $bl->position > ($line->oldcopy->position)) { // move rank down
776 $bl->position--;
777 $bl->update($user);
778 }
779 }
780 }
781
782
783 $line->fk_bom = $this->id;
784 $line->qty = $qty;
785 $line->qty_frozen = $qty_frozen;
786 $line->disable_stock_change = $disable_stock_change;
787 $line->efficiency = $efficiency;
788 $line->import_key = $import_key;
789 $line->position = $rankToUse;
790
791
792 if (!empty($fk_unit)) {
793 $line->fk_unit = $fk_unit;
794 }
795
796
797 if (is_array($array_options) && count($array_options) > 0) {
798 // We replace values in this->line->array_options only for entries defined into $array_options
799 foreach ($array_options as $key => $value) {
800 $line->array_options[$key] = $array_options[$key];
801 }
802 }
803 if ($line->fk_default_workstation != $fk_default_workstation) {
804 $line->fk_default_workstation = ($fk_default_workstation > 0 ? $fk_default_workstation : 0);
805 }
806
807 $result = $line->update($user);
808
809 if ($result > 0) {
810 $this->calculateCosts();
811 $this->db->commit();
812 return $result;
813 } else {
814 $this->setErrorsFromObject($line);
815 dol_syslog(get_class($this)."::addLine error=".$this->error, LOG_ERR);
816 $this->db->rollback();
817 return -2;
818 }
819 } else {
820 dol_syslog(get_class($this)."::addLine status of BOM must be Draft to allow use of ->addLine()", LOG_ERR);
821 return -3;
822 }
823 }
824
833 public function deleteLine(User $user, $idline, $notrigger = 0)
834 {
835 if ($this->status < 0) {
836 $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
837 return -2;
838 }
839
840 // Fetch current line from the database and then clone the object and set it in $oldline property
841 $line = new BOMLine($this->db);
842 $line->fetch($idline);
843 if ($this->id > 0 && (int) $line->fk_bom !== (int) $this->id) {
844 $this->error = 'ErrorLineIDDoesNotMatchWithObjectID';
845 return -1;
846 }
847
848 $this->db->begin();
849 $line->fetch_optionals();
850
851 $staticLine = clone $line;
852 $line->oldcopy = $staticLine;
853 $line->context = $this->context;
854
855 $result = $line->delete($user, $notrigger);
856
857 //Positions (rank) reordering
858 foreach ($this->lines as $bl) {
859 if ($bl->position > ($line->oldcopy->position)) { // move rank down
860 $bl->position--;
861 $bl->update($user);
862 }
863 }
864
865 if ($result > 0) {
866 $this->calculateCosts();
867 $this->db->commit();
868 return $result;
869 } else {
870 $this->setErrorsFromObject($line);
871 dol_syslog(get_class($this)."::addLine error=".$this->error, LOG_ERR);
872 $this->db->rollback();
873 return -2;
874 }
875 }
876
884 public function getNextNumRef($prod)
885 {
886 global $langs, $conf;
887 $langs->load("mrp");
888
889 if (getDolGlobalString('BOM_ADDON')) {
890 $mybool = false;
891
892 $file = getDolGlobalString('BOM_ADDON') . ".php";
893 $classname = getDolGlobalString('BOM_ADDON');
894
895 // Include file with class
896 $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
897 foreach ($dirmodels as $reldir) {
898 $dir = dol_buildpath($reldir."core/modules/bom/");
899
900 // Load file with numbering class (if found)
901 $mybool = ((bool) @include_once $dir.$file) || $mybool;
902 }
903
904 if (!$mybool) {
905 dol_print_error(null, "Failed to include file ".$file);
906 return '';
907 }
908
909 $obj = new $classname();
910 '@phan-var-force ModeleNumRefBoms $obj';
912 $numref = $obj->getNextValue($prod, $this);
913
914 if ($numref != "") {
915 return $numref;
916 } else {
917 $this->error = $obj->error;
918 //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
919 return "";
920 }
921 } else {
922 print $langs->trans("Error")." ".$langs->trans("Error_BOM_ADDON_NotDefined");
923 return "";
924 }
925 }
926
934 public function validate($user, $notrigger = 0)
935 {
936 global $conf;
937
938 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
939
940 $error = 0;
941
942 // Protection
943 if ($this->status == self::STATUS_VALIDATED) {
944 dol_syslog(get_class($this)."::validate action abandoned: already validated", LOG_WARNING);
945 return 0;
946 }
947
948 $now = dol_now();
949
950 $this->db->begin();
951
952 // Define new ref
953 if (preg_match('/^[\‍(]?PROV/i', $this->ref) || empty($this->ref)) { // empty should not happened, but when it occurs, the test save life
954 $res = $this->fetch_product();
955 if ($res < 0 || !is_object($this->product)) {
956 $this->db->rollback();
957 return -1;
958 }
959 $num = $this->getNextNumRef($this->product);
960 } else {
961 $num = (string) $this->ref;
962 }
963 $this->newref = dol_sanitizeFileName($num);
964
965 // Validate
966 $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element;
967 $sql .= " SET ref = '".$this->db->escape($num)."',";
968 $sql .= " status = ".self::STATUS_VALIDATED.",";
969 $sql .= " date_valid='".$this->db->idate($now)."',";
970 $sql .= " fk_user_valid = ".((int) $user->id);
971 $sql .= " WHERE rowid = ".((int) $this->id);
972
973 dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
974 $resql = $this->db->query($sql);
975 if (!$resql) {
976 dol_print_error($this->db);
977 $this->error = $this->db->lasterror();
978 $error++;
979 }
980
981 if (!$error && !$notrigger) {
982 // Call trigger
983 $result = $this->call_trigger('BOM_VALIDATE', $user);
984 if ($result < 0) {
985 $error++;
986 }
987 // End call triggers
988 }
989
990 if (!$error) {
991 $this->oldref = $this->ref;
992
993 // Rename directory if dir was a temporary ref
994 if (preg_match('/^[\‍(]?PROV/i', $this->ref)) {
995 // Now we rename also files into index
996 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'bom/".$this->db->escape($this->newref)."'";
997 $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
998 $resql = $this->db->query($sql);
999 if (!$resql) {
1000 $error++;
1001 $this->error = $this->db->lasterror();
1002 }
1003 $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'bom/".$this->db->escape($this->newref)."'";
1004 $sql .= " WHERE filepath = 'bom/".$this->db->escape($this->ref)."' and entity = ".((int) $conf->entity);
1005 $resql = $this->db->query($sql);
1006 if (!$resql) {
1007 $error++;
1008 $this->error = $this->db->lasterror();
1009 }
1010
1011 // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
1012 $oldref = dol_sanitizeFileName($this->ref);
1013 $newref = dol_sanitizeFileName($num);
1014 $dirsource = getMultidirOutput($this) . '/'.$oldref;
1015 $dirdest = getMultidirOutput($this) . '/'.$newref;
1016 if (!$error && file_exists($dirsource)) {
1017 dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
1018
1019 if (@rename($dirsource, $dirdest)) {
1020 dol_syslog("Rename ok");
1021 // Rename docs starting with $oldref with $newref
1022 $listoffiles = dol_dir_list(getMultidirOutput($this) . '/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
1023 foreach ($listoffiles as $fileentry) {
1024 $dirsource = $fileentry['name'];
1025 $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
1026 $dirsource = $fileentry['path'].'/'.$dirsource;
1027 $dirdest = $fileentry['path'].'/'.$dirdest;
1028 @rename($dirsource, $dirdest);
1029 }
1030 }
1031 }
1032 }
1033 }
1034
1035 // Set new ref and current status
1036 if (!$error) {
1037 $this->ref = $num;
1038 $this->status = self::STATUS_VALIDATED;
1039 }
1040
1041 if (!$error) {
1042 $this->db->commit();
1043 return 1;
1044 } else {
1045 $this->db->rollback();
1046 return -1;
1047 }
1048 }
1049
1057 public function setDraft($user, $notrigger = 0)
1058 {
1059 // Protection
1060 if ($this->status <= self::STATUS_DRAFT) {
1061 return 0;
1062 }
1063
1064 return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'BOM_UNVALIDATE');
1065 }
1066
1074 public function cancel($user, $notrigger = 0)
1075 {
1076 // Protection
1077 if ($this->status != self::STATUS_VALIDATED) {
1078 return 0;
1079 }
1080
1081 return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'BOM_CLOSE');
1082 }
1083
1091 public function reopen($user, $notrigger = 0)
1092 {
1093 // Protection
1094 if ($this->status != self::STATUS_CANCELED) {
1095 return 0;
1096 }
1097
1098 return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'BOM_REOPEN');
1099 }
1100
1107 public function getTooltipContentArray($params)
1108 {
1109 global $langs;
1110
1111 $langs->loadLangs(['product', 'mrp']);
1112
1113 $datas = [];
1114
1115 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1116 return ['optimize' => $langs->trans("ShowBillOfMaterials")];
1117 }
1118 $picto = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("BillOfMaterials").'</u>';
1119 if (isset($this->status)) {
1120 $picto .= ' '.$this->getLibStatut(5);
1121 }
1122 $datas['picto'] = $picto;
1123 $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.$this->ref;
1124 if (isset($this->label)) {
1125 $datas['label'] = '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1126 }
1127 if (!empty($this->fk_product) && $this->fk_product > 0) {
1128 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1129 $product = new Product($this->db);
1130 $resultFetch = $product->fetch($this->fk_product);
1131 if ($resultFetch > 0) {
1132 $datas['product'] = "<br><b>".$langs->trans("Product").'</b>: '.$product->ref.' - '.$product->label;
1133 }
1134 }
1135
1136 return $datas;
1137 }
1138
1149 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
1150 {
1151 global $conf, $langs, $hookmanager;
1152
1153 if (!empty($conf->dol_no_mouse_hover)) {
1154 $notooltip = 1; // Force disable tooltips
1155 }
1156
1157 $result = '';
1158 $params = [
1159 'id' => $this->id,
1160 'objecttype' => $this->element,
1161 'option' => $option,
1162 ];
1163 $classfortooltip = 'classfortooltip';
1164 $dataparams = '';
1165 if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
1166 $classfortooltip = 'classforajaxtooltip';
1167 $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
1168 $label = '';
1169 } else {
1170 $label = implode($this->getTooltipContentArray($params));
1171 }
1172
1173 $baseurl = DOL_URL_ROOT.'/bom/bom_card.php';
1174
1175 $query = ['id' => $this->id];
1176
1177 if ($option != 'nolink') {
1178 // Add param to save lastsearch_values or not
1179 $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
1180 if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
1181 $add_save_lastsearch_values = 1;
1182 }
1183 if ($add_save_lastsearch_values) {
1184 $query = array_merge($query, ['save_lastsearch_values' => 1]);
1185 }
1186 }
1187 $url = dolBuildUrl($baseurl, $query);
1188
1189 $linkclose = '';
1190 if (empty($notooltip)) {
1191 if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
1192 $label = $langs->trans("ShowBillOfMaterials");
1193 $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
1194 }
1195 $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
1196 $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
1197 } else {
1198 $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
1199 }
1200
1201 $linkstart = '<a href="'.$url.'"';
1202 $linkstart .= $linkclose.'>';
1203 $linkend = '</a>';
1204
1205 $result .= $linkstart;
1206 if ($withpicto) {
1207 $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 0, 0, $notooltip ? 0 : 1);
1208 }
1209 if ($withpicto != 2) {
1210 $result .= $this->ref;
1211 }
1212 $result .= $linkend;
1213 //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
1214
1215 global $action, $hookmanager;
1216 $hookmanager->initHooks(array('bomdao'));
1217 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1218 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1219 if ($reshook > 0) {
1220 $result = $hookmanager->resPrint;
1221 } else {
1222 $result .= $hookmanager->resPrint;
1223 }
1224
1225 return $result;
1226 }
1227
1234 public function getLibStatut($mode = 0)
1235 {
1236 return $this->LibStatut($this->status, $mode);
1237 }
1238
1239 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1247 public function LibStatut($status, $mode = 0)
1248 {
1249 // phpcs:enable
1250 if (empty($this->labelStatus)) {
1251 global $langs;
1252 //$langs->load("mrp");
1253 $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
1254 $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
1255 $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
1256 }
1257
1258 $statusType = 'status'.$status;
1259 if ($status == self::STATUS_VALIDATED) {
1260 $statusType = 'status4';
1261 }
1262 if ($status == self::STATUS_CANCELED) {
1263 $statusType = 'status6';
1264 }
1265
1266 return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status], '', $statusType, $mode);
1267 }
1268
1275 public function info($id)
1276 {
1277 $sql = 'SELECT rowid, date_creation as datec, tms as datem,';
1278 $sql .= ' fk_user_creat, fk_user_modif';
1279 $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
1280 $sql .= ' WHERE t.rowid = '.((int) $id);
1281 $result = $this->db->query($sql);
1282 if ($result) {
1283 if ($this->db->num_rows($result)) {
1284 $obj = $this->db->fetch_object($result);
1285
1286 $this->id = $obj->rowid;
1287
1288 $this->user_creation_id = $obj->fk_user_creat;
1289 $this->user_modification_id = $obj->fk_user_modif;
1290 $this->date_creation = $this->db->jdate($obj->datec);
1291 $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
1292 }
1293
1294 $this->db->free($result);
1295 } else {
1296 dol_print_error($this->db);
1297 }
1298 }
1299
1305 public function getLinesArray()
1306 {
1307 $this->lines = array();
1308
1309 $objectline = new BOMLine($this->db);
1310 $result = $objectline->fetchAll('ASC', 'position', 0, 0, '(fk_bom:=:'.((int) $this->id).')');
1311
1312 if (is_numeric($result)) {
1313 $this->error = $objectline->error;
1314 $this->errors = $objectline->errors;
1315 return $result;
1316 } else {
1317 $this->lines = $result;
1318 return $this->lines;
1319 }
1320 }
1321
1333 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
1334 {
1335 global $langs;
1336
1337 $langs->load("mrp");
1338 $outputlangs->load("products");
1339
1340 if (!dol_strlen($modele)) {
1341 $modele = '';
1342
1343 if ($this->model_pdf) {
1344 $modele = $this->model_pdf;
1345 } elseif (getDolGlobalString('BOM_ADDON_PDF')) {
1346 $modele = getDolGlobalString('BOM_ADDON_PDF');
1347 }
1348 }
1349
1350 $modelpath = "core/modules/bom/doc/";
1351 if (!empty($modele)) {
1352 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1353 } else {
1354 return 0;
1355 }
1356 }
1357
1358 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1365 public function is_photo_available($sdir)
1366 {
1367 // phpcs:enable
1368 include_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1369 include_once DOL_DOCUMENT_ROOT.'/core/lib/images.lib.php';
1370
1371 $sdir .= '/'.get_exdir(0, 0, 0, 0, $this, 'bom');
1372
1373 $dir_osencoded = dol_osencode($sdir);
1374 if (file_exists($dir_osencoded)) {
1375 $handle = opendir($dir_osencoded);
1376 if (is_resource($handle)) {
1377 while (($file = readdir($handle)) !== false) {
1378 if (!utf8_check($file)) {
1379 $file = mb_convert_encoding($file, 'UTF-8', 'ISO-8859-1'); // To be sure data is stored in UTF8 in memory
1380 }
1381 if (dol_is_file($sdir.$file) && image_format_supported($file) >= 0) {
1382 return true;
1383 }
1384 }
1385 }
1386 }
1387 return false;
1388 }
1389
1396 public function initAsSpecimen()
1397 {
1398 $this->initAsSpecimenCommon();
1399 $this->ref = 'BOM-123';
1400 $this->date_creation = dol_now() - 20000;
1401
1402 return 1;
1403 }
1404
1405
1412 public function calculateCosts()
1413 {
1414 global $hookmanager;
1415
1416 include_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
1417 $this->unit_cost = 0;
1418 $this->total_cost = 0;
1419
1420 $parameters = array();
1421 $reshook = $hookmanager->executeHooks('calculateCostsBom', $parameters, $this); // Note that $action and $object may have been modified by hook
1422
1423 if ($reshook > 0) {
1424 $hookmanager->executeHooks('calculateCostsBomAfter', $parameters, $this); // Note that $action and $object may have been modified by hook
1425 return $hookmanager->resPrint;
1426 }
1427
1428 if (is_array($this->lines) && count($this->lines)) {
1429 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
1430 $productFournisseur = new ProductFournisseur($this->db);
1431 $tmpproduct = new Product($this->db);
1432
1433 foreach ($this->lines as &$line) {
1434 $tmpproduct->cost_price = 0;
1435 $tmpproduct->pmp = 0;
1436 $result = $tmpproduct->fetch($line->fk_product, '', '', '', 0, 1, 1); // We discard selling price and language loading
1437
1438 $unit_cost = (float) (is_null($tmpproduct->cost_price) ? $tmpproduct->pmp : $tmpproduct->cost_price);
1439 if (empty($unit_cost)) { // @phpstan-ignore-line phpstan thinks this is always false. No,if unit_cost is 0, it is not.
1440 if ($productFournisseur->find_min_price_product_fournisseur($line->fk_product) > 0) {
1441 if ($productFournisseur->fourn_remise_percent != "0") {
1442 $line->unit_cost = $productFournisseur->fourn_unitprice_with_discount;
1443 } else {
1444 $line->unit_cost = $productFournisseur->fourn_unitprice;
1445 }
1446 } else {
1447 $line->unit_cost = 0;
1448 }
1449 } else {
1450 $line->unit_cost = (float) price2num($unit_cost);
1451 }
1452
1453 if ($tmpproduct->type == $tmpproduct::TYPE_PRODUCT) {
1454 if (empty($line->fk_bom_child)) {
1455 if ($result < 0) {
1456 $this->error = $tmpproduct->error;
1457 return -1;
1458 }
1459
1460 $line->total_cost = (float) $line->unit_cost * $line->qty / $line->efficiency;
1461
1462 $this->total_cost += $line->total_cost;
1463 } else {
1464 $bom_child = new BOM($this->db);
1465 $res = $bom_child->fetch((int) $line->fk_bom_child);
1466 if ($res > 0) {
1467 $bom_child->calculateCosts();
1468 $line->childBom[] = $bom_child;
1469 $line->total_cost = (float) $bom_child->unit_cost * $line->qty / $line->efficiency;
1470 $this->total_cost += $line->total_cost;
1471 } else {
1472 $this->error = $bom_child->error;
1473 return -2;
1474 }
1475 }
1476 } else {
1477 // Convert qty of line into hours
1478 require_once DOL_DOCUMENT_ROOT.'/core/class/cunits.class.php';
1479 $measuringUnits = new CUnits($this->db);
1480 $measuringUnits->fetch($line->fk_unit);
1481
1482 // The unit is a unit for time, so the $measuringUnits->scale is not a power of 10, but directly the factor to change unit into seconds
1483 $qtyhourforline = $line->qty * (int) $measuringUnits->scale / 3600;
1484
1485 if (isModEnabled('workstation') && !empty($line->fk_default_workstation)) {
1486 $workstation = new Workstation($this->db);
1487 $res = $workstation->fetch($line->fk_default_workstation);
1488
1489 if ($res > 0) {
1490 $line->total_cost = (float) $qtyhourforline * ($workstation->thm_operator_estimated + $workstation->thm_machine_estimated);
1491 } else {
1492 $this->error = $workstation->error;
1493 return -3;
1494 }
1495 } else {
1496 $defaultdurationofservice = $tmpproduct->duration;
1497 $reg = array();
1498 $qtyhourservice = 0;
1499 if (preg_match('/^(\d+)([a-z]+)$/', $defaultdurationofservice, $reg)) {
1500 $qtyhourservice = convertDurationtoHour((float) $reg[1], $reg[2]);
1501 }
1502
1503 if ($qtyhourservice) {
1504 $line->total_cost = (float) $qtyhourforline / $qtyhourservice * $line->unit_cost;
1505 } else {
1506 $line->total_cost = (float) $line->qty * $line->unit_cost;
1507 }
1508 }
1509
1510 $this->total_cost += $line->total_cost;
1511 }
1512 }
1513
1514 $this->total_cost = (float) price2num($this->total_cost, 'MT');
1515
1516 if ($this->qty > 0) {
1517 $this->unit_cost = (float) price2num($this->total_cost / $this->qty, 'MU');
1518 } elseif ($this->qty < 0) {
1519 $this->unit_cost = (float) price2num($this->total_cost * $this->qty, 'MU');
1520 }
1521 }
1522 $hookmanager->executeHooks('calculateCostsBomAfter', $parameters, $this);
1523
1524 return 1;
1525 }
1526
1535 public static function replaceProduct(DoliDB $db, $origin_id, $dest_id)
1536 {
1537 $tables = array(
1538 'bom_bom',
1539 'bom_bomline'
1540 );
1541
1542 return CommonObject::commonReplaceProduct($db, $origin_id, $dest_id, $tables);
1543 }
1544
1552 public function getNetNeeds(&$TNetNeeds = array(), $qty = 0)
1553 {
1554 if (!empty($this->lines)) {
1555 foreach ($this->lines as $line) {
1556 if (!empty($line->childBom)) {
1557 foreach ($line->childBom as $childBom) {
1558 $childBom->getNetNeeds($TNetNeeds, $line->qty * $qty / $childBom->qty);
1559 }
1560 } else {
1561 if (empty($TNetNeeds[$line->fk_product]['qty'])) {
1562 $TNetNeeds[$line->fk_product]['qty'] = 0.0;
1563 }
1564 // When using nested level (or not), the qty for needs must always use the same unit to be able to be cumulated.
1565 // So if unit in bom is not the same than default, we must recalculate qty after units comparisons.
1566 $TNetNeeds[$line->fk_product]['fk_unit'] = $line->fk_unit;
1567 $TNetNeeds[$line->fk_product]['qty'] += $line->qty * $qty;
1568 }
1569 }
1570 }
1571 }
1572
1581 public function getNetNeedsTree(&$TNetNeeds = array(), $qty = 0, $level = 0)
1582 {
1583 if (!empty($this->lines)) {
1584 foreach ($this->lines as $line) {
1585 if (!empty($line->childBom)) {
1586 foreach ($line->childBom as $childBom) {
1587 $TNetNeeds[$childBom->id]['bom'] = $childBom;
1588 $TNetNeeds[$childBom->id]['parentid'] = $this->id;
1589 // When using nested level (or not), the qty for needs must always use the same unit to be able to be cumulated.
1590 // So if unit in bom is not the same than default, we must recalculate qty after units comparisons.
1591 //$TNetNeeds[$childBom->id]['fk_unit'] = $line->fk_unit;
1592 $TNetNeeds[$childBom->id]['qty'] = $line->qty * $qty;
1593 $TNetNeeds[$childBom->id]['level'] = $level;
1594 $TNetNeeds[$childBom->id]['position'] = $line->position;
1595 $childBom->getNetNeedsTree($TNetNeeds, $line->qty * $qty / $childBom->qty, $level + 1);
1596 }
1597 } else {
1598 // When using nested level (or not), the qty for needs must always use the same unit to be able to be cumulated.
1599 // So if unit in bom is not the same than default, we must recalculate qty after units comparisons.
1600 if (!isset($TNetNeeds[$this->id]['product'])) {
1601 $TNetNeeds[$this->id]['product'] = array();
1602 }
1603 if (!isset($TNetNeeds[$this->id]['product'][$line->fk_product])) {
1604 $TNetNeeds[$this->id]['product'][$line->fk_product] = array();
1605 }
1606 $TNetNeeds[$this->id]['product'][$line->fk_product]['fk_unit'] = $line->fk_unit;
1607 if (!isset($TNetNeeds[$this->id]['product'][$line->fk_product]['qty'])) {
1608 $TNetNeeds[$this->id]['product'][$line->fk_product]['qty'] = 0.0;
1609 }
1610 $TNetNeeds[$this->id]['product'][$line->fk_product]['qty'] += $line->qty * $qty;
1611 $TNetNeeds[$this->id]['product'][$line->fk_product]['level'] = $level;
1612 $TNetNeeds[$this->id]['product'][$line->fk_product]['position'] = $line->position;
1613 }
1614 }
1615 }
1616 }
1617
1626 public function getParentBomTreeRecursive(&$TParentBom, $bom_id = 0, $level = 1)
1627 {
1628 // Protection against infinite loop
1629 if ($level > 1000) {
1630 return;
1631 }
1632
1633 if (empty($bom_id)) {
1634 $bom_id = $this->id;
1635 }
1636
1637 $sql = "SELECT l.fk_bom, b.label FROM ".MAIN_DB_PREFIX."bom_bomline as l INNER JOIN ".MAIN_DB_PREFIX.$this->table_element." b ON b.rowid = l.fk_bom";
1638 $sql .= " WHERE fk_bom_child = ".((int) $bom_id);
1639
1640 $resql = $this->db->query($sql);
1641 if (!empty($resql)) {
1642 while ($res = $this->db->fetch_object($resql)) {
1643 $TParentBom[(int) $res->fk_bom] = (int) $res->fk_bom;
1644 $this->getParentBomTreeRecursive($TParentBom, $res->fk_bom, $level + 1);
1645 }
1646 }
1647 }
1648
1656 public function getKanbanView($option = '', $arraydata = null)
1657 {
1658 global $langs;
1659
1660 $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
1661
1662 $return = '<div class="box-flex-item box-flex-grow-zero">';
1663 $return .= '<div class="info-box info-box-sm">';
1664 $return .= '<span class="info-box-icon bg-infobox-action">';
1665 $return .= img_picto('', $this->picto);
1666 $return .= '</span>';
1667 $return .= '<div class="info-box-content">';
1668 $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">' . $this->getNomUrl() . '</span>';
1669 if ($selected >= 0) {
1670 $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
1671 }
1672 $arrayofkeyval = $this->fields['bomtype']['arrayofkeyval'] ?? null;
1673 if (!empty($arrayofkeyval)) {
1674 $return .= '<br><span class="info-box-label opacitymedium">'.$langs->trans("Type").' : </span>';
1675 if ($this->bomtype == 0) {
1676 $return .= '<span class="info-box-label">'.$arrayofkeyval[0].'</span>';
1677 } else {
1678 $return .= '<span class="info-box-label">'.$arrayofkeyval[1].'</span>';
1679 }
1680 }
1681 if (!empty($arraydata['prod'])) {
1682 $prod = $arraydata['prod'];
1683 $return .= '<br><span class="info-box-label">'.$prod->getNomUrl(1).'</span>';
1684 }
1685 $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
1686
1687 $return .= '</div>';
1688 $return .= '</div>';
1689 $return .= '</div>';
1690
1691 return $return;
1692 }
1693}
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
static replaceProduct(DoliDB $db, $origin_id, $dest_id)
Function used to replace a product id with another one.
fetchLines()
Load object lines in memory from the database.
is_photo_available($sdir)
Return if at least one photo is available.
__construct(DoliDB $db)
Constructor.
calculateCosts()
BOM costs calculation based on cost_price or pmp of each BOM line.
info($id)
Load the info information in the object.
getLibStatut($mode=0)
Return label of the status.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
create(User $user, $notrigger=0)
Create object into database.
validate($user, $notrigger=0)
Validate bom.
reopen($user, $notrigger=0)
Reopen if canceled.
cancel($user, $notrigger=0)
Set cancel status.
LibStatut($status, $mode=0)
Return the status.
getParentBomTreeRecursive(&$TParentBom, $bom_id=0, $level=1)
Recursively retrieves all parent bom in the tree that leads to the $bom_id bom.
getTooltipContentArray($params)
getTooltipContentArray
fetchLinesbytypeproduct($typeproduct=0)
Load object lines in memory from the database by type of product.
deleteLine(User $user, $idline, $notrigger=0)
Delete a line of object in database.
createFromClone(User $user, $fromid)
Clone an object into another one.
fetch($id, $ref=null)
Load object in memory from the database.
getNomUrl($withpicto=0, $option='', $notooltip=0, $morecss='', $save_lastsearch_value=-1)
Return a link to the object card (with optionally the picto)
updateLine($rowid, $qty, $qty_frozen=0, $disable_stock_change=0, $efficiency=1.0, $position=-1, $import_key=null, $fk_unit=0, $array_options=array(), $fk_default_workstation=null)
Update an BOM line into database.
getNetNeeds(&$TNetNeeds=array(), $qty=0)
Get Net needs by product.
update(User $user, $notrigger=0)
Update object into database.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0, $moreparams=null)
Create a document onto disk according to template module.
getLinesArray()
Create an array of lines.
setDraft($user, $notrigger=0)
Set draft status.
getKanbanView($option='', $arraydata=null)
Return clickable link of object (with eventually picto)
fetchAll($sortorder='', $sortfield='', $limit=0, $offset=0, $filter='', $filtermode='AND')
Load list of objects in memory from the database.
addLine($fk_product, $qty, $qty_frozen=0, $disable_stock_change=0, $efficiency=1.0, $position=-1, $fk_bom_child=null, $import_key=null, $fk_unit=0, $array_options=array(), $fk_default_workstation=null)
Add an BOM line into database (linked to BOM)
getNetNeedsTree(&$TNetNeeds=array(), $qty=0, $level=0)
Get/add Net needs Tree by product or bom.
Class for BOMLine.
Class of dictionary type of thirdparty (used by imports)
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
setErrorsFromObject($object)
setErrorsFromObject
isLineOfObject($lineid)
Check that a line belongs to this object, using $this->table_element_line and $this->fk_element.
createCommon(User $user, $notrigger=0)
Create object in the database.
getFieldList($alias='', $excludefields=array())
Function to concat keys of fields.
updateCommon(User $user, $notrigger=0)
Update object into database.
setStatusCommon($user, $status, $notrigger=0, $triggercode='')
Set to a status.
initAsSpecimenCommon()
Initialise object with example values Id must be 0 if object instance is a specimen.
copy_linked_contact($objFrom, $source='internal')
Copy contact from one element to current.
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.
line_max($fk_parent_line=0)
Get max value used for position of line (rang)
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 predefined suppliers products.
Class to manage products or services.
Class to manage Dolibarr users.
Class for Workstation.
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
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
Definition date.lib.php:357
dol_is_file($pathoffile)
Return if path is a file.
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.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
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.
getMultidirOutput($object, $module='', $forobject=0, $mode='output')
Return the full path of the directory where a module (or an object of a module) stores its files.
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.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
image_format_supported($file, $acceptsvg=0)
Return if a filename is file name of a supported image format.