dolibarr 25.0.0-alpha
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 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 3 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program. If not, see <https://www.gnu.org/licenses/>.
22 */
23
35{
39 public $element = 'stockmouvement';
40
44 public $table_element = 'stock_mouvement';
45
46
50 public $product_id;
51
57 public $entrepot_id;
58
62 public $warehouse_id;
63
67 public $qty;
68
77 public $type;
78
82 public $datem = '';
86 public $price;
87
91 public $fk_user_author;
92
96 public $label;
97
103 public $fk_origin;
104
108 public $origin_id;
109
115 public $origintype;
116
120 public $origin_type;
124 public $line_id_oject_src;
128 public $line_id_oject_origin;
129
135 public $inventorycode;
136
140 public $movementcode;
141
145 public $batch;
146
150 public $line_id_object_src;
154 public $line_id_object_origin;
155
159 public $eatby;
160
164 public $sellby;
165
166
167
168 public $fields = array(
169 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10, 'showoncombobox' => 1),
170 'tms' => array('type' => 'timestamp', 'label' => 'DateModification', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 15),
171 'datem' => array('type' => 'datetime', 'label' => 'Datem', 'enabled' => 1, 'visible' => -1, 'position' => 20),
172 'fk_product' => array('type' => 'integer:Product:product/class/product.class.php:1', 'label' => 'Product', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 25),
173 'fk_entrepot' => array('type' => 'integer:Entrepot:product/stock/class/entrepot.class.php', 'label' => 'Warehouse', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 30),
174 'value' => array('type' => 'double', 'label' => 'Value', 'enabled' => 1, 'visible' => -1, 'position' => 35),
175 'price' => array('type' => 'double(24,8)', 'label' => 'Price', 'enabled' => 1, 'visible' => -1, 'position' => 40),
176 'type_mouvement' => array('type' => 'smallint(6)', 'label' => 'Type mouvement', 'enabled' => 1, 'visible' => -1, 'position' => 45),
177 'fk_user_author' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserAuthor', 'enabled' => 1, 'visible' => -1, 'position' => 50),
178 'label' => array('type' => 'varchar(255)', 'label' => 'Label', 'enabled' => 1, 'visible' => -1, 'position' => 55),
179 'fk_origin' => array('type' => 'integer', 'label' => 'Origin', 'enabled' => 1, 'visible' => -1, 'position' => 60),
180 'origintype' => array('type' => 'varchar(32)', 'label' => 'Origintype', 'enabled' => 1, 'visible' => -1, 'position' => 65),
181 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 70),
182 '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),
183 'inventorycode' => array('type' => 'varchar(128)', 'label' => 'InventoryCode', 'enabled' => 1, 'visible' => -1, 'position' => 80),
184 'batch' => array('type' => 'varchar(30)', 'label' => 'Batch', 'enabled' => 1, 'visible' => -1, 'position' => 85),
185 'eatby' => array('type' => 'date', 'label' => 'Eatby', 'enabled' => 1, 'visible' => -1, 'position' => 90),
186 'sellby' => array('type' => 'date', 'label' => 'Sellby', 'enabled' => 1, 'visible' => -1, 'position' => 95),
187 'fk_project' => array('type' => 'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label' => 'Project', 'enabled' => 1, 'visible' => -1, 'position' => 100),
188 );
189
190
191
197 public function __construct($db)
198 {
199 $this->db = $db;
200 }
201
202 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
230 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)
231 {
232 // phpcs:enable
233 global $conf, $langs;
234
235 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
236 require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
237
238 $error = 0;
239 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));
240
241 // Call hook at beginning
242 global $action, $hookmanager;
243 $hookmanager->initHooks(array('mouvementstock'));
244
245 if (is_object($hookmanager)) {
246 $parameters = array(
247 'currentcontext' => 'mouvementstock',
248 'user' => &$user,
249 'fk_product' => &$fk_product,
250 'entrepot_id' => &$entrepot_id,
251 'qty' => &$qty,
252 'type' => &$type,
253 'price' => &$price,
254 'label' => &$label,
255 'inventorycode' => &$inventorycode,
256 'datem' => &$datem,
257 'eatby' => &$eatby,
258 'sellby' => &$sellby,
259 'batch' => &$batch,
260 'skip_batch' => &$skip_batch,
261 'id_product_batch' => &$id_product_batch
262 );
263 $reshook = $hookmanager->executeHooks('stockMovementCreate', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
264
265 if ($reshook < 0) {
266 if (!empty($hookmanager->resPrint)) {
267 dol_print_error(null, $hookmanager->resPrint);
268 }
269 return $reshook;
270 } elseif ($reshook > 0) {
271 return $reshook;
272 }
273 }
274 // end hook at beginning
275
276 // Clean parameters
277 $price = price2num($price, 'MU'); // Clean value for the casse we receive a float zero value, to have it a real zero value.
278 if (empty($price)) {
279 $price = 0;
280 }
281 $now = (!empty($datem) ? $datem : dol_now());
282
283 //print "livraison fk_product=".$fk_product." entrepot_id=".$entrepot_id; exit;
284
285 // Check parameters
286 if (!($fk_product > 0)) {
287 return 0;
288 }
289 if (!($entrepot_id > 0)) {
290 return 0;
291 }
292
293 if (is_numeric($eatby) && $eatby < 0) {
294 dol_syslog(get_class($this)."::_create start ErrorBadValueForParameterEatBy eatby = ".$eatby);
295 $this->errors[] = 'ErrorBadValueForParameterEatBy';
296 return -1;
297 }
298 if (is_numeric($sellby) && $sellby < 0) {
299 dol_syslog(get_class($this)."::_create start ErrorBadValueForParameterSellBy sellby = ".$sellby);
300 $this->errors[] = 'ErrorBadValueForParameterSellBy';
301 return -1;
302 }
303
304 // Set properties of movement
305 $this->product_id = $fk_product;
306 $this->entrepot_id = $entrepot_id; // deprecated
307 $this->warehouse_id = $entrepot_id;
308 $this->qty = $qty;
309 $this->type = $type;
310 $this->price = price2num($price);
311 $this->label = $label;
312 $this->inventorycode = $inventorycode;
313 $this->datem = $now;
314 $this->batch = $batch;
315
316 $mvid = 0;
317
318 $product = new Product($this->db);
319
320 $result = $product->fetch($fk_product);
321 if ($result < 0) {
322 $this->setErrorsFromObject($product);
323 dol_print_error(null, "Failed to fetch product");
324 return -1;
325 }
326 if ($product->id <= 0) { // Can happen if database is corrupted (a product id exist in stock with product that has been removed)
327 return 0;
328 }
329
330 // Define if we must make the stock change (If product type is a service or if stock is used also for services)
331 // Only record into stock tables will be disabled by this (the rest like writing into lot table or movement of subproucts are done)
332 $movestock = 0;
333 $productChildrenNb = 0;
334 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
335 $productChildrenNb = $product->hasFatherOrChild(1);
336 }
337
338 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.
339 $movestock = 1;
340 }
341
342 $this->db->begin();
343
344 // Set value $product->stock_reel and detail per warehouse into $product->stock_warehouse array
345 if ($movestock) {
346 $product->load_stock('novirtual');
347 }
348
349 // Test if product require batch data. If yes, and there is not or values are not correct, we throw an error.
350 if (isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
351 if (empty($batch)) {
352 $langs->load("errors");
353 $this->errors[] = $langs->transnoentitiesnoconv("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref);
354 dol_syslog("Try to make a movement of a product with status_batch on without any batch data", LOG_ERR);
355
356 $this->db->rollback();
357 return -2;
358 }
359
360 // An outgoing movement (qty < 0) takes the eat-by/sell-by dates of the lot as they are now: the dates given by
361 // the caller (often a copy kept on the line of a reception or shipment, so maybe outdated since the dates were
362 // corrected on the lot) must not block the movement nor be saved into the lot.
363 if ($qty < 0) {
364 $eatby = '';
365 $sellby = '';
366 }
367
368 // Check table llx_product_lot from batchnumber for same product
369 // If found and eatby/sellby defined into table and provided and differs, return error
370 // If found and eatby/sellby defined into table and not provided, we take value from table
371 // If found and eatby/sellby not defined into table and provided, we update table
372 // If found and eatby/sellby not defined into table and not provided, we do nothing
373 // If not found, we add record
374 $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".$this->db->prefix()."product_lot as pb";
375 $sql .= " WHERE pb.fk_product = ".((int) $fk_product)." AND pb.batch = '".$this->db->escape($batch)."'";
376
377 dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
378
379 $resql = $this->db->query($sql);
380 if ($resql) {
381 $num = $this->db->num_rows($resql);
382 $i = 0;
383 if ($num > 0) {
384 while ($i < $num && $obj = $this->db->fetch_object($resql)) {
385 if ($obj->eatby) {
386 if ($eatby) {
387 $tmparray = dol_getdate((int) $eatby, true);
388 $eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
389 if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) { // We test date without hours and with hours for backward compatibility
390 // If found and eatby/sellby defined into table and provided and differs, return error
391 $langs->load("stocks");
392 $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatbywithouthour, 'dayhour'));
393 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);
394 $this->db->rollback();
395 return -3;
396 }
397 } else {
398 $eatby = $obj->eatby; // If found and eatby/sellby defined into table and not provided, we take value from table
399 }
400 } else {
401 if ($eatby) { // If found and eatby/sellby not defined into table and provided, we update table
402 $productlot = new Productlot($this->db);
403 $result = $productlot->fetch($obj->rowid);
404 $productlot->eatby = $eatby;
405 $result = $productlot->update($user);
406 if ($result <= 0) {
407 $this->setErrorsFromObject($productlot);
408 $this->db->rollback();
409 return -5;
410 }
411 }
412 }
413 if ($obj->sellby) {
414 if ($sellby) {
415 $tmparray = dol_getdate((int) $sellby, true);
416 $sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
417 if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) { // We test date without hours and with hours for backward compatibility
418 // If found and eatby/sellby defined into table and provided and differs, return error
419 $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
420 dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
421 $this->db->rollback();
422 return -3;
423 }
424 } else {
425 $sellby = $obj->sellby; // If found and eatby/sellby defined into table and not provided, we take value from table
426 }
427 } else {
428 if ($sellby) { // If found and eatby/sellby not defined into table and provided, we update table
429 $productlot = new Productlot($this->db);
430 $result = $productlot->fetch($obj->rowid);
431 $productlot->sellby = $sellby;
432 $result = $productlot->update($user);
433 if ($result <= 0) {
434 $this->setErrorsFromObject($productlot);
435 $this->db->rollback();
436 return -5;
437 }
438 }
439 }
440
441 $i++;
442 }
443 } else { // If not found, we add record
444 $productlot = new Productlot($this->db);
445 $productlot->origin_type = !empty($this->origin_type) ? $this->origin_type : '';
446 $productlot->origin_id = !empty($this->origin_id) ? $this->origin_id : 0;
447 $productlot->entity = $conf->entity;
448 $productlot->fk_product = $fk_product;
449 $productlot->batch = $batch;
450 // If we are here = first time we manage this batch, so we used dates provided by users to create lot
451 $productlot->eatby = $eatby;
452 $productlot->sellby = $sellby;
453 $result = $productlot->create($user);
454 if ($result <= 0) {
455 $this->setErrorsFromObject($productlot);
456 $this->db->rollback();
457 return -4;
458 }
459 }
460 } else {
461 dol_print_error($this->db);
462 $this->db->rollback();
463 return -1;
464 }
465 }
466
467 // Check if stock is enough when qty is < 0.
468 // THIS MUST BE DONE AT END OF MOVEMENTS
469 // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2.
470 if ($movestock && $qty < 0 && getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER')) {
471 if (isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
472 $foundforbatch = 0;
473 $qtyisnotenough = 0;
474 if (isset($product->stock_warehouse[$entrepot_id])) {
475 foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) {
476 // Lot '59' must be different than lot '59c' and also '0123' must be different than '123'
477 if ((string) $batch !== (string) $batchcursor) {
478 continue;
479 }
480
481 $foundforbatch = 1;
482 if ($prodbatch->qty < abs($qty)) {
483 $qtyisnotenough = $prodbatch->qty;
484 }
485 break;
486 }
487 }
488 if (!$foundforbatch || $qtyisnotenough) {
489 $langs->load("stocks");
490 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
491 $tmpwarehouse = new Entrepot($this->db);
492 $tmpwarehouse->fetch($entrepot_id);
493
494 $this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, (string) $batch, $qtyisnotenough, $tmpwarehouse->ref);
495 $this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, (string) $batch, $qtyisnotenough, $tmpwarehouse->ref);
496 $this->db->rollback();
497 return -8;
498 }
499 } else {
500 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))) {
501 $langs->load("stocks");
502 $this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
503 $this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
504 $this->db->rollback();
505 return -8;
506 }
507 }
508 }
509
510 if ($movestock && $product->stockable_product == Product::ENABLED_STOCK) { // Change stock for current product, change for subproduct is done after
511 // Set $origin_type, origin_id and fk_project
512 $fk_project = $this->fk_project;
513 if (!empty($this->origin_type)) { // This is set by caller for tracking reason
514 $origin_type = $this->origin_type;
515 $origin_id = $this->origin_id;
516 if (empty($fk_project) && $origin_type == 'project') {
517 $fk_project = $origin_id;
518 $origin_type = '';
519 $origin_id = 0;
520 }
521 } else {
522 $fk_project = 0;
523 $origin_type = '';
524 $origin_id = 0;
525 }
526
527 // llx_stock_mouvement.label is VARCHAR(255)
528 $label = dol_trunc((string) $label, 255, 'right', 'UTF-8', 1);
529
530 $sql = "INSERT INTO ".$this->db->prefix()."stock_mouvement(";
531 $sql .= " datem, fk_product, batch, eatby, sellby,";
532 $sql .= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet";
533 $sql .= ")";
534 $sql .= " VALUES ('".$this->db->idate($this->datem)."', ".((int) $this->product_id).", ";
535 $sql .= " ".(isset($batch) ? "'".$this->db->escape($batch)."'" : "null").", ";
536 $sql .= " ".($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ";
537 $sql .= " ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ";
538 $sql .= " ".((int) $this->entrepot_id).", ".((float) $this->qty).", ".((int) $this->type).",";
539 $sql .= " ".((int) $user->id).",";
540 $sql .= " '".$this->db->escape($label)."',";
541 $sql .= " ".($inventorycode ? "'".$this->db->escape($inventorycode)."'" : "null").",";
542 $sql .= " ".((float) price2num($price)).",";
543 $sql .= " ".((int) $origin_id).",";
544 $sql .= " '".$this->db->escape($origin_type)."',";
545 $sql .= " ".((int) $fk_project);
546 $sql .= ")";
547
548 dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG);
549 $resql = $this->db->query($sql);
550
551 if ($resql) {
552 $mvid = $this->db->last_insert_id($this->db->prefix()."stock_mouvement");
553 $this->id = $mvid;
554 } else {
555 $this->error = $this->db->lasterror();
556 $this->errors[] = $this->error;
557 $error = -1;
558 }
559
560 // Define current values for qty and pmp
561 $oldqty = $product->stock_reel;
562 $oldpmp = $product->pmp;
563 $oldqtywarehouse = 0;
564
565 // Test if there is already a record for couple (warehouse / product), so later we will make an update or create.
566 $alreadyarecord = 0;
567 $fk_product_stock = 0;
568 if (!$error) {
569 $sql = "SELECT rowid, reel FROM ".$this->db->prefix()."product_stock";
570 $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product); // This is a unique key
571
572 dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG);
573 $resql = $this->db->query($sql);
574 if ($resql) {
575 $obj = $this->db->fetch_object($resql);
576 if ($obj) {
577 $alreadyarecord = 1;
578 $oldqtywarehouse = $obj->reel;
579 $fk_product_stock = $obj->rowid;
580 }
581 $this->db->free($resql);
582 } else {
583 $this->errors[] = $this->db->lasterror();
584 $error = -2;
585 }
586 }
587
588 // Calculate new AWP (PMP)
589 $newpmp = 0;
590 if (!$error) {
591 if ($type == 0 || $type == 3) {
592 // After a stock increase
593 // Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0.
594 // Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input)
595 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')))) {
596 $oldqtytouse = ($oldqty >= 0 ? $oldqty : 0);
597 // We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined
598 if ($oldpmp > 0 && ($oldqtytouse + $qty) != 0) {
599 $newpmp = price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU');
600 } else {
601 $newpmp = $price; // For this product, PMP was not yet set. We set it to input price.
602 }
603 //print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." ";
604 //print "qty=".$qty." newpmp=".$newpmp;
605 //exit;
606 } else {
607 $newpmp = $oldpmp;
608 }
609 } else {
610 // ($type == 1 || $type == 2)
611 // -> After a stock decrease, we don't change value of the AWP/PMP of a product.
612 // else
613 // Type of movement unknown
614 $newpmp = $oldpmp;
615 }
616 }
617 // Update stock quantity
618 if (!$error) {
619 if ($alreadyarecord > 0) {
620 $sql = "UPDATE ".$this->db->prefix()."product_stock SET reel = " . ((float) $oldqtywarehouse + (float) $qty);
621 $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product);
622 } else {
623 $sql = "INSERT INTO ".$this->db->prefix()."product_stock";
624 $sql .= " (reel, fk_entrepot, fk_product) VALUES ";
625 $sql .= " (".((float) $qty).", ".((int) $entrepot_id).", ".((int) $fk_product).")";
626 }
627
628 dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG);
629 $resql = $this->db->query($sql);
630 if (!$resql) {
631 $this->errors[] = $this->db->lasterror();
632 $error = -3;
633 } elseif (empty($fk_product_stock)) {
634 $fk_product_stock = $this->db->last_insert_id($this->db->prefix()."product_stock");
635 }
636 }
637
638 // Update detail of stock for the lot.
639 if (!$error && isModEnabled('productbatch') && (($product->hasbatch() && !$skip_batch) || $force_update_batch)) {
640 if ($id_product_batch > 0) {
641 $result = $this->createBatch($id_product_batch, $qty);
642 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
643 $param_batch = array('fk_product_stock' => $fk_product_stock, 'batchnumber' => (string) $batch);
644 $result = $this->createBatch($param_batch, $qty);
645 }
646 } else {
647 $param_batch = array('fk_product_stock' => $fk_product_stock, 'batchnumber' => (string) $batch);
648 $result = $this->createBatch($param_batch, $qty);
649 }
650 if ($result < 0) {
651 $error++;
652 }
653 }
654
655 // Update PMP and denormalized value of stock qty at product level
656 if (!$error) {
657 $newpmp = price2num($newpmp, 'MU');
658
659 // $sql = "UPDATE ".$this->db->prefix()."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty;
660 // $sql.= " WHERE rowid = ".((int) $fk_product);
661 // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
662 $sql = "UPDATE ".$this->db->prefix()."product as p SET pmp = ".((float) $newpmp).",";
663 $sql .= " stock=(SELECT SUM(ps.reel) FROM ".$this->db->prefix()."product_stock as ps WHERE ps.fk_product = p.rowid)";
664 $sql .= " WHERE rowid = ".((int) $fk_product);
665
666 dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG);
667 $resql = $this->db->query($sql);
668 if (!$resql) {
669 $this->errors[] = $this->db->lasterror();
670 $error = -4;
671 }
672 }
673
674 if (empty($donotcleanemptylines)) {
675 // 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
676 // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
677 $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)";
678 $resql = $this->db->query($sql);
679 // The NOT IN clause already excludes rows still referenced by product_batch (the only child FK on
680 // product_stock), so this DELETE cannot fail on a child constraint. Any failure is therefore a real
681 // error, in particular a deadlock (1213) that rolls back the whole transaction including the movement
682 // just inserted; if we swallowed it, _create() would commit an empty transaction and return the
683 // movement id as a success, so the caller (and the REST API) would think the movement was saved while
684 // it was lost.
685 if (!$resql) {
686 $this->errors[] = $this->db->lasterror();
687 $error++;
688 }
689 }
690 }
691
692 // Add movement for sub products (recursive call)
693 if (!$error && getDolGlobalString('PRODUIT_SOUSPRODUITS') && !getDolGlobalString('PRODUIT_SOUSPRODUITS_ALWAYS_DISABLE_CHILDREN_STOCK_MOVE') && empty($disablestockchangeforsubproduct)) {
694 $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
695 }
696
697 if ($movestock && !$error) {
698 // Call trigger
699 if ($product->stockable_product != Product::DISABLED_STOCK ) {
700 $result = $this->call_trigger('STOCK_MOVEMENT', $user);
701 if ($result < 0) {
702 $error++;
703 }
704 }
705 // End call triggers
706 // Check unicity for serial numbered equipment once all movement were done.
707 if (!$error && isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
708 if ($product->status_batch == 2 && $qty > 0) { // We check only if we increased qty
709 if ($this->getBatchCount($fk_product, (string) $batch) > 1) {
710 $error++;
711 $this->errors[] = $langs->trans("TooManyQtyForSerialNumber", $product->ref, (string) $batch);
712 }
713 }
714 }
715 }
716
717 if (!$error) {
718 $this->db->commit();
719 return $mvid;
720 } else {
721 $this->db->rollback();
722 dol_syslog(get_class($this)."::_create error code=".$error, LOG_ERR);
723 return -6;
724 }
725 }
726
727
728
736 public function fetch($id)
737 {
738 dol_syslog(__METHOD__, LOG_DEBUG);
739
740 $sql = "SELECT";
741 $sql .= " t.rowid,";
742 $sql .= " t.tms,";
743 $sql .= " t.datem,";
744 $sql .= " t.fk_product,";
745 $sql .= " t.fk_entrepot,";
746 $sql .= " t.value,";
747 $sql .= " t.price,";
748 $sql .= " t.type_mouvement,";
749 $sql .= " t.fk_user_author,";
750 $sql .= " t.label,";
751 $sql .= " t.fk_origin as origin_id,";
752 $sql .= " t.origintype as origin_type,";
753 $sql .= " t.inventorycode as movementcode,";
754 $sql .= " t.batch,";
755 $sql .= " t.eatby,";
756 $sql .= " t.sellby,";
757 $sql .= " t.fk_projet as fk_project";
758 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
759 $sql .= " WHERE t.rowid = ".((int) $id);
760
761 $resql = $this->db->query($sql);
762 if ($resql) {
763 $numrows = $this->db->num_rows($resql);
764 if ($numrows) {
765 $obj = $this->db->fetch_object($resql);
766
767 $this->id = $obj->rowid;
768
769 $this->product_id = $obj->fk_product;
770 $this->warehouse_id = $obj->fk_entrepot;
771 $this->qty = $obj->value;
772 $this->type = $obj->type_mouvement;
773
774 $this->tms = $this->db->jdate($obj->tms);
775 $this->datem = $this->db->jdate($obj->datem);
776 $this->price = $obj->price;
777 $this->fk_user_author = $obj->fk_user_author;
778 $this->label = $obj->label;
779 $this->fk_origin = $obj->origin_id; // For backward compatibility
780 $this->origintype = $obj->origin_type; // For backward compatibility
781 $this->origin_id = $obj->origin_id;
782 $this->origin_type = $obj->origin_type;
783 $this->inventorycode = $obj->movementcode; // For backward compatibility
784 $this->movementcode = $obj->movementcode;
785 $this->batch = $obj->batch;
786 $this->eatby = $this->db->jdate($obj->eatby);
787 $this->sellby = $this->db->jdate($obj->sellby);
788 $this->fk_project = $obj->fk_project;
789 }
790
791 // Retrieve all extrafield
792 $this->fetch_optionals();
793
794 // $this->fetch_lines();
795
796 $this->db->free($resql);
797
798 if ($numrows) {
799 return 1;
800 } else {
801 return 0;
802 }
803 } else {
804 $this->errors[] = 'Error '.$this->db->lasterror();
805 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
806
807 return -1;
808 }
809 }
810
811
812
813
828 private function _createSubProduct($user, $idProduct, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '')
829 {
830 global $langs;
831
832 $error = 0;
833
834 $sql = "SELECT fk_product_pere, fk_product_fils, qty";
835 $sql .= " FROM ".$this->db->prefix()."product_association";
836 $sql .= " WHERE fk_product_pere = ".((int) $idProduct);
837 $sql .= " AND incdec = 1";
838
839 dol_syslog(__METHOD__.' for parent product '.$idProduct, LOG_DEBUG);
840 $resql = $this->db->query($sql);
841 if ($resql) {
842 // Create movement for each sub-product
843 while ($obj = $this->db->fetch_object($resql)) {
844 $tmpmove = dol_clone($this, 1);
845 $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
846 if ($result < 0) {
847 $this->error = $tmpmove->error;
848 $this->errors = array_merge($this->errors, $tmpmove->errors);
849 if ($result == -2) {
850 $this->errors[] = $langs->trans('ErrorNoteAlsoThatSubProductCantBeFollowedByLot');
851 }
852 $error = $result;
853 dol_syslog(__METHOD__ . ' Error : ' . $this->errorsToString(), LOG_ERR);
854 break;
855 }
856 unset($tmpmove);
857 }
858
859 $this->db->free($resql);
860 } else {
861 $error = -2;
862 }
863
864 return $error;
865 }
866
867
886 public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '', $donotcleanemptylines = 0)
887 {
888 $skip_batch = !isModEnabled('productbatch');
889
890 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);
891 }
892
912 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)
913 {
914 $skip_batch = !isModEnabled('productbatch');
915
916 return $this->_create($user, $fk_product, $entrepot_id, $qty, 3, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch, $disablestockchangeforsubproduct, $donotcleanemptylines);
917 }
918
926 public function calculateBalanceForProductBefore($productidselected, $datebefore)
927 {
928 $nb = 0;
929
930 $sql = "SELECT SUM(value) as nb from ".$this->db->prefix()."stock_mouvement";
931 $sql .= " WHERE fk_product = ".((int) $productidselected);
932 $sql .= " AND datem < '".$this->db->idate($datebefore)."'";
933
934 dol_syslog(get_class($this).__METHOD__, LOG_DEBUG);
935 $resql = $this->db->query($sql);
936 if ($resql) {
937 $obj = $this->db->fetch_object($resql);
938 if ($obj) {
939 $nb = (float) $obj->nb;
940 }
941 return (empty($nb) ? 0 : $nb);
942 } else {
943 dol_print_error($this->db);
944 return -1;
945 }
946 }
947
957 private function createBatch($dluo, $qty)
958 {
959 global $user, $langs;
960
961 $langs->load('productbatch');
962
963 $pdluo = new Productbatch($this->db);
964
965 $vbatchnumber = '';
966 $vfk_product_stock = 0;
967 $result = 0;
968
969 // Try to find an existing record with same batch number or id
970 if (is_numeric($dluo)) {
971 $result = $pdluo->fetch($dluo);
972 if (empty($pdluo->id)) {
973 // We didn't find the line. May be it was deleted before by a previous move in same transaction.
974 $this->error = $langs->trans('CantMoveNonExistantSerial');
975 $this->errors[] = $this->error;
976 $result = -2;
977 }
978 } elseif (is_array($dluo)) {
979 if (isset($dluo['fk_product_stock'])) {
980 $vfk_product_stock = $dluo['fk_product_stock'];
981 $vbatchnumber = $dluo['batchnumber'];
982
983 $result = $pdluo->find($vfk_product_stock, 0, 0, $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here)
984 } else {
985 dol_syslog(get_class($this)."::createBatch array param dluo must contain at least key fk_product_stock", LOG_ERR);
986 $result = -1;
987 }
988 } else {
989 dol_syslog(get_class($this)."::createBatch error invalid param dluo", LOG_ERR);
990 $result = -1;
991 }
992
993 if ($result >= 0) {
994 // No error
995 if ($pdluo->id > 0) { // product_batch record found
996 //print "Avant ".$pdluo->qty." Apres ".($pdluo->qty + $qty)."<br>";
997 $pdluo->qty += $qty;
998 if ($pdluo->qty == 0) {
999 $result = $pdluo->delete($user, 1);
1000 } else {
1001 $result = $pdluo->update($user, 1);
1002 }
1003 } else { // product_batch record not found
1004 $pdluo->fk_product_stock = $vfk_product_stock;
1005 $pdluo->qty = $qty;
1006 $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.
1007 $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.
1008 $pdluo->batch = $vbatchnumber;
1009
1010 $result = $pdluo->create($user, 1);
1011 if ($result < 0) {
1012 $this->setErrorsFromObject($pdluo);
1013 }
1014 }
1015 }
1016
1017 return $result;
1018 }
1019
1020 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1028 public function get_origin($origin_id, $origin_type)
1029 {
1030 // phpcs:enable
1031 $origin = '';
1032
1033 switch ($origin_type) {
1034 case 'commande':
1035 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1036 $origin = new Commande($this->db);
1037 break;
1038 case 'shipping':
1039 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1040 $origin = new Expedition($this->db);
1041 break;
1042 case 'facture':
1043 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1044 $origin = new Facture($this->db);
1045 break;
1046 case 'order_supplier':
1047 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1048 $origin = new CommandeFournisseur($this->db);
1049 break;
1050 case 'invoice_supplier':
1051 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1052 $origin = new FactureFournisseur($this->db);
1053 break;
1054 case 'project':
1055 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1056 $origin = new Project($this->db);
1057 break;
1058 case 'mo':
1059 require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
1060 $origin = new Mo($this->db);
1061 break;
1062 case 'user':
1063 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1064 $origin = new User($this->db);
1065 break;
1066 case 'reception':
1067 require_once DOL_DOCUMENT_ROOT.'/reception/class/reception.class.php';
1068 $origin = new Reception($this->db);
1069 break;
1070 case 'inventory':
1071 require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
1072 $origin = new Inventory($this->db);
1073 break;
1074 default:
1075 if ($origin_type) {
1076 // Separate origin_type with "@" : left part is class name, right part is module name
1077 $origin_type_array = explode('@', $origin_type);
1078 $classname = $origin_type_array[0];
1079 $modulename = empty($origin_type_array[1]) ? strtolower($classname) : $origin_type_array[1];
1080
1081 // Dolibarr names its class files in lowercase, so use a lowercase file name whatever
1082 // the case of the class name (class names themselves are case insensitive in PHP).
1083 $result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php');
1084
1085 if ($result) {
1086 $classname = ucfirst($classname);
1087 $origin = new $classname($this->db);
1088 }
1089 }
1090 break;
1091 }
1092
1093 if (empty($origin) || !is_object($origin)) {
1094 return '';
1095 }
1096
1097 if ($origin->fetch($origin_id) > 0) {
1098 return $origin->getNomUrl(1);
1099 }
1100
1101 return '';
1102 }
1103
1114 public function setOrigin($origin_element, $origin_id, $line_id_object_src = 0, $line_id_object_origin = 0)
1115 {
1116 $this->origin_type = $origin_element;
1117 $this->origin_id = $origin_id;
1118 $this->line_id_object_src = $line_id_object_src;
1119 $this->line_id_object_origin = $line_id_object_origin;
1120 // For backward compatibility
1121 $this->origintype = $origin_element;
1122 $this->fk_origin = $origin_id;
1123 }
1124
1125
1133 public function initAsSpecimen()
1134 {
1135 // Initialize parameters
1136 $this->id = 0;
1137
1138 // There is no specific properties. All data into insert are provided as method parameter.
1139
1140 return 1;
1141 }
1142
1149 public function getTypeMovement($withlabel = 0)
1150 {
1151 global $langs;
1152
1153 $s = '';
1154 switch ($this->type) {
1155 case "0":
1156 $s = '<span class="invertforbadge"><span class="fa fa-level-down-alt stockmovemententry stockmovementtransfer" title="'.$langs->trans('StockIncreaseAfterCorrectTransfer').'"></span></span>';
1157 if ($withlabel) {
1158 $s .= $langs->trans('StockIncreaseAfterCorrectTransfer');
1159 }
1160 break;
1161 case "1":
1162 $s = '<span class="invertforbadge"><span class="fa fa-level-up-alt stockmovementexit stockmovementtransfer" title="'.$langs->trans('StockDecreaseAfterCorrectTransfer').'"></span></span>';
1163 if ($withlabel) {
1164 $s .= $langs->trans('StockDecreaseAfterCorrectTransfer');
1165 }
1166 break;
1167 case "2":
1168 $s = '<span class="invertforbadge"><span class="fa fa-long-arrow-alt-up stockmovementexit stockmovement" title="'.$langs->trans('StockDecrease').'"></span></span>';
1169 if ($withlabel) {
1170 $s .= $langs->trans('StockDecrease');
1171 }
1172 break;
1173 case "3":
1174 $s = '<span class="invertforbadge"><span class="fa fa-long-arrow-alt-down stockmovemententry stockmovement" title="'.$langs->trans('StockIncrease').'"></span></span>';
1175 if ($withlabel) {
1176 $s .= $langs->trans('StockIncrease');
1177 }
1178 break;
1179 }
1180
1181 return $s;
1182 }
1183
1195 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
1196 {
1197 global $langs;
1198
1199 $result = '';
1200
1201 $label = img_picto('', 'stock', 'class="pictofixedwidth"').'<u>'.$langs->trans("StockMovement").'</u>';
1202 $label .= '<div width="100%">';
1203 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->id;
1204 $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1205 $qtylabel = (($this->qty > 0) ? '<span class="stockmovemententry">+' : '<span class="stockmovementexit">') . $this->qty . '</span>';
1206 if ($this->inventorycode) {
1207 $label .= '<br><b>'.$langs->trans('InventoryCode').':</b> '.$this->inventorycode;
1208 }
1209 $label .= '<br><b>'.$langs->trans('Qty').':</b> ' . $qtylabel;
1210 if ($this->batch) {
1211 $label .= '<br><b>'.$langs->trans('Batch').':</b> '.$this->batch;
1212 }
1213 /* TODO Get also warehouse label in a property instead of id
1214 if ($this->warehouse_id > 0) {
1215 $label .= '<br><b>'.$langs->trans('Warehouse').':</b> '.$this->warehouse_id;
1216 }*/
1217 $label .= '</div>';
1218
1219 // Link to page of warehouse tab
1220 if ($option == 'movements') {
1221 $url = DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$this->id;
1222 } else {
1223 $url = DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$this->warehouse_id.'&msid='.$this->id;
1224 }
1225
1226 $link = '<a href="'.$url.'"'.($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
1227 $link .= '>';
1228 $linkend = '</a>';
1229
1230 if ($withpicto) {
1231 $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
1232 if ($withpicto != 2) {
1233 $result .= ' ';
1234 }
1235 }
1236 $result .= $link.$this->id.$linkend;
1237
1238 global $action, $hookmanager;
1239 $hookmanager->initHooks(array($this->element . 'dao'));
1240 $parameters = array('id' => $this->id, 'getnomurl' => &$result);
1241 $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1242 if ($reshook > 0) {
1243 $result = $hookmanager->resPrint;
1244 } else {
1245 $result .= $hookmanager->resPrint;
1246 }
1247
1248 return $result;
1249 }
1250
1257 public function getLibStatut($mode = 0)
1258 {
1259 return $this->LibStatut($mode);
1260 }
1261
1262 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1269 public function LibStatut($mode = 0)
1270 {
1271 // phpcs:enable
1272 global $langs;
1273
1274 if ($mode == 0 || $mode == 1) {
1275 return $langs->trans('StatusNotApplicable');
1276 } elseif ($mode == 2) {
1277 return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1278 } elseif ($mode == 3) {
1279 return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1280 } elseif ($mode == 4) {
1281 return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1282 } elseif ($mode == 5) {
1283 return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1284 }
1285
1286 return 'Bad value for mode';
1287 }
1288
1299 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1300 {
1301 global $langs;
1302
1303 $langs->load("stocks");
1304 $outputlangs->load("products");
1305
1306 if (!dol_strlen($modele)) {
1307 $modele = 'stdmovement';
1308
1309 if ($this->model_pdf) {
1310 $modele = $this->model_pdf;
1311 } elseif (getDolGlobalString('MOUVEMENT_ADDON_PDF')) {
1312 $modele = getDolGlobalString('MOUVEMENT_ADDON_PDF');
1313 }
1314 }
1315
1316 $modelpath = "core/modules/stock/doc/";
1317
1318 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1319 }
1320
1328 public function delete(User $user, $notrigger = 0)
1329 {
1330 return $this->deleteCommon($user, $notrigger);
1331 //return $this->deleteCommon($user, $notrigger, 1);
1332 }
1333
1341 private function getBatchCount($fk_product, $batch)
1342 {
1343 $cpt = 0;
1344
1345 $sql = "SELECT sum(pb.qty) as cpt";
1346 $sql .= " FROM ".$this->db->prefix()."product_batch as pb";
1347 $sql .= " INNER JOIN ".$this->db->prefix()."product_stock as ps ON ps.rowid = pb.fk_product_stock";
1348 $sql .= " WHERE ps.fk_product = " . ((int) $fk_product);
1349 $sql .= " AND pb.batch = '" . $this->db->escape($batch) . "'";
1350
1351 $result = $this->db->query($sql);
1352 if ($result) {
1353 if ($this->db->num_rows($result)) {
1354 $obj = $this->db->fetch_object($result);
1355 $cpt = $obj->cpt;
1356 }
1357
1358 $this->db->free($result);
1359 } else {
1360 dol_print_error($this->db);
1361 return -1;
1362 }
1363
1364 return $cpt;
1365 }
1366
1373 private static function getReverseType($type)
1374 {
1375 $reversetypes = array(0 => 1, 1 => 0, 2 => 3, 3 => 2);
1376
1377 return (isset($reversetypes[(int) $type]) ? $reversetypes[(int) $type] : -1);
1378 }
1379
1391 private function countMovementsWithSameSignature($code, $qty, $type, $datem = 0)
1392 {
1393 $sql = "SELECT COUNT(rowid) as nb";
1394 $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement";
1395 $sql .= " WHERE fk_product = ".((int) $this->product_id);
1396 $sql .= " AND fk_entrepot = ".((int) $this->warehouse_id);
1397 $sql .= " AND COALESCE(batch, '') = '".$this->db->escape((string) $this->batch)."'";
1398 $sql .= " AND value = ".((float) $qty);
1399 $sql .= " AND type_mouvement = ".((int) $type);
1400 $sql .= " AND COALESCE(inventorycode, '') = '".$this->db->escape($code)."'";
1401 if ($datem) {
1402 $sql .= " AND datem = '".$this->db->idate($datem)."'";
1403 }
1404
1405 $resql = $this->db->query($sql);
1406 if (!$resql) {
1407 $this->error = $this->db->lasterror();
1408 return -1;
1409 }
1410 $obj = $this->db->fetch_object($resql);
1411 $this->db->free($resql);
1412
1413 return ($obj ? (int) $obj->nb : 0);
1414 }
1415
1422 public function reverseMovement()
1423 {
1424 global $user, $langs;
1425
1426 $langs->load("stocks");
1427
1428 $formattedDate = "REVERT-" .($this->inventorycode ? $this->inventorycode : dol_print_date($this->datem, '%Y%m%d%His'));
1429
1430 // A reverse movement can not be reversed
1431 if (strpos((string) $this->inventorycode, 'REVERT-') === 0) {
1432 $this->error = $langs->trans("ErrorStockMovementIsAlreadyAReverse", $this->id);
1433 return -1;
1434 }
1435
1436 $newtype = self::getReverseType($this->type);
1437 if ($newtype < 0) {
1438 $this->error = $langs->trans("ErrorStockMovementBadType", $this->id);
1439 return -1;
1440 }
1441 $newlabel = 'Revert '.$this->label;
1442 // Note that qty should be > 0 with 0 or 3, < 0 with 1 or 2.
1443 $newqty = - $this->qty;
1444
1445 // A movement can be reversed only once. Several movements can be the same (same code, product, warehouse, batch, quantity and type),
1446 // so we compare the number of such movements with the number of reverse movements already done.
1447 $nbmovements = $this->countMovementsWithSameSignature((string) $this->inventorycode, $this->qty, $this->type, ($this->inventorycode ? 0 : $this->datem));
1448 $nbreverses = $this->countMovementsWithSameSignature($formattedDate, $newqty, $newtype);
1449 if ($nbmovements < 0 || $nbreverses < 0) {
1450 return -1;
1451 }
1452 if ($nbreverses >= $nbmovements) {
1453 $this->error = $langs->trans("ErrorStockMovementAlreadyReversed", $this->id);
1454 return -1;
1455 }
1456
1457 $this->db->begin();
1458
1459 $result = $this->_create($user, $this->product_id, $this->warehouse_id, $newqty, $newtype, 0, $newlabel, $formattedDate, '', 0, 0, $this->batch);
1460
1461 if ($result > 0) {
1462 $this->db->commit();
1463 return 1;
1464 } else {
1465 $this->db->rollback();
1466 return -1;
1467 }
1468 }
1469
1478 public function getDateLastMovementProductBatch($fk_entrepot, $fk_product, $batch)
1479 {
1480 $date = '';
1481
1482 $sql = "SELECT MAX(datem) as datem";
1483 $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement";
1484 $sql .= " WHERE fk_product = " . ((int) $fk_product);
1485 $sql .= " AND fk_entrepot = " .((int) $fk_entrepot);
1486 $sql .= " AND batch = '" . $this->db->escape($batch) . "'";
1487
1488 $result = $this->db->query($sql);
1489 if ($result) {
1490 if ($this->db->num_rows($result)) {
1491 $dateObj = $this->db->fetch_object($result);
1492 $date = $dateObj->datem;
1493 }
1494 $this->db->free($result);
1495 } else {
1496 dol_print_error($this->db);
1497 return $date;
1498 }
1499
1500 return $date;
1501 }
1502}
$propal type
'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',...
Definition propal.php:281
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage predefined suppliers products.
Class to manage customers 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.
countMovementsWithSameSignature($code, $qty, $type, $datem=0)
Count the movements that have the same product, warehouse, batch, quantity, type and code as the move...
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.
static getReverseType($type)
Return the type of the movement that reverses a movement of a given type.
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...
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
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_trunc($string, $size=40, $trunc='right', $stringencoding='UTF-8', $nodot=0, $display=0)
Truncate a string to a particular length adding '...' if string larger than length.
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.