Merge pull request #12855 from Dolibarr/scrutinizer-patch-3

Scrutinizer Auto-Fixes
This commit is contained in:
Laurent Destailleur 2020-01-16 03:05:38 +01:00 committed by GitHub
commit cadad6aed9
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 144 additions and 144 deletions

View File

@ -45,10 +45,10 @@ function moPrepareHead($object)
$head[$h][1] = $langs->trans("Production"); $head[$h][1] = $langs->trans("Production");
$arrayproduced = $object->fetchLinesLinked('produced', 0); $arrayproduced = $object->fetchLinesLinked('produced', 0);
$nbProduced = 0; $nbProduced = 0;
foreach($arrayproduced as $lineproduced) { foreach ($arrayproduced as $lineproduced) {
$nbProduced += $lineproduced['qty']; $nbProduced += $lineproduced['qty'];
} }
$head[$h][1].= '<span class="badge marginleftonlyshort">'.$nbProduced.' / '.$object->qty.'</span>'; $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbProduced.' / '.$object->qty.'</span>';
$head[$h][2] = 'production'; $head[$h][2] = 'production';
$h++; $h++;
@ -59,19 +59,19 @@ function moPrepareHead($object)
if (!empty($object->note_public)) $nbNote++; if (!empty($object->note_public)) $nbNote++;
$head[$h][0] = dol_buildpath('/mrp/mo_note.php', 1).'?id='.$object->id; $head[$h][0] = dol_buildpath('/mrp/mo_note.php', 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Notes'); $head[$h][1] = $langs->trans('Notes');
if ($nbNote > 0) $head[$h][1].= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>'; if ($nbNote > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.$nbNote.'</span>';
$head[$h][2] = 'note'; $head[$h][2] = 'note';
$h++; $h++;
} }
require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php';
$upload_dir = $conf->mrp->dir_output . "/mo/" . dol_sanitizeFileName($object->ref); $upload_dir = $conf->mrp->dir_output."/mo/".dol_sanitizeFileName($object->ref);
$nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$'));
$nbLinks=Link::count($db, $object->element, $object->id); $nbLinks = Link::count($db, $object->element, $object->id);
$head[$h][0] = dol_buildpath("/mrp/mo_document.php", 1).'?id='.$object->id; $head[$h][0] = dol_buildpath("/mrp/mo_document.php", 1).'?id='.$object->id;
$head[$h][1] = $langs->trans('Documents'); $head[$h][1] = $langs->trans('Documents');
if (($nbFiles+$nbLinks) > 0) $head[$h][1].= '<span class="badge marginleftonlyshort">'.($nbFiles+$nbLinks).'</span>'; if (($nbFiles + $nbLinks) > 0) $head[$h][1] .= '<span class="badge marginleftonlyshort">'.($nbFiles + $nbLinks).'</span>';
$head[$h][2] = 'document'; $head[$h][2] = 'document';
$h++; $h++;

View File

@ -136,7 +136,7 @@ if (empty($reshook))
else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__'); else $backtopage = DOL_URL_ROOT.'/mrp/mo_card.php?id='.($id > 0 ? $id : '__ID__');
} }
} }
if ($cancel && ! empty($backtopageforcancel)) { if ($cancel && !empty($backtopageforcancel)) {
$backtopage = $backtopageforcancel; $backtopage = $backtopageforcancel;
} }
@ -522,7 +522,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
if (!empty($object->lines)) if (!empty($object->lines))
{ {
$i = 0; $i = 0;
foreach($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toconsume') { if ($line->role == 'toconsume') {
if ($i) print ', '; if ($i) print ', ';
$tmpproduct = new Product($db); $tmpproduct = new Product($db);
@ -541,7 +541,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea
if (!empty($object->lines)) if (!empty($object->lines))
{ {
$i = 0; $i = 0;
foreach($object->lines as $line) { foreach ($object->lines as $line) {
if ($line->role == 'toproduce') { if ($line->role == 'toproduce') {
if ($i) print ', '; if ($i) print ', ';
$tmpproduct = new Product($db); $tmpproduct = new Product($db);

View File

@ -124,19 +124,19 @@ class MouvementStock extends CommonObject
dol_syslog(get_class($this)."::_create start userid=$user->id, fk_product=$fk_product, warehouse_id=$entrepot_id, qty=$qty, type=$type, price=$price, label=$label, inventorycode=$inventorycode, datem=".$datem.", eatby=".$eatby.", sellby=".$sellby.", batch=".$batch.", skip_batch=".$skip_batch); dol_syslog(get_class($this)."::_create start userid=$user->id, fk_product=$fk_product, warehouse_id=$entrepot_id, qty=$qty, type=$type, price=$price, label=$label, inventorycode=$inventorycode, datem=".$datem.", eatby=".$eatby.", sellby=".$sellby.", batch=".$batch.", skip_batch=".$skip_batch);
// Clean parameters // Clean parameters
if (empty($price)) $price=0; if (empty($price)) $price = 0;
$now=(! empty($datem) ? $datem : dol_now()); $now = (!empty($datem) ? $datem : dol_now());
// Check parameters // Check parameters
if (empty($fk_product)) return 0; if (empty($fk_product)) return 0;
if ($eatby < 0) if ($eatby < 0)
{ {
$this->errors[]='ErrorBadValueForParameterEatBy'; $this->errors[] = 'ErrorBadValueForParameterEatBy';
return -1; return -1;
} }
if ($sellby < 0) if ($sellby < 0)
{ {
$this->errors[]='ErrorBadValueForParameterSellBy'; $this->errors[] = 'ErrorBadValueForParameterSellBy';
return -1; return -1;
} }
@ -155,7 +155,7 @@ class MouvementStock extends CommonObject
$mvid = 0; $mvid = 0;
$product = new Product($this->db); $product = new Product($this->db);
$result=$product->fetch($fk_product); $result = $product->fetch($fk_product);
if ($result < 0) if ($result < 0)
{ {
dol_print_error('', "Failed to fetch product"); dol_print_error('', "Failed to fetch product");
@ -167,11 +167,11 @@ class MouvementStock extends CommonObject
$product->load_stock('novirtual'); $product->load_stock('novirtual');
// Test if product require batch data. If yes, and there is not, we throw an error. // Test if product require batch data. If yes, and there is not, we throw an error.
if (! empty($conf->productbatch->enabled) && $product->hasbatch() && ! $skip_batch) if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch)
{ {
if (empty($batch)) if (empty($batch))
{ {
$this->errors[]=$langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref); $this->errors[] = $langs->trans("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref);
dol_syslog("Try to make a movement of a product with status_batch on without any batch data"); dol_syslog("Try to make a movement of a product with status_batch on without any batch data");
$this->db->rollback(); $this->db->rollback();
@ -185,13 +185,13 @@ class MouvementStock extends CommonObject
// If found and eatby/sellby not defined into table and not provided, we do nothing // If found and eatby/sellby not defined into table and not provided, we do nothing
// If not found, we add record // If not found, we add record
$sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".MAIN_DB_PREFIX."product_lot as pb"; $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".MAIN_DB_PREFIX."product_lot as pb";
$sql.= " WHERE pb.fk_product = ".$fk_product." AND pb.batch = '".$this->db->escape($batch)."'"; $sql .= " WHERE pb.fk_product = ".$fk_product." AND pb.batch = '".$this->db->escape($batch)."'";
dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG); dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql)
{ {
$num = $this->db->num_rows($resql); $num = $this->db->num_rows($resql);
$i=0; $i = 0;
if ($num > 0) if ($num > 0)
{ {
while ($i < $num) while ($i < $num)
@ -201,12 +201,12 @@ class MouvementStock extends CommonObject
{ {
if ($eatby) if ($eatby)
{ {
$tmparray=dol_getdate($eatby, true); $tmparray = dol_getdate($eatby, true);
$eatbywithouthour=dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); $eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) // We test date without hours and with hours for backward compatibility
{ {
// If found and eatby/sellby defined into table and provided and differs, return error // If found and eatby/sellby defined into table and provided and differs, return error
$this->errors[]=$langs->trans("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatby, 'dayhour')); $this->errors[] = $langs->trans("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatby, 'dayhour'));
dol_syslog("ThisSerialAlreadyExistWithDifferentDate batch=".$batch.", eatby found into product_lot = ".$obj->eatby." = ".dol_print_date($this->db->jdate($obj->eatby), 'dayhourrfc')." so eatbywithouthour = ".$eatbywithouthour." = ".dol_print_date($eatbywithouthour)." - eatby provided = ".$eatby." = ".dol_print_date($eatby, 'dayhourrfc'), LOG_ERR); dol_syslog("ThisSerialAlreadyExistWithDifferentDate batch=".$batch.", eatby found into product_lot = ".$obj->eatby." = ".dol_print_date($this->db->jdate($obj->eatby), 'dayhourrfc')." so eatbywithouthour = ".$eatbywithouthour." = ".dol_print_date($eatbywithouthour)." - eatby provided = ".$eatby." = ".dol_print_date($eatby, 'dayhourrfc'), LOG_ERR);
$this->db->rollback(); $this->db->rollback();
return -3; return -3;
@ -238,12 +238,12 @@ class MouvementStock extends CommonObject
{ {
if ($sellby) if ($sellby)
{ {
$tmparray=dol_getdate($sellby, true); $tmparray = dol_getdate($sellby, true);
$sellbywithouthour=dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']); $sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) // We test date without hours and with hours for backward compatibility if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) // We test date without hours and with hours for backward compatibility
{ {
// If found and eatby/sellby defined into table and provided and differs, return error // If found and eatby/sellby defined into table and provided and differs, return error
$this->errors[]=$langs->trans("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)); $this->errors[] = $langs->trans("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR); dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
$this->db->rollback(); $this->db->rollback();
return -3; return -3;
@ -303,25 +303,25 @@ class MouvementStock extends CommonObject
} }
// Define if we must make the stock change (If product type is a service or if stock is used also for services) // Define if we must make the stock change (If product type is a service or if stock is used also for services)
$movestock=0; $movestock = 0;
if ($product->type != Product::TYPE_SERVICE || ! empty($conf->global->STOCK_SUPPORTS_SERVICES)) $movestock=1; if ($product->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) $movestock = 1;
// Check if stock is enough when qty is < 0 // Check if stock is enough when qty is < 0
// Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2. // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2.
if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER)) if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER))
{ {
if (! empty($conf->productbatch->enabled) && $product->hasbatch() && ! $skip_batch) if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch)
{ {
$foundforbatch=0; $foundforbatch = 0;
$qtyisnotenough=0; $qtyisnotenough = 0;
foreach($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch)
{ {
if ($batch != $batchcursor) continue; if ($batch != $batchcursor) continue;
$foundforbatch=1; $foundforbatch = 1;
if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty; if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty;
break; break;
} }
if (! $foundforbatch || $qtyisnotenough) if (!$foundforbatch || $qtyisnotenough)
{ {
$langs->load("stocks"); $langs->load("stocks");
include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php'; include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
@ -350,10 +350,10 @@ class MouvementStock extends CommonObject
if ($movestock && $entrepot_id > 0) // Change stock for current product, change for subproduct is done after if ($movestock && $entrepot_id > 0) // Change stock for current product, change for subproduct is done after
{ {
$fk_project = 0; $fk_project = 0;
if(!empty($this->origin)) { // This is set by caller for tracking reason if (!empty($this->origin)) { // This is set by caller for tracking reason
$origintype = $this->origin->element; $origintype = $this->origin->element;
$fk_origin = $this->origin->id; $fk_origin = $this->origin->id;
if($origintype == 'project') $fk_project = $fk_origin; if ($origintype == 'project') $fk_project = $fk_origin;
else else
{ {
$res = $this->origin->fetch($fk_origin); $res = $this->origin->fetch($fk_origin);
@ -372,22 +372,22 @@ class MouvementStock extends CommonObject
} }
$sql = "INSERT INTO ".MAIN_DB_PREFIX."stock_mouvement("; $sql = "INSERT INTO ".MAIN_DB_PREFIX."stock_mouvement(";
$sql.= " datem, fk_product, batch, eatby, sellby,"; $sql .= " datem, fk_product, batch, eatby, sellby,";
$sql.= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet"; $sql .= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet";
$sql.= ")"; $sql .= ")";
$sql.= " VALUES ('".$this->db->idate($now)."', ".$this->product_id.", "; $sql .= " VALUES ('".$this->db->idate($now)."', ".$this->product_id.", ";
$sql.= " ".($batch?"'".$batch."'":"null").", "; $sql .= " ".($batch ? "'".$batch."'" : "null").", ";
$sql.= " ".($eatby?"'".$this->db->idate($eatby)."'":"null").", "; $sql .= " ".($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ";
$sql.= " ".($sellby?"'".$this->db->idate($sellby)."'":"null").", "; $sql .= " ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ";
$sql.= " ".$this->entrepot_id.", ".$this->qty.", ".$this->type.","; $sql .= " ".$this->entrepot_id.", ".$this->qty.", ".$this->type.",";
$sql.= " ".$user->id.","; $sql .= " ".$user->id.",";
$sql.= " '".$this->db->escape($label)."',"; $sql .= " '".$this->db->escape($label)."',";
$sql.= " ".($inventorycode?"'".$this->db->escape($inventorycode)."'":"null").","; $sql .= " ".($inventorycode ? "'".$this->db->escape($inventorycode)."'" : "null").",";
$sql.= " '".price2num($price)."',"; $sql .= " '".price2num($price)."',";
$sql.= " '".$fk_origin."',"; $sql .= " '".$fk_origin."',";
$sql.= " '".$origintype."',"; $sql .= " '".$origintype."',";
$sql.= " ". $fk_project; $sql .= " ".$fk_project;
$sql.= ")"; $sql .= ")";
dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG); dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG);
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -399,24 +399,24 @@ class MouvementStock extends CommonObject
} }
else else
{ {
$this->errors[]=$this->db->lasterror(); $this->errors[] = $this->db->lasterror();
$error = -1; $error = -1;
} }
// Define current values for qty and pmp // Define current values for qty and pmp
$oldqty=$product->stock_reel; $oldqty = $product->stock_reel;
$oldpmp=$product->pmp; $oldpmp = $product->pmp;
$oldqtywarehouse=0; $oldqtywarehouse = 0;
// Test if there is already a record for couple (warehouse / product) // Test if there is already a record for couple (warehouse / product)
$alreadyarecord = 0; $alreadyarecord = 0;
if (! $error) if (!$error)
{ {
$sql = "SELECT rowid, reel FROM ".MAIN_DB_PREFIX."product_stock"; $sql = "SELECT rowid, reel FROM ".MAIN_DB_PREFIX."product_stock";
$sql.= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; // This is a unique key $sql .= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; // This is a unique key
dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG); dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG);
$resql=$this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql)
{ {
$obj = $this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
@ -430,25 +430,25 @@ class MouvementStock extends CommonObject
} }
else else
{ {
$this->errors[]=$this->db->lasterror(); $this->errors[] = $this->db->lasterror();
$error = -2; $error = -2;
} }
} }
// Calculate new PMP. // Calculate new PMP.
$newpmp=0; $newpmp = 0;
if (! $error) if (!$error)
{ {
// Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0. // Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0.
// Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input) // Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input)
if (($type == 0 || $type == 3) && $price > 0) if (($type == 0 || $type == 3) && $price > 0)
{ {
$oldqtytouse=($oldqty >= 0?$oldqty:0); $oldqtytouse = ($oldqty >= 0 ? $oldqty : 0);
// We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined // We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined
if ($oldpmp > 0) $newpmp=price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU'); if ($oldpmp > 0) $newpmp = price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU');
else else
{ {
$newpmp=$price; // For this product, PMP was not yet set. We set it to input price. $newpmp = $price; // For this product, PMP was not yet set. We set it to input price.
} }
//print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." "; //print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." ";
//print "qty=".$qty." newpmp=".$newpmp; //print "qty=".$qty." newpmp=".$newpmp;
@ -465,25 +465,25 @@ class MouvementStock extends CommonObject
} }
} }
// Update stock quantity // Update stock quantity
if (! $error) if (!$error)
{ {
if ($alreadyarecord > 0) if ($alreadyarecord > 0)
{ {
$sql = "UPDATE ".MAIN_DB_PREFIX."product_stock SET reel = reel + ".$qty; $sql = "UPDATE ".MAIN_DB_PREFIX."product_stock SET reel = reel + ".$qty;
$sql.= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product; $sql .= " WHERE fk_entrepot = ".$entrepot_id." AND fk_product = ".$fk_product;
} }
else else
{ {
$sql = "INSERT INTO ".MAIN_DB_PREFIX."product_stock"; $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_stock";
$sql.= " (reel, fk_entrepot, fk_product) VALUES "; $sql .= " (reel, fk_entrepot, fk_product) VALUES ";
$sql.= " (".$qty.", ".$entrepot_id.", ".$fk_product.")"; $sql .= " (".$qty.", ".$entrepot_id.", ".$fk_product.")";
} }
dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG); dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG);
$resql=$this->db->query($sql); $resql = $this->db->query($sql);
if (! $resql) if (!$resql)
{ {
$this->errors[]=$this->db->lasterror(); $this->errors[] = $this->db->lasterror();
$error = -3; $error = -3;
} }
elseif (empty($fk_product_stock)) elseif (empty($fk_product_stock))
@ -493,61 +493,61 @@ class MouvementStock extends CommonObject
} }
// Update detail stock for batch product // Update detail stock for batch product
if (! $error && ! empty($conf->productbatch->enabled) && $product->hasbatch() && ! $skip_batch) if (!$error && !empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch)
{ {
if ($id_product_batch > 0) if ($id_product_batch > 0)
{ {
$result=$this->createBatch($id_product_batch, $qty); $result = $this->createBatch($id_product_batch, $qty);
} }
else else
{ {
$param_batch=array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch); $param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch);
$result=$this->createBatch($param_batch, $qty); $result = $this->createBatch($param_batch, $qty);
} }
if ($result<0) $error++; if ($result < 0) $error++;
} }
// Update PMP and denormalized value of stock qty at product level // Update PMP and denormalized value of stock qty at product level
if (! $error) if (!$error)
{ {
// $sql = "UPDATE ".MAIN_DB_PREFIX."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty; // $sql = "UPDATE ".MAIN_DB_PREFIX."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty;
// $sql.= " WHERE rowid = ".$fk_product; // $sql.= " WHERE rowid = ".$fk_product;
// Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
$sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$newpmp.", "; $sql = "UPDATE ".MAIN_DB_PREFIX."product as p SET pmp = ".$newpmp.", ";
$sql.= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)"; $sql .= " stock=(SELECT SUM(ps.reel) FROM ".MAIN_DB_PREFIX."product_stock as ps WHERE ps.fk_product = p.rowid)";
$sql.= " WHERE rowid = ".$fk_product; $sql .= " WHERE rowid = ".$fk_product;
dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG); dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG);
$resql=$this->db->query($sql); $resql = $this->db->query($sql);
if (! $resql) if (!$resql)
{ {
$this->errors[]=$this->db->lasterror(); $this->errors[] = $this->db->lasterror();
$error = -4; $error = -4;
} }
} }
// If stock is now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine // If stock is now 0, we can remove entry into llx_product_stock, but only if there is no child lines into llx_product_batch (detail of batch, because we can imagine
// having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot. // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
$sql="DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)"; $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".MAIN_DB_PREFIX."product_batch as pb)";
$resql=$this->db->query($sql); $resql = $this->db->query($sql);
// We do not test error, it can fails if there is child in batch details // We do not test error, it can fails if there is child in batch details
} }
// Add movement for sub products (recursive call) // Add movement for sub products (recursive call)
if (! $error && ! empty($conf->global->PRODUIT_SOUSPRODUITS) && empty($conf->global->INDEPENDANT_SUBPRODUCT_STOCK)) if (!$error && !empty($conf->global->PRODUIT_SOUSPRODUITS) && empty($conf->global->INDEPENDANT_SUBPRODUCT_STOCK))
{ {
$error = $this->_createSubProduct($user, $fk_product, $entrepot_id, $qty, $type, 0, $label, $inventorycode); // we use 0 as price, because pmp is not changed for subproduct $error = $this->_createSubProduct($user, $fk_product, $entrepot_id, $qty, $type, 0, $label, $inventorycode); // we use 0 as price, because pmp is not changed for subproduct
} }
if ($movestock && ! $error) if ($movestock && !$error)
{ {
// Call trigger // Call trigger
$result=$this->call_trigger('STOCK_MOVEMENT', $user); $result = $this->call_trigger('STOCK_MOVEMENT', $user);
if ($result < 0) $error++; if ($result < 0) $error++;
// End call triggers // End call triggers
} }
if (! $error) if (!$error)
{ {
$this->db->commit(); $this->db->commit();
return $mvid; return $mvid;
@ -591,12 +591,12 @@ class MouvementStock extends CommonObject
$sql .= " t.eatby,"; $sql .= " t.eatby,";
$sql .= " t.sellby,"; $sql .= " t.sellby,";
$sql .= " t.fk_projet as fk_project"; $sql .= " t.fk_projet as fk_project";
$sql .= ' FROM ' . MAIN_DB_PREFIX . $this->table_element . ' as t'; $sql .= ' FROM '.MAIN_DB_PREFIX.$this->table_element.' as t';
$sql.= ' WHERE 1 = 1'; $sql .= ' WHERE 1 = 1';
//if (null !== $ref) { //if (null !== $ref) {
//$sql .= ' AND t.ref = ' . '\'' . $ref . '\''; //$sql .= ' AND t.ref = ' . '\'' . $ref . '\'';
//} else { //} else {
$sql .= ' AND t.rowid = ' . $id; $sql .= ' AND t.rowid = '.$id;
//} //}
$resql = $this->db->query($sql); $resql = $this->db->query($sql);
@ -640,10 +640,10 @@ class MouvementStock extends CommonObject
return 0; return 0;
} }
} else { } else {
$this->errors[] = 'Error ' . $this->db->lasterror(); $this->errors[] = 'Error '.$this->db->lasterror();
dol_syslog(__METHOD__ . ' ' . implode(',', $this->errors), LOG_ERR); dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
return - 1; return -1;
} }
} }
@ -672,19 +672,19 @@ class MouvementStock extends CommonObject
$pqtys = array(); $pqtys = array();
$sql = "SELECT fk_product_pere, fk_product_fils, qty"; $sql = "SELECT fk_product_pere, fk_product_fils, qty";
$sql.= " FROM ".MAIN_DB_PREFIX."product_association"; $sql .= " FROM ".MAIN_DB_PREFIX."product_association";
$sql.= " WHERE fk_product_pere = ".$idProduct; $sql .= " WHERE fk_product_pere = ".$idProduct;
$sql.= " AND incdec = 1"; $sql .= " AND incdec = 1";
dol_syslog(get_class($this)."::_createSubProduct for parent product ".$idProduct, LOG_DEBUG); dol_syslog(get_class($this)."::_createSubProduct for parent product ".$idProduct, LOG_DEBUG);
$resql=$this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql)
{ {
$i=0; $i = 0;
while ($obj=$this->db->fetch_object($resql)) while ($obj = $this->db->fetch_object($resql))
{ {
$pids[$i]=$obj->fk_product_fils; $pids[$i] = $obj->fk_product_fils;
$pqtys[$i]=$obj->qty; $pqtys[$i] = $obj->qty;
$i++; $i++;
} }
$this->db->free($resql); $this->db->free($resql);
@ -695,12 +695,12 @@ class MouvementStock extends CommonObject
} }
// Create movement for each subproduct // Create movement for each subproduct
foreach($pids as $key => $value) foreach ($pids as $key => $value)
{ {
if (! $error) if (!$error)
{ {
$tmpmove = clone $this; $tmpmove = clone $this;
$result = $tmpmove->_create($user, $pids[$key], $entrepot_id, ($qty * $pqtys[$key]), $type, 0, $label, $inventorycode); // This will also call _createSubProduct making this recursive $result = $tmpmove->_create($user, $pids[$key], $entrepot_id, ($qty * $pqtys[$key]), $type, 0, $label, $inventorycode); // This will also call _createSubProduct making this recursive
if ($result < 0) if ($result < 0)
{ {
$this->error = $tmpmove->error; $this->error = $tmpmove->error;
@ -736,7 +736,7 @@ class MouvementStock extends CommonObject
* @param string $inventorycode Inventory code * @param string $inventorycode Inventory code
* @return int <0 if KO, >0 if OK * @return int <0 if KO, >0 if OK
*/ */
public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode='') public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '')
{ {
global $conf; global $conf;
@ -762,7 +762,7 @@ class MouvementStock extends CommonObject
* @param string $inventorycode Inventory code * @param string $inventorycode Inventory code
* @return int <0 if KO, >0 if OK * @return int <0 if KO, >0 if OK
*/ */
public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode='') public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode = '')
{ {
global $conf; global $conf;
@ -803,19 +803,19 @@ class MouvementStock extends CommonObject
*/ */
public function calculateBalanceForProductBefore($productidselected, $datebefore) public function calculateBalanceForProductBefore($productidselected, $datebefore)
{ {
$nb=0; $nb = 0;
$sql = 'SELECT SUM(value) as nb from '.MAIN_DB_PREFIX.'stock_mouvement'; $sql = 'SELECT SUM(value) as nb from '.MAIN_DB_PREFIX.'stock_mouvement';
$sql.= ' WHERE fk_product = '.$productidselected; $sql .= ' WHERE fk_product = '.$productidselected;
$sql.= " AND datem < '".$this->db->idate($datebefore)."'"; $sql .= " AND datem < '".$this->db->idate($datebefore)."'";
dol_syslog(get_class($this).__METHOD__.'', LOG_DEBUG); dol_syslog(get_class($this).__METHOD__.'', LOG_DEBUG);
$resql=$this->db->query($sql); $resql = $this->db->query($sql);
if ($resql) if ($resql)
{ {
$obj=$this->db->fetch_object($resql); $obj = $this->db->fetch_object($resql);
if ($obj) $nb = $obj->nb; if ($obj) $nb = $obj->nb;
return (empty($nb)?0:$nb); return (empty($nb) ? 0 : $nb);
} }
else else
{ {
@ -837,14 +837,14 @@ class MouvementStock extends CommonObject
{ {
global $user; global $user;
$pdluo=new Productbatch($this->db); $pdluo = new Productbatch($this->db);
$result=0; $result = 0;
// Try to find an existing record with same batch number or id // Try to find an existing record with same batch number or id
if (is_numeric($dluo)) if (is_numeric($dluo))
{ {
$result=$pdluo->fetch($dluo); $result = $pdluo->fetch($dluo);
if (empty($pdluo->id)) if (empty($pdluo->id))
{ {
// We didn't find the line. May be it was deleted before by a previous move in same transaction. // We didn't find the line. May be it was deleted before by a previous move in same transaction.
@ -857,10 +857,10 @@ class MouvementStock extends CommonObject
{ {
if (isset($dluo['fk_product_stock'])) if (isset($dluo['fk_product_stock']))
{ {
$vfk_product_stock=$dluo['fk_product_stock']; $vfk_product_stock = $dluo['fk_product_stock'];
$vbatchnumber = $dluo['batchnumber']; $vbatchnumber = $dluo['batchnumber'];
$result = $pdluo->find($vfk_product_stock, '', '', $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here) $result = $pdluo->find($vfk_product_stock, '', '', $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here)
} }
else else
{ {
@ -883,24 +883,24 @@ class MouvementStock extends CommonObject
$pdluo->qty += $qty; $pdluo->qty += $qty;
if ($pdluo->qty == 0) if ($pdluo->qty == 0)
{ {
$result=$pdluo->delete($user, 1); $result = $pdluo->delete($user, 1);
} else { } else {
$result=$pdluo->update($user, 1); $result = $pdluo->update($user, 1);
} }
} }
else // product_batch record not found else // product_batch record not found
{ {
$pdluo->fk_product_stock=$vfk_product_stock; $pdluo->fk_product_stock = $vfk_product_stock;
$pdluo->qty = $qty; $pdluo->qty = $qty;
$pdluo->eatby = $veatby; $pdluo->eatby = $veatby;
$pdluo->sellby = $vsellby; $pdluo->sellby = $vsellby;
$pdluo->batch = $vbatchnumber; $pdluo->batch = $vbatchnumber;
$result=$pdluo->create($user, 1); $result = $pdluo->create($user, 1);
if ($result < 0) if ($result < 0)
{ {
$this->error=$pdluo->error; $this->error = $pdluo->error;
$this->errors=$pdluo->errors; $this->errors = $pdluo->errors;
} }
} }
} }
@ -919,7 +919,7 @@ class MouvementStock extends CommonObject
public function get_origin($fk_origin, $origintype) public function get_origin($fk_origin, $origintype)
{ {
// phpcs:enable // phpcs:enable
$origin=''; $origin = '';
switch ($origintype) { switch ($origintype) {
case 'commande': case 'commande':
@ -954,7 +954,7 @@ class MouvementStock extends CommonObject
default: default:
if ($origintype) if ($origintype)
{ {
$result=dol_include_once('/'.$origintype.'/class/'.$origintype.'.class.php'); $result = dol_include_once('/'.$origintype.'/class/'.$origintype.'.class.php');
if ($result) if ($result)
{ {
$classname = ucfirst($origintype); $classname = ucfirst($origintype);
@ -964,7 +964,7 @@ class MouvementStock extends CommonObject
break; break;
} }
if (empty($origin) || ! is_object($origin)) return ''; if (empty($origin) || !is_object($origin)) return '';
if ($origin->fetch($fk_origin) > 0) { if ($origin->fetch($fk_origin) > 0) {
return $origin->getNomUrl(1); return $origin->getNomUrl(1);
@ -985,7 +985,7 @@ class MouvementStock extends CommonObject
{ {
if (!empty($origin_element) && $origin_id > 0) if (!empty($origin_element) && $origin_id > 0)
{ {
$origin=''; $origin = '';
if ($origin_element == 'project') if ($origin_element == 'project')
{ {
if (!class_exists('Project')) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php'; if (!class_exists('Project')) require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
@ -1010,10 +1010,10 @@ class MouvementStock extends CommonObject
*/ */
public function initAsSpecimen() public function initAsSpecimen()
{ {
global $user,$langs,$conf,$mysoc; global $user, $langs, $conf, $mysoc;
// Initialize parameters // Initialize parameters
$this->id=0; $this->id = 0;
// There is no specific properties. All data into insert are provided as method parameter. // There is no specific properties. All data into insert are provided as method parameter.
} }
@ -1036,23 +1036,23 @@ class MouvementStock extends CommonObject
$result = ''; $result = '';
$companylink = ''; $companylink = '';
$label = '<u>' . $langs->trans("Movement") . ' '.$this->id.'</u>'; $label = '<u>'.$langs->trans("Movement").' '.$this->id.'</u>';
$label.= '<div width="100%">'; $label .= '<div width="100%">';
$label.= '<b>' . $langs->trans('Label') . ':</b> ' . $this->label; $label .= '<b>'.$langs->trans('Label').':</b> '.$this->label;
$label.= '<br><b>' . $langs->trans('Qty') . ':</b> ' .$this->qty; $label .= '<br><b>'.$langs->trans('Qty').':</b> '.$this->qty;
$label.= '</div>'; $label .= '</div>';
$link = '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$this->warehouse_id.'&msid='.$this->id.'"'; $link = '<a href="'.DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$this->warehouse_id.'&msid='.$this->id.'"';
$link.= ($notooltip?'':' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss?' '.$morecss:'').'"'); $link .= ($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
$link.= '>'; $link .= '>';
$linkend='</a>'; $linkend = '</a>';
if ($withpicto) if ($withpicto)
{ {
$result.=($link.img_object(($notooltip?'':$label), 'stock', ($notooltip?'':'class="classfortooltip"')).$linkend); $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
if ($withpicto != 2) $result.=' '; if ($withpicto != 2) $result .= ' ';
} }
$result.= $link . $this->id . $linkend; $result .= $link.$this->id.$linkend;
return $result; return $result;
} }
@ -1113,16 +1113,16 @@ class MouvementStock extends CommonObject
*/ */
public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0) public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
{ {
global $conf,$user,$langs; global $conf, $user, $langs;
$langs->load("stocks"); $langs->load("stocks");
if (! dol_strlen($modele)) { if (!dol_strlen($modele)) {
$modele = 'stdmovement'; $modele = 'stdmovement';
if ($this->modelpdf) { if ($this->modelpdf) {
$modele = $this->modelpdf; $modele = $this->modelpdf;
} elseif (! empty($conf->global->MOUVEMENT_ADDON_PDF)) { } elseif (!empty($conf->global->MOUVEMENT_ADDON_PDF)) {
$modele = $conf->global->MOUVEMENT_ADDON_PDF; $modele = $conf->global->MOUVEMENT_ADDON_PDF;
} }
} }