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';
34 require_once DOL_DOCUMENT_ROOT.
'/workstation/class/workstation.class.php';
46 public $module =
'bom';
51 public $element =
'bom';
57 public $TRIGGER_PREFIX =
'BOM';
62 public $table_element =
'bom_bom';
67 public $picto =
'bom';
75 const STATUS_DRAFT = 0;
76 const STATUS_VALIDATED = 1;
77 const STATUS_CANCELED = 9;
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'),
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'),
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')),
169 public $fk_user_creat;
174 public $fk_user_modif;
179 public $fk_user_valid;
184 public $fk_warehouse;
223 public $table_element_line =
'bom_bomline';
228 public $fk_element =
'fk_bom';
233 public $class_element_line =
'BOMLine';
243 protected $childtablesoncascade = array(
'bom_bomline');
248 public $lines = array();
253 public $total_cost = 0;
258 public $unit_cost = 0;
272 $this->ismultientitymanaged = 1;
273 $this->isextrafieldmanaged = 1;
276 $this->fields[
'rowid'][
'visible'] = 0;
278 if (!
isModEnabled(
'multicompany') && isset($this->fields[
'entity'])) {
279 $this->fields[
'entity'][
'enabled'] = 0;
283 foreach ($this->fields as $key => $val) {
284 if (isset($val[
'enabled']) && empty($val[
'enabled'])) {
285 unset($this->fields[$key]);
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);
310 if ($this->efficiency <= 0 || $this->efficiency > 1) {
311 $this->efficiency = 1;
326 global $langs, $extrafields;
336 $result =
$object->fetchCommon($fromid);
337 if ($result > 0 && !empty(
$object->table_element_line)) {
351 $default_ref = $this->fields[
'ref'][
'default'] ??
null;
352 $object->ref = empty($default_ref) ? $langs->trans(
"copy_of_").$object->ref : $default_ref;
354 $object->label = empty($this->fields[
'label'][
'default']) ? $langs->trans(
"CopyOf").
" ".
$object->label : $this->fields[
'label'][
'default'];
355 $object->status = self::STATUS_DRAFT;
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])) {
364 unset(
$object->array_options[$key]);
370 $object->context[
'createfromclone'] =
'createfromclone';
371 $result =
$object->createCommon($user);
387 if (property_exists($this,
'socid') && $this->socid ==
$object->socid) {
397 unset(
$object->context[
'createfromclone']);
404 $this->db->rollback();
416 public function fetch($id, $ref =
null)
420 if ($result > 0 && !empty($this->table_element_line)) {
435 $this->lines = array();
449 $this->lines = array();
451 $objectlineclassname = $this->class_element_line;
452 if (!class_exists($objectlineclassname)) {
453 $this->error =
'Error, class BOMLine not found during call of fetchLinesCommon';
457 $objectline =
new BOMLine($this->db);
459 '@phan-var-force BOMLine $objectline';
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');
470 $resql = $this->db->query($sql);
472 $num_rows = $this->db->num_rows($resql);
474 while ($i < $num_rows) {
475 $obj = $this->db->fetch_object($resql);
477 $newline =
new BOMLine($this->db);
478 '@phan-var-force BOMLine $newline';
479 $newline->setVarsFromFetchObj($obj);
483 $newline->fetch_optionals();
486 $this->lines[] = $newline;
493 $this->error = $this->db->lasterror();
494 $this->errors[] = $this->error;
511 public function fetchAll($sortorder =
'', $sortfield =
'', $limit = 0, $offset = 0, $filter =
'', $filtermode =
'AND')
519 $sql .=
' FROM '.MAIN_DB_PREFIX.$this->table_element.
' as t';
520 if ($this->ismultientitymanaged) {
521 $sql .=
' WHERE t.entity IN ('.getEntity($this->element).
')';
523 $sql .=
' WHERE 1 = 1';
530 $this->errors[] = $errormessage;
531 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
535 if (!empty($sortfield)) {
536 $sql .= $this->db->order($sortfield, $sortorder);
538 if (!empty($limit)) {
539 $sql .= $this->db->plimit($limit, $offset);
542 $resql = $this->db->query($sql);
544 $num = $this->db->num_rows($resql);
546 while ($obj = $this->db->fetch_object($resql)) {
547 $record =
new self($this->db);
548 $record->setVarsFromFetchObj($obj);
550 $records[$record->id] = $record;
552 $this->db->free($resql);
556 $this->errors[] =
'Error '.$this->db->lasterror();
557 dol_syslog(__METHOD__.
' '.implode(
',', $this->errors), LOG_ERR);
572 if ($this->efficiency <= 0 || $this->efficiency > 1) {
573 $this->efficiency = 1;
586 public function delete(
User $user, $notrigger = 0)
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)
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);
616 if ($this->
status == self::STATUS_DRAFT) {
617 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
623 if (empty($qty_frozen)) {
626 if (empty($disable_stock_change)) {
627 $disable_stock_change = 0;
629 if (empty($efficiency)) {
632 if (empty($fk_bom_child)) {
633 $fk_bom_child =
null;
635 if (empty($import_key)) {
638 if (empty($position)) {
643 $efficiency = (float)
price2num($efficiency);
644 $position = (float)
price2num($position);
650 $rankToUse = $position;
651 if ($rankToUse <= 0 or $rankToUse > $rangMax) {
652 $rankToUse = $rangMax + 1;
654 foreach ($this->lines as $bl) {
655 if ($bl->position >= $rankToUse) {
663 $line =
new BOMLine($this->db);
665 $line->context = $this->context;
667 $line->fk_bom = $this->id;
668 $line->fk_product = $fk_product;
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;
679 if (is_array($array_options) && count($array_options) > 0) {
680 $line->array_options = $array_options;
683 $result = $line->create($user);
691 dol_syslog(get_class($this).
"::addLine error=".$this->error, LOG_ERR);
692 $this->db->rollback();
696 dol_syslog(get_class($this).
"::addLine status of BOM must be Draft to allow use of ->addLine()", LOG_ERR);
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)
721 $this->error =
'ErrorLineIDDoesNotMatchWithObjectID';
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);
729 if ($this->
status == self::STATUS_DRAFT) {
730 include_once DOL_DOCUMENT_ROOT.
'/core/lib/price.lib.php';
736 if (empty($qty_frozen)) {
739 if (empty($disable_stock_change)) {
740 $disable_stock_change = 0;
742 if (empty($efficiency)) {
745 if (empty($import_key)) {
748 if (empty($position)) {
753 $efficiency = (float)
price2num($efficiency);
754 $position = (float)
price2num($position);
759 $line =
new BOMLine($this->db);
760 $line->fetch($rowid);
761 $line->fetch_optionals();
763 $staticLine = clone $line;
764 $line->oldcopy = $staticLine;
765 $line->context = $this->context;
768 $rankToUse = (int) $position;
769 if ($rankToUse != $line->oldcopy->position) {
770 foreach ($this->lines as $bl) {
771 if ($bl->position >= $rankToUse and $bl->position < ($line->oldcopy->position + 1)) {
775 if ($bl->position <= $rankToUse and $bl->position > ($line->oldcopy->position)) {
783 $line->fk_bom = $this->id;
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;
792 if (!empty($fk_unit)) {
793 $line->fk_unit = $fk_unit;
797 if (is_array($array_options) && count($array_options) > 0) {
799 foreach ($array_options as $key => $value) {
800 $line->array_options[$key] = $array_options[$key];
803 if ($line->fk_default_workstation != $fk_default_workstation) {
804 $line->fk_default_workstation = ($fk_default_workstation > 0 ? $fk_default_workstation : 0);
807 $result = $line->update($user);
815 dol_syslog(get_class($this).
"::addLine error=".$this->error, LOG_ERR);
816 $this->db->rollback();
820 dol_syslog(get_class($this).
"::addLine status of BOM must be Draft to allow use of ->addLine()", LOG_ERR);
836 $this->error =
'ErrorDeleteLineNotAllowedByObjectStatus';
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';
849 $line->fetch_optionals();
851 $staticLine = clone $line;
852 $line->oldcopy = $staticLine;
853 $line->context = $this->context;
855 $result = $line->delete($user, $notrigger);
858 foreach ($this->lines as $bl) {
859 if ($bl->position > ($line->oldcopy->position)) {
871 dol_syslog(get_class($this).
"::addLine error=".$this->error, LOG_ERR);
872 $this->db->rollback();
884 public function getNextNumRef($prod)
886 global $langs,
$conf;
896 $dirmodels = array_merge(array(
'/'), (array)
$conf->modules_parts[
'models']);
897 foreach ($dirmodels as $reldir) {
901 $mybool = ((bool) @include_once $dir.$file) || $mybool;
905 dol_print_error(
null,
"Failed to include file ".$file);
909 $obj =
new $classname();
910 '@phan-var-force ModeleNumRefBoms $obj';
912 $numref = $obj->getNextValue($prod, $this);
917 $this->error = $obj->error;
922 print $langs->trans(
"Error").
" ".$langs->trans(
"Error_BOM_ADDON_NotDefined");
938 require_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
943 if ($this->
status == self::STATUS_VALIDATED) {
944 dol_syslog(get_class($this).
"::validate action abandoned: already validated", LOG_WARNING);
953 if (preg_match(
'/^[\(]?PROV/i', $this->
ref) || empty($this->
ref)) {
955 if ($res < 0 || !is_object($this->product)) {
956 $this->db->rollback();
959 $num = $this->getNextNumRef($this->product);
961 $num = (string) $this->
ref;
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);
973 dol_syslog(get_class($this).
"::validate()", LOG_DEBUG);
974 $resql = $this->db->query($sql);
976 dol_print_error($this->db);
977 $this->error = $this->db->lasterror();
981 if (!$error && !$notrigger) {
983 $result = $this->call_trigger(
'BOM_VALIDATE', $user);
991 $this->oldref = $this->ref;
994 if (preg_match(
'/^[\(]?PROV/i', $this->
ref)) {
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);
1001 $this->error = $this->db->lasterror();
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);
1008 $this->error = $this->db->lasterror();
1016 if (!$error && file_exists($dirsource)) {
1017 dol_syslog(get_class($this).
"::validate() rename dir ".$dirsource.
" into ".$dirdest);
1019 if (@rename($dirsource, $dirdest)) {
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);
1038 $this->
status = self::STATUS_VALIDATED;
1042 $this->db->commit();
1045 $this->db->rollback();
1060 if ($this->
status <= self::STATUS_DRAFT) {
1064 return $this->
setStatusCommon($user, self::STATUS_DRAFT, $notrigger,
'BOM_UNVALIDATE');
1074 public function cancel($user, $notrigger = 0)
1077 if ($this->
status != self::STATUS_VALIDATED) {
1081 return $this->
setStatusCommon($user, self::STATUS_CANCELED, $notrigger,
'BOM_CLOSE');
1091 public function reopen($user, $notrigger = 0)
1094 if ($this->
status != self::STATUS_CANCELED) {
1098 return $this->
setStatusCommon($user, self::STATUS_VALIDATED, $notrigger,
'BOM_REOPEN');
1111 $langs->loadLangs([
'product',
'mrp']);
1116 return [
'optimize' => $langs->trans(
"ShowBillOfMaterials")];
1118 $picto = img_picto(
'', $this->picto).
' <u class="paddingrightonly">'.$langs->trans(
"BillOfMaterials").
'</u>';
1119 if (isset($this->
status)) {
1120 $picto .=
' '.$this->getLibStatut(5);
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;
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;
1149 public function getNomUrl($withpicto = 0, $option =
'', $notooltip = 0, $morecss =
'', $save_lastsearch_value = -1)
1151 global
$conf, $langs, $hookmanager;
1153 if (!empty(
$conf->dol_no_mouse_hover)) {
1160 'objecttype' => $this->element,
1161 'option' => $option,
1163 $classfortooltip =
'classfortooltip';
1166 $classfortooltip =
'classforajaxtooltip';
1167 $dataparams =
' data-params="'.dol_escape_htmltag(json_encode($params)).
'"';
1173 $baseurl = DOL_URL_ROOT.
'/bom/bom_card.php';
1175 $query = [
'id' => $this->id];
1177 if ($option !=
'nolink') {
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;
1183 if ($add_save_lastsearch_values) {
1184 $query = array_merge($query, [
'save_lastsearch_values' => 1]);
1190 if (empty($notooltip)) {
1192 $label = $langs->trans(
"ShowBillOfMaterials");
1193 $linkclose .=
' alt="'.dolPrintHTMLForAttribute($label).
'"';
1195 $linkclose .= ($label ?
' title="'.dolPrintHTMLForAttribute($label).
'"' :
' title="tocomplete"');
1196 $linkclose .= $dataparams.
' class="'.$classfortooltip.($morecss ?
' '.$morecss :
'').
'"';
1198 $linkclose = ($morecss ?
' class="'.$morecss.
'"' :
'');
1201 $linkstart =
'<a href="'.$url.
'"';
1202 $linkstart .= $linkclose.
'>';
1205 $result .= $linkstart;
1207 $result .= img_object(($notooltip ?
'' : $label), ($this->picto ? $this->picto :
'generic'), (($withpicto != 2) ?
'class="paddingright"' :
''), 0, 0, $notooltip ? 0 : 1);
1209 if ($withpicto != 2) {
1210 $result .= $this->ref;
1212 $result .= $linkend;
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);
1220 $result = $hookmanager->resPrint;
1222 $result .= $hookmanager->resPrint;
1250 if (empty($this->labelStatus)) {
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');
1258 $statusType =
'status'.$status;
1259 if ($status == self::STATUS_VALIDATED) {
1260 $statusType =
'status4';
1262 if ($status == self::STATUS_CANCELED) {
1263 $statusType =
'status6';
1266 return dolGetStatus($this->labelStatus[$status], $this->labelStatus[$status],
'', $statusType, $mode);
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);
1283 if ($this->db->num_rows($result)) {
1284 $obj = $this->db->fetch_object($result);
1286 $this->
id = $obj->rowid;
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);
1294 $this->db->free($result);
1296 dol_print_error($this->db);
1307 $this->lines = array();
1309 $objectline =
new BOMLine($this->db);
1310 $result = $objectline->fetchAll(
'ASC',
'position', 0, 0,
'(fk_bom:=:'.((
int) $this->
id).
')');
1312 if (is_numeric($result)) {
1313 $this->error = $objectline->error;
1314 $this->errors = $objectline->errors;
1317 $this->lines = $result;
1318 return $this->lines;
1333 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams =
null)
1337 $langs->load(
"mrp");
1338 $outputlangs->load(
"products");
1343 if ($this->model_pdf) {
1344 $modele = $this->model_pdf;
1350 $modelpath =
"core/modules/bom/doc/";
1351 if (!empty($modele)) {
1352 return $this->
commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
1368 include_once DOL_DOCUMENT_ROOT.
'/core/lib/files.lib.php';
1369 include_once DOL_DOCUMENT_ROOT.
'/core/lib/images.lib.php';
1371 $sdir .=
'/'.get_exdir(0, 0, 0, 0, $this,
'bom');
1374 if (file_exists($dir_osencoded)) {
1375 $handle = opendir($dir_osencoded);
1376 if (is_resource($handle)) {
1377 while (($file = readdir($handle)) !==
false) {
1379 $file = mb_convert_encoding($file,
'UTF-8',
'ISO-8859-1');
1399 $this->
ref =
'BOM-123';
1400 $this->date_creation =
dol_now() - 20000;
1414 global $hookmanager;
1416 include_once DOL_DOCUMENT_ROOT.
'/product/class/product.class.php';
1417 $this->unit_cost = 0;
1418 $this->total_cost = 0;
1420 $parameters = array();
1421 $reshook = $hookmanager->executeHooks(
'calculateCostsBom', $parameters, $this);
1424 $hookmanager->executeHooks(
'calculateCostsBomAfter', $parameters, $this);
1425 return $hookmanager->resPrint;
1428 if (is_array($this->lines) && count($this->lines)) {
1429 require_once DOL_DOCUMENT_ROOT.
'/fourn/class/fournisseur.product.class.php';
1431 $tmpproduct =
new Product($this->db);
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);
1438 $unit_cost = (float) (is_null($tmpproduct->cost_price) ? $tmpproduct->pmp : $tmpproduct->cost_price);
1439 if (empty($unit_cost)) {
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;
1444 $line->unit_cost = $productFournisseur->fourn_unitprice;
1447 $line->unit_cost = 0;
1450 $line->unit_cost = (float)
price2num($unit_cost);
1453 if ($tmpproduct->type == $tmpproduct::TYPE_PRODUCT) {
1454 if (empty($line->fk_bom_child)) {
1456 $this->error = $tmpproduct->error;
1460 $line->total_cost = (float) $line->unit_cost * $line->qty / $line->efficiency;
1462 $this->total_cost += $line->total_cost;
1464 $bom_child =
new BOM($this->db);
1465 $res = $bom_child->fetch((
int) $line->fk_bom_child);
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;
1472 $this->error = $bom_child->error;
1478 require_once DOL_DOCUMENT_ROOT.
'/core/class/cunits.class.php';
1479 $measuringUnits =
new CUnits($this->db);
1480 $measuringUnits->fetch($line->fk_unit);
1483 $qtyhourforline = $line->qty * (int) $measuringUnits->scale / 3600;
1485 if (
isModEnabled(
'workstation') && !empty($line->fk_default_workstation)) {
1487 $res = $workstation->fetch($line->fk_default_workstation);
1490 $line->total_cost = (float) $qtyhourforline * ($workstation->thm_operator_estimated + $workstation->thm_machine_estimated);
1492 $this->error = $workstation->error;
1496 $defaultdurationofservice = $tmpproduct->duration;
1498 $qtyhourservice = 0;
1499 if (preg_match(
'/^(\d+)([a-z]+)$/', $defaultdurationofservice, $reg)) {
1503 if ($qtyhourservice) {
1504 $line->total_cost = (float) $qtyhourforline / $qtyhourservice * $line->unit_cost;
1506 $line->total_cost = (float) $line->qty * $line->unit_cost;
1510 $this->total_cost += $line->total_cost;
1514 $this->total_cost = (float)
price2num($this->total_cost,
'MT');
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');
1522 $hookmanager->executeHooks(
'calculateCostsBomAfter', $parameters, $this);
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);
1561 if (empty($TNetNeeds[$line->fk_product][
'qty'])) {
1562 $TNetNeeds[$line->fk_product][
'qty'] = 0.0;
1566 $TNetNeeds[$line->fk_product][
'fk_unit'] = $line->fk_unit;
1567 $TNetNeeds[$line->fk_product][
'qty'] += $line->qty * $qty;
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;
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);
1600 if (!isset($TNetNeeds[$this->
id][
'product'])) {
1601 $TNetNeeds[$this->id][
'product'] = array();
1603 if (!isset($TNetNeeds[$this->
id][
'product'][$line->fk_product])) {
1604 $TNetNeeds[$this->id][
'product'][$line->fk_product] = array();
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;
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;
1629 if ($level > 1000) {
1633 if (empty($bom_id)) {
1634 $bom_id = $this->id;
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);
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;
1660 $selected = (empty($arraydata[
'selected']) ? 0 : $arraydata[
'selected']);
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"' :
'').
'>';
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>';
1678 $return .=
'<span class="info-box-label">'.$arrayofkeyval[1].
'</span>';
1681 if (!empty($arraydata[
'prod'])) {
1682 $prod = $arraydata[
'prod'];
1683 $return .=
'<br><span class="info-box-label">'.$prod->getNomUrl(1).
'</span>';
1685 $return .=
'<br><div class="info-box-status">'.$this->getLibStatut(3).
'</div>';
1687 $return .=
'</div>';
1688 $return .=
'</div>';
1689 $return .=
'</div>';
if(! $sortfield) if(! $sortorder) $object
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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 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.
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...
convertDurationtoHour($duration_value, $duration_unit)
Convert duration to hour.
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.
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.