dolibarr 22.0.5
mouvementstock.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3 * Copyright (C) 2005-2015 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2011 Jean Heimburger <jean@tiaris.info>
5 * Copyright (C) 2014 Cedric GROSS <c.gross@kreiz-it.fr>
6 * Copyright (C) 2024-2025 MDW <mdeweerd@users.noreply.github.com>
7 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
34{
38 public $element = 'stockmouvement';
39
43 public $table_element = 'stock_mouvement';
44
45
49 public $product_id;
50
56 public $entrepot_id;
57
61 public $warehouse_id;
62
66 public $qty;
67
76 public $type;
77
81 public $datem = '';
85 public $price;
86
90 public $fk_user_author;
91
95 public $label;
96
102 public $fk_origin;
103
107 public $origin_id;
108
114 public $origintype;
115
119 public $origin_type;
123 public $line_id_oject_src;
127 public $line_id_oject_origin;
128
132 public $inventorycode;
133
137 public $batch;
138
142 public $line_id_object_src;
146 public $line_id_object_origin;
147
151 public $eatby;
152
156 public $sellby;
157
158
159
160 public $fields = array(
161 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10, 'showoncombobox' => 1),
162 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
163 'datem' => array('type' => 'datetime', 'label' => 'Datem', 'enabled' => 1, 'visible' => -1, 'position' => 20),
164 'fk_product' => array('type' => 'integer:Product:product/class/product.class.php:1', 'label' => 'Product', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
165 'fk_entrepot' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 30),
166 'value' => array('type' => 'double', 'label' => 'Value', 'enabled' => 1, 'visible' => -1, 'position' => 35),
167 'price' => array('type' => 'double(24,8)', 'label' => 'Price', 'enabled' => 1, 'visible' => -1, 'position' => 40),
168 'type_mouvement' => array('type' => 'smallint(6)', 'label' => 'Type mouvement', 'enabled' => 1, 'visible' => -1, 'position' => 45),
169 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user author', 'enabled' => 1, 'visible' => -1, 'position' => 50),
170 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => -1, 'position' => 55),
171 'fk_origin' => array('type' => 'integer', 'label' => 'Fk origin', 'enabled' => 1, 'visible' => -1, 'position' => 60),
172 'origintype' => array('type' => 'varchar(32)', 'label' => 'Origintype', 'enabled' => 1, 'visible' => -1, 'position' => 65),
173 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 70),
174 'fk_projet' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => '$conf->project->enabled', 'visible' => -1, 'notnull' => 1, 'position' => 75),
175 'inventorycode' => array('type' => 'varchar(128)', 'label' => 'InventoryCode', 'enabled' => 1, 'visible' => -1, 'position' => 80),
176 'batch' => array('type' => 'varchar(30)', 'label' => 'Batch', 'enabled' => 1, 'visible' => -1, 'position' => 85),
177 'eatby' => array('type' => 'date', 'label' => 'Eatby', 'enabled' => 1, 'visible' => -1, 'position' => 90),
178 'sellby' => array('type' => 'date', 'label' => 'Sellby', 'enabled' => 1, 'visible' => -1, 'position' => 95),
179 'fk_project' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Fk project', 'enabled' => 1, 'visible' => -1, 'position' => 100),
180 );
181
182
183
189 public function __construct($db)
190 {
191 $this->db = $db;
192 }
193
194 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
222 public function _create($user, $fk_product, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '', $eatby = 0, $sellby = 0, $batch = '', $skip_batch = false, $id_product_batch = 0, $disablestockchangeforsubproduct = 0, $donotcleanemptylines = 0, $force_update_batch = false)
223 {
224 // phpcs:enable
225 global $conf, $langs;
226
227 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
228 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
229
230 $error = 0;
231 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=".json_encode($skip_batch));
232
233 // Call hook at beginning
234 global $action, $hookmanager;
235 $hookmanager->initHooks(array('mouvementstock'));
236
237 if (is_object($hookmanager)) {
238 $parameters = array(
239 'currentcontext' => 'mouvementstock',
240 'user' => &$user,
241 'fk_product' => &$fk_product,
242 'entrepot_id' => &$entrepot_id,
243 'qty' => &$qty,
244 'type' => &$type,
245 'price' => &$price,
246 'label' => &$label,
247 'inventorycode' => &$inventorycode,
248 'datem' => &$datem,
249 'eatby' => &$eatby,
250 'sellby' => &$sellby,
251 'batch' => &$batch,
252 'skip_batch' => &$skip_batch,
253 'id_product_batch' => &$id_product_batch
254 );
255 $reshook = $hookmanager->executeHooks('stockMovementCreate', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
256
257 if ($reshook < 0) {
258 if (!empty($hookmanager->resPrint)) {
259 dol_print_error(null, $hookmanager->resPrint);
260 }
261 return $reshook;
262 } elseif ($reshook > 0) {
263 return $reshook;
264 }
265 }
266 // end hook at beginning
267
268 // Clean parameters
269 $price = price2num($price, 'MU'); // Clean value for the casse we receive a float zero value, to have it a real zero value.
270 if (empty($price)) {
271 $price = 0;
272 }
273 $now = (!empty($datem) ? $datem : dol_now());
274
275 // Check parameters
276 if (!($fk_product > 0)) {
277 return 0;
278 }
279 if (!($entrepot_id > 0)) {
280 return 0;
281 }
282
283 if (is_numeric($eatby) && $eatby < 0) {
284 dol_syslog(get_class($this)."::_create start ErrorBadValueForParameterEatBy eatby = ".$eatby);
285 $this->errors[] = 'ErrorBadValueForParameterEatBy';
286 return -1;
287 }
288 if (is_numeric($sellby) && $sellby < 0) {
289 dol_syslog(get_class($this)."::_create start ErrorBadValueForParameterSellBy sellby = ".$sellby);
290 $this->errors[] = 'ErrorBadValueForParameterSellBy';
291 return -1;
292 }
293
294 // Set properties of movement
295 $this->product_id = $fk_product;
296 $this->entrepot_id = $entrepot_id; // deprecated
297 $this->warehouse_id = $entrepot_id;
298 $this->qty = $qty;
299 $this->type = $type;
300 $this->price = price2num($price);
301 $this->label = $label;
302 $this->inventorycode = $inventorycode;
303 $this->datem = $now;
304 $this->batch = $batch;
305
306 $mvid = 0;
307
308 $product = new Product($this->db);
309
310 $result = $product->fetch($fk_product);
311 if ($result < 0) {
312 $this->error = $product->error;
313 $this->errors = $product->errors;
314 dol_print_error(null, "Failed to fetch product");
315 return -1;
316 }
317 if ($product->id <= 0) { // Can happen if database is corrupted (a product id exist in stock with product that has been removed)
318 return 0;
319 }
320
321 // Define if we must make the stock change (If product type is a service or if stock is used also for services)
322 // Only record into stock tables will be disabled by this (the rest like writing into lot table or movement of subproucts are done)
323 $movestock = 0;
324 $productChildrenNb = 0;
325 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
326 $productChildrenNb = $product->hasFatherOrChild(1);
327 }
328
329 if (($product->type != Product::TYPE_SERVICE || getDolGlobalString('STOCK_SUPPORTS_SERVICES')) && ($productChildrenNb == 0 || getDolGlobalInt('PRODUIT_SOUSPRODUITS_ALSO_ENABLE_PARENT_STOCK_MOVE'))) {
330 $movestock = 1;
331 }
332
333 $this->db->begin();
334
335 // Set value $product->stock_reel and detail per warehouse into $product->stock_warehouse array
336 if ($movestock) {
337 $product->load_stock('novirtual');
338 }
339
340 // Test if product require batch data. If yes, and there is not or values are not correct, we throw an error.
341 if (isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
342 if (empty($batch)) {
343 $langs->load("errors");
344 $this->errors[] = $langs->transnoentitiesnoconv("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref);
345 dol_syslog("Try to make a movement of a product with status_batch on without any batch data", LOG_ERR);
346
347 $this->db->rollback();
348 return -2;
349 }
350
351 // Check table llx_product_lot from batchnumber for same product
352 // If found and eatby/sellby defined into table and provided and differs, return error
353 // If found and eatby/sellby defined into table and not provided, we take value from table
354 // If found and eatby/sellby not defined into table and provided, we update table
355 // If found and eatby/sellby not defined into table and not provided, we do nothing
356 // If not found, we add record
357 $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".$this->db->prefix()."product_lot as pb";
358 $sql .= " WHERE pb.fk_product = ".((int) $fk_product)." AND pb.batch = '".$this->db->escape($batch)."'";
359
360 dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
361
362 $resql = $this->db->query($sql);
363 if ($resql) {
364 $num = $this->db->num_rows($resql);
365 $i = 0;
366 if ($num > 0) {
367 while ($i < $num) {
368 $obj = $this->db->fetch_object($resql);
369 if ($obj->eatby) {
370 if ($eatby) {
371 $tmparray = dol_getdate((int) $eatby, true);
372 $eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
373 if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) { // We test date without hours and with hours for backward compatibility
374 // If found and eatby/sellby defined into table and provided and differs, return error
375 $langs->load("stocks");
376 $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatbywithouthour, 'dayhour'));
377 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);
378 $this->db->rollback();
379 return -3;
380 }
381 } else {
382 $eatby = $obj->eatby; // If found and eatby/sellby defined into table and not provided, we take value from table
383 }
384 } else {
385 if ($eatby) { // If found and eatby/sellby not defined into table and provided, we update table
386 $productlot = new Productlot($this->db);
387 $result = $productlot->fetch($obj->rowid);
388 $productlot->eatby = $eatby;
389 $result = $productlot->update($user);
390 if ($result <= 0) {
391 $this->error = $productlot->error;
392 $this->errors = $productlot->errors;
393 $this->db->rollback();
394 return -5;
395 }
396 }
397 }
398 if ($obj->sellby) {
399 if ($sellby) {
400 $tmparray = dol_getdate((int) $sellby, true);
401 $sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
402 if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) { // We test date without hours and with hours for backward compatibility
403 // If found and eatby/sellby defined into table and provided and differs, return error
404 $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
405 dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
406 $this->db->rollback();
407 return -3;
408 }
409 } else {
410 $sellby = $obj->sellby; // If found and eatby/sellby defined into table and not provided, we take value from table
411 }
412 } else {
413 if ($sellby) { // If found and eatby/sellby not defined into table and provided, we update table
414 $productlot = new Productlot($this->db);
415 $result = $productlot->fetch($obj->rowid);
416 $productlot->sellby = $sellby;
417 $result = $productlot->update($user);
418 if ($result <= 0) {
419 $this->error = $productlot->error;
420 $this->errors = $productlot->errors;
421 $this->db->rollback();
422 return -5;
423 }
424 }
425 }
426
427 $i++;
428 }
429 } else { // If not found, we add record
430 $productlot = new Productlot($this->db);
431 $productlot->origin_type = !empty($this->origin_type) ? $this->origin_type : '';
432 $productlot->origin_id = !empty($this->origin_id) ? $this->origin_id : 0;
433 $productlot->entity = $conf->entity;
434 $productlot->fk_product = $fk_product;
435 $productlot->batch = $batch;
436 // If we are here = first time we manage this batch, so we used dates provided by users to create lot
437 $productlot->eatby = $eatby;
438 $productlot->sellby = $sellby;
439 $result = $productlot->create($user);
440 if ($result <= 0) {
441 $this->error = $productlot->error;
442 $this->errors = $productlot->errors;
443 $this->db->rollback();
444 return -4;
445 }
446 }
447 } else {
448 dol_print_error($this->db);
449 $this->db->rollback();
450 return -1;
451 }
452 }
453
454 // Check if stock is enough when qty is < 0.
455 // THIS MUST BE DONE AT END OF MOVEMENTS
456 // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2.
457 if ($movestock && $qty < 0 && getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER')) {
458 if (isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
459 $foundforbatch = 0;
460 $qtyisnotenough = 0;
461 if (isset($product->stock_warehouse[$entrepot_id])) {
462 foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) {
463 if ((string) $batch != (string) $batchcursor) { // Lot '59' must be different than lot '59c'
464 continue;
465 }
466
467 $foundforbatch = 1;
468 if ($prodbatch->qty < abs($qty)) {
469 $qtyisnotenough = $prodbatch->qty;
470 }
471 break;
472 }
473 }
474 if (!$foundforbatch || $qtyisnotenough) {
475 $langs->load("stocks");
476 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
477 $tmpwarehouse = new Entrepot($this->db);
478 $tmpwarehouse->fetch($entrepot_id);
479
480 $this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
481 $this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
482 $this->db->rollback();
483 return -8;
484 }
485 } else {
486 if ($product->stockable_product == Product::ENABLED_STOCK && (empty($product->stock_warehouse[$entrepot_id]) || empty($product->stock_warehouse[$entrepot_id]->real) || $product->stock_warehouse[$entrepot_id]->real < abs($qty))) {
487 $langs->load("stocks");
488 $this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
489 $this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
490 $this->db->rollback();
491 return -8;
492 }
493 }
494 }
495
496 if ($movestock && $product->stockable_product == Product::ENABLED_STOCK) { // Change stock for current product, change for subproduct is done after
497 // Set $origin_type, origin_id and fk_project
498 $fk_project = $this->fk_project;
499 if (!empty($this->origin_type)) { // This is set by caller for tracking reason
500 $origin_type = $this->origin_type;
501 $origin_id = $this->origin_id;
502 if (empty($fk_project) && $origin_type == 'project') {
503 $fk_project = $origin_id;
504 $origin_type = '';
505 $origin_id = 0;
506 }
507 } else {
508 $fk_project = 0;
509 $origin_type = '';
510 $origin_id = 0;
511 }
512
513 $sql = "INSERT INTO ".$this->db->prefix()."stock_mouvement(";
514 $sql .= " datem, fk_product, batch, eatby, sellby,";
515 $sql .= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet";
516 $sql .= ")";
517 $sql .= " VALUES ('".$this->db->idate($this->datem)."', ".((int) $this->product_id).", ";
518 $sql .= " ".($batch ? "'".$this->db->escape($batch)."'" : "null").", ";
519 $sql .= " ".($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ";
520 $sql .= " ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ";
521 $sql .= " ".((int) $this->entrepot_id).", ".((float) $this->qty).", ".((int) $this->type).",";
522 $sql .= " ".((int) $user->id).",";
523 $sql .= " '".$this->db->escape($label)."',";
524 $sql .= " ".($inventorycode ? "'".$this->db->escape($inventorycode)."'" : "null").",";
525 $sql .= " ".((float) price2num($price)).",";
526 $sql .= " ".((int) $origin_id).",";
527 $sql .= " '".$this->db->escape($origin_type)."',";
528 $sql .= " ".((int) $fk_project);
529 $sql .= ")";
530
531 dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG);
532 $resql = $this->db->query($sql);
533
534 if ($resql) {
535 $mvid = $this->db->last_insert_id($this->db->prefix()."stock_mouvement");
536 $this->id = $mvid;
537 } else {
538 $this->error = $this->db->lasterror();
539 $this->errors[] = $this->error;
540 $error = -1;
541 }
542
543 // Define current values for qty and pmp
544 $oldqty = $product->stock_reel;
545 $oldpmp = $product->pmp;
546 $oldqtywarehouse = 0;
547
548 // Test if there is already a record for couple (warehouse / product), so later we will make an update or create.
549 $alreadyarecord = 0;
550 $fk_product_stock = 0;
551 if (!$error) {
552 $sql = "SELECT rowid, reel FROM ".$this->db->prefix()."product_stock";
553 $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product); // This is a unique key
554
555 dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG);
556 $resql = $this->db->query($sql);
557 if ($resql) {
558 $obj = $this->db->fetch_object($resql);
559 if ($obj) {
560 $alreadyarecord = 1;
561 $oldqtywarehouse = $obj->reel;
562 $fk_product_stock = $obj->rowid;
563 }
564 $this->db->free($resql);
565 } else {
566 $this->errors[] = $this->db->lasterror();
567 $error = -2;
568 }
569 }
570
571 // Calculate new AWP (PMP)
572 $newpmp = 0;
573 if (!$error) {
574 if ($type == 0 || $type == 3) {
575 // After a stock increase
576 // Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0.
577 // Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input)
578 if ($price > 0 || (getDolGlobalString('STOCK_UPDATE_AWP_EVEN_WHEN_ENTRY_PRICE_IS_NULL') && $price == 0 && in_array($this->origin_type, array('order_supplier', 'invoice_supplier')))) {
579 $oldqtytouse = ($oldqty >= 0 ? $oldqty : 0);
580 // We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined
581 if ($oldpmp > 0 && ($oldqtytouse + $qty) != 0) {
582 $newpmp = price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU');
583 } else {
584 $newpmp = $price; // For this product, PMP was not yet set. We set it to input price.
585 }
586 //print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." ";
587 //print "qty=".$qty." newpmp=".$newpmp;
588 //exit;
589 } else {
590 $newpmp = $oldpmp;
591 }
592 } else {
593 // ($type == 1 || $type == 2)
594 // -> After a stock decrease, we don't change value of the AWP/PMP of a product.
595 // else
596 // Type of movement unknown
597 $newpmp = $oldpmp;
598 }
599 }
600 // Update stock quantity
601 if (!$error) {
602 if ($alreadyarecord > 0) {
603 $sql = "UPDATE ".$this->db->prefix()."product_stock SET reel = " . ((float) $oldqtywarehouse + (float) $qty);
604 $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product);
605 } else {
606 $sql = "INSERT INTO ".$this->db->prefix()."product_stock";
607 $sql .= " (reel, fk_entrepot, fk_product) VALUES ";
608 $sql .= " (".((float) $qty).", ".((int) $entrepot_id).", ".((int) $fk_product).")";
609 }
610
611 dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG);
612 $resql = $this->db->query($sql);
613 if (!$resql) {
614 $this->errors[] = $this->db->lasterror();
615 $error = -3;
616 } elseif (empty($fk_product_stock)) {
617 $fk_product_stock = $this->db->last_insert_id($this->db->prefix()."product_stock");
618 }
619 }
620
621 // Update detail of stock for the lot.
622 if (!$error && isModEnabled('productbatch') && (($product->hasbatch() && !$skip_batch) || $force_update_batch)) {
623 if ($id_product_batch > 0) {
624 $result = $this->createBatch($id_product_batch, $qty);
625 if ($result == -2 && $fk_product_stock > 0) { // The entry for this product batch does not exists anymore, bu we already have a llx_product_stock, so we recreate the batch entry in product_batch
626 $param_batch = array('fk_product_stock' => $fk_product_stock, 'batchnumber' => $batch);
627 $result = $this->createBatch($param_batch, $qty);
628 }
629 } else {
630 $param_batch = array('fk_product_stock' => $fk_product_stock, 'batchnumber' => $batch);
631 $result = $this->createBatch($param_batch, $qty);
632 }
633 if ($result < 0) {
634 $error++;
635 }
636 }
637
638 // Update PMP and denormalized value of stock qty at product level
639 if (!$error) {
640 $newpmp = price2num($newpmp, 'MU');
641
642 // $sql = "UPDATE ".$this->db->prefix()."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty;
643 // $sql.= " WHERE rowid = ".((int) $fk_product);
644 // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
645 $sql = "UPDATE ".$this->db->prefix()."product as p SET pmp = ".((float) $newpmp).",";
646 $sql .= " stock=(SELECT SUM(ps.reel) FROM ".$this->db->prefix()."product_stock as ps WHERE ps.fk_product = p.rowid)";
647 $sql .= " WHERE rowid = ".((int) $fk_product);
648
649 dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG);
650 $resql = $this->db->query($sql);
651 if (!$resql) {
652 $this->errors[] = $this->db->lasterror();
653 $error = -4;
654 }
655 }
656
657 if (empty($donotcleanemptylines)) {
658 // 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
659 // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
660 $sql = "DELETE FROM ".$this->db->prefix()."product_stock WHERE reel = 0 AND rowid NOT IN (SELECT fk_product_stock FROM ".$this->db->prefix()."product_batch as pb)";
661 $resql = $this->db->query($sql);
662 // We do not test error, it can fails if there is child in batch details
663 }
664 }
665
666 // Add movement for sub products (recursive call)
667 if (!$error && getDolGlobalString('PRODUIT_SOUSPRODUITS') && !getDolGlobalString('INDEPENDANT_SUBPRODUCT_STOCK') && empty($disablestockchangeforsubproduct)) {
668 $error = $this->_createSubProduct($user, $fk_product, $entrepot_id, $qty, $type, 0, $label, $inventorycode, $datem); // we use 0 as price, because AWP must not change for subproduct
669 }
670
671 if ($movestock && !$error) {
672 // Call trigger
673 if ($product->stockable_product != Product::DISABLED_STOCK ) {
674 $result = $this->call_trigger('STOCK_MOVEMENT', $user);
675 if ($result < 0) {
676 $error++;
677 }
678 }
679 // End call triggers
680 // Check unicity for serial numbered equipment once all movement were done.
681 if (!$error && isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
682 if ($product->status_batch == 2 && $qty > 0) { // We check only if we increased qty
683 if ($this->getBatchCount($fk_product, $batch) > 1) {
684 $error++;
685 $this->errors[] = $langs->trans("TooManyQtyForSerialNumber", $product->ref, $batch);
686 }
687 }
688 }
689 }
690
691 if (!$error) {
692 $this->db->commit();
693 return $mvid;
694 } else {
695 $this->db->rollback();
696 dol_syslog(get_class($this)."::_create error code=".$error, LOG_ERR);
697 return -6;
698 }
699 }
700
701
702
710 public function fetch($id)
711 {
712 dol_syslog(__METHOD__, LOG_DEBUG);
713
714 $sql = "SELECT";
715 $sql .= " t.rowid,";
716 $sql .= " t.tms,";
717 $sql .= " t.datem,";
718 $sql .= " t.fk_product,";
719 $sql .= " t.fk_entrepot,";
720 $sql .= " t.value,";
721 $sql .= " t.price,";
722 $sql .= " t.type_mouvement,";
723 $sql .= " t.fk_user_author,";
724 $sql .= " t.label,";
725 $sql .= " t.fk_origin as origin_id,";
726 $sql .= " t.origintype as origin_type,";
727 $sql .= " t.inventorycode,";
728 $sql .= " t.batch,";
729 $sql .= " t.eatby,";
730 $sql .= " t.sellby,";
731 $sql .= " t.fk_projet as fk_project";
732 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
733 $sql .= " WHERE t.rowid = ".((int) $id);
734
735 $resql = $this->db->query($sql);
736 if ($resql) {
737 $numrows = $this->db->num_rows($resql);
738 if ($numrows) {
739 $obj = $this->db->fetch_object($resql);
740
741 $this->id = $obj->rowid;
742
743 $this->product_id = $obj->fk_product;
744 $this->warehouse_id = $obj->fk_entrepot;
745 $this->qty = $obj->value;
746 $this->type = $obj->type_mouvement;
747
748 $this->tms = $this->db->jdate($obj->tms);
749 $this->datem = $this->db->jdate($obj->datem);
750 $this->price = $obj->price;
751 $this->fk_user_author = $obj->fk_user_author;
752 $this->label = $obj->label;
753 $this->fk_origin = $obj->origin_id; // For backward compatibility
754 $this->origintype = $obj->origin_type; // For backward compatibility
755 $this->origin_id = $obj->origin_id;
756 $this->origin_type = $obj->origin_type;
757 $this->inventorycode = $obj->inventorycode;
758 $this->batch = $obj->batch;
759 $this->eatby = $this->db->jdate($obj->eatby);
760 $this->sellby = $this->db->jdate($obj->sellby);
761 $this->fk_project = $obj->fk_project;
762 }
763
764 // Retrieve all extrafield
765 $this->fetch_optionals();
766
767 // $this->fetch_lines();
768
769 $this->db->free($resql);
770
771 if ($numrows) {
772 return 1;
773 } else {
774 return 0;
775 }
776 } else {
777 $this->errors[] = 'Error '.$this->db->lasterror();
778 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
779
780 return -1;
781 }
782 }
783
784
785
786
801 private function _createSubProduct($user, $idProduct, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '')
802 {
803 global $langs;
804
805 $error = 0;
806
807 $sql = "SELECT fk_product_pere, fk_product_fils, qty";
808 $sql .= " FROM ".$this->db->prefix()."product_association";
809 $sql .= " WHERE fk_product_pere = ".((int) $idProduct);
810 $sql .= " AND incdec = 1";
811
812 dol_syslog(__METHOD__.' for parent product '.$idProduct, LOG_DEBUG);
813 $resql = $this->db->query($sql);
814 if ($resql) {
815 // Create movement for each sub-product
816 while ($obj = $this->db->fetch_object($resql)) {
817 $tmpmove = dol_clone($this, 1);
818 $result = $tmpmove->_create($user, $obj->fk_product_fils, $entrepot_id, ($qty * $obj->qty), $type, 0, $label, $inventorycode, $datem); // This will also call _createSubProduct making this recursive
819 if ($result < 0) {
820 $this->error = $tmpmove->error;
821 $this->errors = array_merge($this->errors, $tmpmove->errors);
822 if ($result == -2) {
823 $this->errors[] = $langs->trans('ErrorNoteAlsoThatSubProductCantBeFollowedByLot');
824 }
825 $error = $result;
826 dol_syslog(__METHOD__ . ' Error : ' . $this->errorsToString(), LOG_ERR);
827 break;
828 }
829 unset($tmpmove);
830 }
831
832 $this->db->free($resql);
833 } else {
834 $error = -2;
835 }
836
837 return $error;
838 }
839
840
859 public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '', $donotcleanemptylines = 0)
860 {
861 global $conf;
862
863 $skip_batch = empty($conf->productbatch->enabled);
864
865 return $this->_create($user, $fk_product, $entrepot_id, (0 - $qty), 2, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch, 0, $donotcleanemptylines);
866 }
867
887 public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode = '', $donotcleanemptylines = 0, $disablestockchangeforsubproduct = 0)
888 {
889 global $conf;
890
891 $skip_batch = empty($conf->productbatch->enabled);
892
893 return $this->_create($user, $fk_product, $entrepot_id, $qty, 3, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch, $disablestockchangeforsubproduct, $donotcleanemptylines);
894 }
895
903 public function calculateBalanceForProductBefore($productidselected, $datebefore)
904 {
905 $nb = 0;
906
907 $sql = "SELECT SUM(value) as nb from ".$this->db->prefix()."stock_mouvement";
908 $sql .= " WHERE fk_product = ".((int) $productidselected);
909 $sql .= " AND datem < '".$this->db->idate($datebefore)."'";
910
911 dol_syslog(get_class($this).__METHOD__, LOG_DEBUG);
912 $resql = $this->db->query($sql);
913 if ($resql) {
914 $obj = $this->db->fetch_object($resql);
915 if ($obj) {
916 $nb = $obj->nb;
917 }
918 return (empty($nb) ? 0 : $nb);
919 } else {
920 dol_print_error($this->db);
921 return -1;
922 }
923 }
924
934 private function createBatch($dluo, $qty)
935 {
936 global $user, $langs;
937
938 $langs->load('productbatch');
939
940 $pdluo = new Productbatch($this->db);
941
942 $vbatchnumber = '';
943 $vfk_product_stock = 0;
944 $result = 0;
945
946 // Try to find an existing record with same batch number or id
947 if (is_numeric($dluo)) {
948 $result = $pdluo->fetch($dluo);
949 if (empty($pdluo->id)) {
950 // We didn't find the line. May be it was deleted before by a previous move in same transaction.
951 $this->error = $langs->trans('CantMoveNonExistantSerial');
952 $this->errors[] = $this->error;
953 $result = -2;
954 }
955 } elseif (is_array($dluo)) {
956 if (isset($dluo['fk_product_stock'])) {
957 $vfk_product_stock = $dluo['fk_product_stock'];
958 $vbatchnumber = $dluo['batchnumber'];
959
960 $result = $pdluo->find($vfk_product_stock, 0, 0, $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here)
961 } else {
962 dol_syslog(get_class($this)."::createBatch array param dluo must contain at least key fk_product_stock", LOG_ERR);
963 $result = -1;
964 }
965 } else {
966 dol_syslog(get_class($this)."::createBatch error invalid param dluo", LOG_ERR);
967 $result = -1;
968 }
969
970 if ($result >= 0) {
971 // No error
972 if ($pdluo->id > 0) { // product_batch record found
973 //print "Avant ".$pdluo->qty." Apres ".($pdluo->qty + $qty)."<br>";
974 $pdluo->qty += $qty;
975 if ($pdluo->qty == 0) {
976 $result = $pdluo->delete($user, 1);
977 } else {
978 $result = $pdluo->update($user, 1);
979 }
980 } else { // product_batch record not found
981 $pdluo->fk_product_stock = $vfk_product_stock;
982 $pdluo->qty = $qty;
983 $pdluo->eatby = empty($dluo['eatby']) ? '' : $dluo['eatby']; // No more used. Now eatby date is store in table of lot, no more into prouct_batch table.
984 $pdluo->sellby = empty($dluo['sellby']) ? '' : $dluo['sellby']; // No more used. Now sellby date is store in table of lot, no more into prouct_batch table.
985 $pdluo->batch = $vbatchnumber;
986
987 $result = $pdluo->create($user, 1);
988 if ($result < 0) {
989 $this->error = $pdluo->error;
990 $this->errors = $pdluo->errors;
991 }
992 }
993 }
994
995 return $result;
996 }
997
998 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1006 public function get_origin($origin_id, $origin_type)
1007 {
1008 // phpcs:enable
1009 $origin = '';
1010
1011 switch ($origin_type) {
1012 case 'commande':
1013 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1014 $origin = new Commande($this->db);
1015 break;
1016 case 'shipping':
1017 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1018 $origin = new Expedition($this->db);
1019 break;
1020 case 'facture':
1021 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1022 $origin = new Facture($this->db);
1023 break;
1024 case 'order_supplier':
1025 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1026 $origin = new CommandeFournisseur($this->db);
1027 break;
1028 case 'invoice_supplier':
1029 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1030 $origin = new FactureFournisseur($this->db);
1031 break;
1032 case 'project':
1033 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1034 $origin = new Project($this->db);
1035 break;
1036 case 'mo':
1037 require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
1038 $origin = new Mo($this->db);
1039 break;
1040 case 'user':
1041 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1042 $origin = new User($this->db);
1043 break;
1044 case 'reception':
1045 require_once DOL_DOCUMENT_ROOT.'/reception/class/reception.class.php';
1046 $origin = new Reception($this->db);
1047 break;
1048 case 'inventory':
1049 require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
1050 $origin = new Inventory($this->db);
1051 break;
1052 default:
1053 if ($origin_type) {
1054 // Separate origin_type with "@" : left part is class name, right part is module name
1055 $origin_type_array = explode('@', $origin_type);
1056 $classname = $origin_type_array[0];
1057 $modulename = empty($origin_type_array[1]) ? strtolower($classname) : $origin_type_array[1];
1058
1059 $result = dol_include_once('/'.$modulename.'/class/'.$classname.'.class.php');
1060
1061 if ($result) {
1062 $classname = ucfirst($classname);
1063 $origin = new $classname($this->db);
1064 }
1065 }
1066 break;
1067 }
1068
1069 if (empty($origin) || !is_object($origin)) {
1070 return '';
1071 }
1072
1073 if ($origin->fetch($origin_id) > 0) {
1074 return $origin->getNomUrl(1);
1075 }
1076
1077 return '';
1078 }
1079
1090 public function setOrigin($origin_element, $origin_id, $line_id_object_src = 0, $line_id_object_origin = 0)
1091 {
1092 $this->origin_type = $origin_element;
1093 $this->origin_id = $origin_id;
1094 $this->line_id_object_src = $line_id_object_src;
1095 $this->line_id_object_origin = $line_id_object_origin;
1096 // For backward compatibility
1097 $this->origintype = $origin_element;
1098 $this->fk_origin = $origin_id;
1099 }
1100
1101
1109 public function initAsSpecimen()
1110 {
1111 // Initialize parameters
1112 $this->id = 0;
1113
1114 // There is no specific properties. All data into insert are provided as method parameter.
1115
1116 return 1;
1117 }
1118
1125 public function getTypeMovement($withlabel = 0)
1126 {
1127 global $langs;
1128
1129 $s = '';
1130 switch ($this->type) {
1131 case "0":
1132 $s = '<span class="fa fa-level-down-alt stockmovemententry stockmovementtransfer" title="'.$langs->trans('StockIncreaseAfterCorrectTransfer').'"></span>';
1133 if ($withlabel) {
1134 $s .= $langs->trans('StockIncreaseAfterCorrectTransfer');
1135 }
1136 break;
1137 case "1":
1138 $s = '<span class="fa fa-level-up-alt stockmovementexit stockmovementtransfer" title="'.$langs->trans('StockDecreaseAfterCorrectTransfer').'"></span>';
1139 if ($withlabel) {
1140 $s .= $langs->trans('StockDecreaseAfterCorrectTransfer');
1141 }
1142 break;
1143 case "2":
1144 $s = '<span class="fa fa-long-arrow-alt-up stockmovementexit stockmovement" title="'.$langs->trans('StockDecrease').'"></span>';
1145 if ($withlabel) {
1146 $s .= $langs->trans('StockDecrease');
1147 }
1148 break;
1149 case "3":
1150 $s = '<span class="fa fa-long-arrow-alt-down stockmovemententry stockmovement" title="'.$langs->trans('StockIncrease').'"></span>';
1151 if ($withlabel) {
1152 $s .= $langs->trans('StockIncrease');
1153 }
1154 break;
1155 }
1156
1157 return $s;
1158 }
1159
1171 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
1172 {
1173 global $langs;
1174
1175 $result = '';
1176
1177 $label = img_picto('', 'stock', 'class="pictofixedwidth"').'<u>'.$langs->trans("StockMovement").'</u>';
1178 $label .= '<div width="100%">';
1179 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->id;
1180 $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1181 $qtylabel = (($this->qty > 0) ? '<span class="stockmovemententry">+' : '<span class="stockmovementexit">') . $this->qty . '</span>';
1182 if ($this->inventorycode) {
1183 $label .= '<br><b>'.$langs->trans('InventoryCode').':</b> '.$this->inventorycode;
1184 }
1185 $label .= '<br><b>'.$langs->trans('Qty').':</b> ' . $qtylabel;
1186 if ($this->batch) {
1187 $label .= '<br><b>'.$langs->trans('Batch').':</b> '.$this->batch;
1188 }
1189 /* TODO Get also warehouse label in a property instead of id
1190 if ($this->warehouse_id > 0) {
1191 $label .= '<br><b>'.$langs->trans('Warehouse').':</b> '.$this->warehouse_id;
1192 }*/
1193 $label .= '</div>';
1194
1195 // Link to page of warehouse tab
1196 if ($option == 'movements') {
1197 $url = DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$this->id;
1198 } else {
1199 $url = DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$this->warehouse_id.'&msid='.$this->id;
1200 }
1201
1202 $link = '<a href="'.$url.'"'.($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
1203 $link .= '>';
1204 $linkend = '</a>';
1205
1206 if ($withpicto) {
1207 $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
1208 if ($withpicto != 2) {
1209 $result .= ' ';
1210 }
1211 }
1212 $result .= $link.$this->id.$linkend;
1213 return $result;
1214 }
1215
1222 public function getLibStatut($mode = 0)
1223 {
1224 return $this->LibStatut($mode);
1225 }
1226
1227 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1234 public function LibStatut($mode = 0)
1235 {
1236 // phpcs:enable
1237 global $langs;
1238
1239 if ($mode == 0 || $mode == 1) {
1240 return $langs->trans('StatusNotApplicable');
1241 } elseif ($mode == 2) {
1242 return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1243 } elseif ($mode == 3) {
1244 return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1245 } elseif ($mode == 4) {
1246 return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1247 } elseif ($mode == 5) {
1248 return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1249 }
1250
1251 return 'Bad value for mode';
1252 }
1253
1264 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1265 {
1266 global $langs;
1267
1268 $langs->load("stocks");
1269 $outputlangs->load("products");
1270
1271 if (!dol_strlen($modele)) {
1272 $modele = 'stdmovement';
1273
1274 if ($this->model_pdf) {
1275 $modele = $this->model_pdf;
1276 } elseif (getDolGlobalString('MOUVEMENT_ADDON_PDF')) {
1277 $modele = getDolGlobalString('MOUVEMENT_ADDON_PDF');
1278 }
1279 }
1280
1281 $modelpath = "core/modules/stock/doc/";
1282
1283 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1284 }
1285
1293 public function delete(User $user, $notrigger = 0)
1294 {
1295 return $this->deleteCommon($user, $notrigger);
1296 //return $this->deleteCommon($user, $notrigger, 1);
1297 }
1298
1306 private function getBatchCount($fk_product, $batch)
1307 {
1308 $cpt = 0;
1309
1310 $sql = "SELECT sum(pb.qty) as cpt";
1311 $sql .= " FROM ".$this->db->prefix()."product_batch as pb";
1312 $sql .= " INNER JOIN ".$this->db->prefix()."product_stock as ps ON ps.rowid = pb.fk_product_stock";
1313 $sql .= " WHERE ps.fk_product = " . ((int) $fk_product);
1314 $sql .= " AND pb.batch = '" . $this->db->escape($batch) . "'";
1315
1316 $result = $this->db->query($sql);
1317 if ($result) {
1318 if ($this->db->num_rows($result)) {
1319 $obj = $this->db->fetch_object($result);
1320 $cpt = $obj->cpt;
1321 }
1322
1323 $this->db->free($result);
1324 } else {
1325 dol_print_error($this->db);
1326 return -1;
1327 }
1328
1329 return $cpt;
1330 }
1331
1337 public function reverseMovement()
1338 {
1339 global $user;
1340
1341 $formattedDate = "REVERT-" .($this->inventorycode ? $this->inventorycode : dol_print_date($this->datem, '%Y%m%d%His'));
1342 if ($this->inventorycode == $formattedDate) {
1343 return -1;
1344 }
1345
1346 $newlabel = 'Revert '.$this->label;
1347 // type is 0=input (stock increase by a stock transfer), 1=output (stock decrease by a stock transfer), 2=output (stock decrease), 3=input (stock increase)
1348 // Note that qty should be > 0 with 0 or 3, < 0 with 1 or 2.
1349 if ($this->type == 0) {
1350 $newtype = 1;
1351 } elseif ($this->type == 1) {
1352 $newtype = 0;
1353 } elseif ($this->type == 2) {
1354 $newtype = 3;
1355 } elseif ($this->type == 3) {
1356 $newtype = 2;
1357 } else {
1358 return -1;
1359 }
1360 $newqty = - $this->qty;
1361
1362 $this->db->begin();
1363
1364 $result = $this->_create($user, $this->product_id, $this->warehouse_id, $newqty, $newtype, 0, $newlabel, $formattedDate, '', 0, 0, $this->batch);
1365
1366 if ($result > 0) {
1367 $this->db->commit();
1368 return 1;
1369 } else {
1370 $this->db->rollback();
1371 return -1;
1372 }
1373 }
1374
1383 public function getDateLastMovementProductBatch($fk_entrepot, $fk_product, $batch)
1384 {
1385 $date = '';
1386
1387 $sql = "SELECT MAX(datem) as datem";
1388 $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement";
1389 $sql .= " WHERE fk_product = " . ((int) $fk_product);
1390 $sql .= " AND fk_entrepot = " .((int) $fk_entrepot);
1391 $sql .= " AND batch = '" . $this->db->escape($batch) . "'";
1392
1393 $result = $this->db->query($sql);
1394 if ($result) {
1395 if ($this->db->num_rows($result)) {
1396 $dateObj = $this->db->fetch_object($result);
1397 $date = $dateObj->datem;
1398 }
1399 $this->db->free($result);
1400 } else {
1401 dol_print_error($this->db);
1402 return $date;
1403 }
1404
1405 return $date;
1406 }
1407}
Class to manage predefined suppliers products.
Class to manage customers orders.
Parent class of all other business classes (invoices, contracts, proposals, orders,...
fetch_optionals($rowid=null, $optionsArray=null)
Function to get extra fields of an object into $this->array_options This method is in most cases call...
commonGenerateDocument($modelspath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams=null)
Common function for all objects extending CommonObject for generating documents.
errorsToString()
Method to output saved errors.
deleteCommon(User $user, $notrigger=0, $forcechilddeletion=0)
Delete object in database.
call_trigger($triggerName, $user)
Call trigger based on this instance.
Class to manage warehouses.
Class to manage suppliers invoices.
Class to manage invoices.
Class for Inventory.
Class for Mo.
Definition mo.class.php:35
Class to manage stock movements.
__construct($db)
Constructor.
generateDocument($modele, $outputlangs, $hidedetails=0, $hidedesc=0, $hideref=0)
Create object on disk.
getNomUrl($withpicto=0, $option='', $notooltip=0, $maxlen=24, $morecss='')
Return a link (with optionally the picto) Use this->id,this->lastname, this->firstname.
setOrigin($origin_element, $origin_id, $line_id_object_src=0, $line_id_object_origin=0)
Set attribute origin_type and fk_origin to object.
_create($user, $fk_product, $entrepot_id, $qty, $type, $price=0, $label='', $inventorycode='', $datem='', $eatby=0, $sellby=0, $batch='', $skip_batch=false, $id_product_batch=0, $disablestockchangeforsubproduct=0, $donotcleanemptylines=0, $force_update_batch=false)
Add a movement of stock (in one direction only).
LibStatut($mode=0)
Return the label of the status.
createBatch($dluo, $qty)
Create or update batch record (update table llx_product_batch).
reception($user, $fk_product, $entrepot_id, $qty, $price=0, $label='', $eatby='', $sellby='', $batch='', $datem='', $id_product_batch=0, $inventorycode='', $donotcleanemptylines=0, $disablestockchangeforsubproduct=0)
Increase stock for product and subproducts.
getBatchCount($fk_product, $batch)
Retrieve number of equipment for a product lot/serial.
get_origin($origin_id, $origin_type)
Return Url link of origin object.
livraison($user, $fk_product, $entrepot_id, $qty, $price=0, $label='', $datem='', $eatby='', $sellby='', $batch='', $id_product_batch=0, $inventorycode='', $donotcleanemptylines=0)
Decrease stock for product and subproducts.
fetch($id)
Load object in memory from the database.
_createSubProduct($user, $idProduct, $entrepot_id, $qty, $type, $price=0, $label='', $inventorycode='', $datem='')
Create movement in database for all subproducts.
initAsSpecimen()
Initialise an instance with random values.
getDateLastMovementProductBatch($fk_entrepot, $fk_product, $batch)
Retrieve date of last stock movement for.
getTypeMovement($withlabel=0)
Return html string with picto for type of movement.
reverseMovement()
Reverse movement for object by updating infos.
calculateBalanceForProductBefore($productidselected, $datebefore)
Count number of product in stock before a specific date.
getLibStatut($mode=0)
Return label statut.
Class to manage products or services.
const DISABLED_STOCK
Stockable product.
const TYPE_SERVICE
Service.
Manage record for batch number management.
Class with list of lots and properties.
Class to manage projects.
Class to manage receptions.
Class to manage Dolibarr users.
dol_mktime($hour, $minute, $second, $month, $day, $year, $gm='auto', $check=1)
Return a timestamp date built from detailed information (by default a local PHP server timestamp) Rep...
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
if(!function_exists( 'dol_getprefix')) dol_include_once($relpath, $classname='')
Make an include_once using default root and alternate root if it fails.
dol_clone($object, $native=2)
Create a clone of instance of object (new instance with same value for each properties) With native =...
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_getdate($timestamp, $fast=false, $forcetimezone='')
Return an array with locale date info.
global $conf
The following vars must be defined: $type2label $form $conf, $lang, The following vars may also be de...
Definition member.php:79
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:158