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