dolibarr 23.0.4
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' => 'Fk 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' => 'Fk 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 // Check table llx_product_lot from batchnumber for same product
361 // If found and eatby/sellby defined into table and provided and differs, return error
362 // If found and eatby/sellby defined into table and not provided, we take value from table
363 // If found and eatby/sellby not defined into table and provided, we update table
364 // If found and eatby/sellby not defined into table and not provided, we do nothing
365 // If not found, we add record
366 $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".$this->db->prefix()."product_lot as pb";
367 $sql .= " WHERE pb.fk_product = ".((int) $fk_product)." AND pb.batch = '".$this->db->escape($batch)."'";
368
369 dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
370
371 $resql = $this->db->query($sql);
372 if ($resql) {
373 $num = $this->db->num_rows($resql);
374 $i = 0;
375 if ($num > 0) {
376 while ($i < $num && $obj = $this->db->fetch_object($resql)) {
377 if ($obj->eatby) {
378 if ($eatby) {
379 $tmparray = dol_getdate((int) $eatby, true);
380 $eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
381 if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) { // We test date without hours and with hours for backward compatibility
382 // If found and eatby/sellby defined into table and provided and differs, return error
383 $langs->load("stocks");
384 $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatbywithouthour, 'dayhour'));
385 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);
386 $this->db->rollback();
387 return -3;
388 }
389 } else {
390 $eatby = $obj->eatby; // If found and eatby/sellby defined into table and not provided, we take value from table
391 }
392 } else {
393 if ($eatby) { // If found and eatby/sellby not defined into table and provided, we update table
394 $productlot = new Productlot($this->db);
395 $result = $productlot->fetch($obj->rowid);
396 $productlot->eatby = $eatby;
397 $result = $productlot->update($user);
398 if ($result <= 0) {
399 $this->setErrorsFromObject($productlot);
400 $this->db->rollback();
401 return -5;
402 }
403 }
404 }
405 if ($obj->sellby) {
406 if ($sellby) {
407 $tmparray = dol_getdate((int) $sellby, true);
408 $sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
409 if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) { // We test date without hours and with hours for backward compatibility
410 // If found and eatby/sellby defined into table and provided and differs, return error
411 $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
412 dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
413 $this->db->rollback();
414 return -3;
415 }
416 } else {
417 $sellby = $obj->sellby; // If found and eatby/sellby defined into table and not provided, we take value from table
418 }
419 } else {
420 if ($sellby) { // If found and eatby/sellby not defined into table and provided, we update table
421 $productlot = new Productlot($this->db);
422 $result = $productlot->fetch($obj->rowid);
423 $productlot->sellby = $sellby;
424 $result = $productlot->update($user);
425 if ($result <= 0) {
426 $this->setErrorsFromObject($productlot);
427 $this->db->rollback();
428 return -5;
429 }
430 }
431 }
432
433 $i++;
434 }
435 } else { // If not found, we add record
436 $productlot = new Productlot($this->db);
437 $productlot->origin_type = !empty($this->origin_type) ? $this->origin_type : '';
438 $productlot->origin_id = !empty($this->origin_id) ? $this->origin_id : 0;
439 $productlot->entity = $conf->entity;
440 $productlot->fk_product = $fk_product;
441 $productlot->batch = $batch;
442 // If we are here = first time we manage this batch, so we used dates provided by users to create lot
443 $productlot->eatby = $eatby;
444 $productlot->sellby = $sellby;
445 $result = $productlot->create($user);
446 if ($result <= 0) {
447 $this->setErrorsFromObject($productlot);
448 $this->db->rollback();
449 return -4;
450 }
451 }
452 } else {
453 dol_print_error($this->db);
454 $this->db->rollback();
455 return -1;
456 }
457 }
458
459 // Check if stock is enough when qty is < 0.
460 // THIS MUST BE DONE AT END OF MOVEMENTS
461 // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2.
462 if ($movestock && $qty < 0 && getDolGlobalInt('STOCK_DISALLOW_NEGATIVE_TRANSFER')) {
463 if (isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
464 $foundforbatch = 0;
465 $qtyisnotenough = 0;
466 if (isset($product->stock_warehouse[$entrepot_id])) {
467 foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) {
468 // Lot '59' must be different than lot '59c' and also '0123' must be different than '123'
469 if ((string) $batch !== (string) $batchcursor) {
470 continue;
471 }
472
473 $foundforbatch = 1;
474 if ($prodbatch->qty < abs($qty)) {
475 $qtyisnotenough = $prodbatch->qty;
476 }
477 break;
478 }
479 }
480 if (!$foundforbatch || $qtyisnotenough) {
481 $langs->load("stocks");
482 include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
483 $tmpwarehouse = new Entrepot($this->db);
484 $tmpwarehouse->fetch($entrepot_id);
485
486 $this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, (string) $batch, $qtyisnotenough, $tmpwarehouse->ref);
487 $this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, (string) $batch, $qtyisnotenough, $tmpwarehouse->ref);
488 $this->db->rollback();
489 return -8;
490 }
491 } else {
492 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))) {
493 $langs->load("stocks");
494 $this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
495 $this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
496 $this->db->rollback();
497 return -8;
498 }
499 }
500 }
501
502 if ($movestock && $product->stockable_product == Product::ENABLED_STOCK) { // Change stock for current product, change for subproduct is done after
503 // Set $origin_type, origin_id and fk_project
504 $fk_project = $this->fk_project;
505 if (!empty($this->origin_type)) { // This is set by caller for tracking reason
506 $origin_type = $this->origin_type;
507 $origin_id = $this->origin_id;
508 if (empty($fk_project) && $origin_type == 'project') {
509 $fk_project = $origin_id;
510 $origin_type = '';
511 $origin_id = 0;
512 }
513 } else {
514 $fk_project = 0;
515 $origin_type = '';
516 $origin_id = 0;
517 }
518
519 $sql = "INSERT INTO ".$this->db->prefix()."stock_mouvement(";
520 $sql .= " datem, fk_product, batch, eatby, sellby,";
521 $sql .= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet";
522 $sql .= ")";
523 $sql .= " VALUES ('".$this->db->idate($this->datem)."', ".((int) $this->product_id).", ";
524 $sql .= " ".(isset($batch) ? "'".$this->db->escape($batch)."'" : "null").", ";
525 $sql .= " ".($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ";
526 $sql .= " ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ";
527 $sql .= " ".((int) $this->entrepot_id).", ".((float) $this->qty).", ".((int) $this->type).",";
528 $sql .= " ".((int) $user->id).",";
529 $sql .= " '".$this->db->escape($label)."',";
530 $sql .= " ".($inventorycode ? "'".$this->db->escape($inventorycode)."'" : "null").",";
531 $sql .= " ".((float) price2num($price)).",";
532 $sql .= " ".((int) $origin_id).",";
533 $sql .= " '".$this->db->escape($origin_type)."',";
534 $sql .= " ".((int) $fk_project);
535 $sql .= ")";
536
537 dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG);
538 $resql = $this->db->query($sql);
539
540 if ($resql) {
541 $mvid = $this->db->last_insert_id($this->db->prefix()."stock_mouvement");
542 $this->id = $mvid;
543 } else {
544 $this->error = $this->db->lasterror();
545 $this->errors[] = $this->error;
546 $error = -1;
547 }
548
549 // Define current values for qty and pmp
550 $oldqty = $product->stock_reel;
551 $oldpmp = $product->pmp;
552 $oldqtywarehouse = 0;
553
554 // Test if there is already a record for couple (warehouse / product), so later we will make an update or create.
555 $alreadyarecord = 0;
556 $fk_product_stock = 0;
557 if (!$error) {
558 $sql = "SELECT rowid, reel FROM ".$this->db->prefix()."product_stock";
559 $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product); // This is a unique key
560
561 dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG);
562 $resql = $this->db->query($sql);
563 if ($resql) {
564 $obj = $this->db->fetch_object($resql);
565 if ($obj) {
566 $alreadyarecord = 1;
567 $oldqtywarehouse = $obj->reel;
568 $fk_product_stock = $obj->rowid;
569 }
570 $this->db->free($resql);
571 } else {
572 $this->errors[] = $this->db->lasterror();
573 $error = -2;
574 }
575 }
576
577 // Calculate new AWP (PMP)
578 $newpmp = 0;
579 if (!$error) {
580 if ($type == 0 || $type == 3) {
581 // After a stock increase
582 // Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0.
583 // Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input)
584 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')))) {
585 $oldqtytouse = ($oldqty >= 0 ? $oldqty : 0);
586 // We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined
587 if ($oldpmp > 0 && ($oldqtytouse + $qty) != 0) {
588 $newpmp = price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU');
589 } else {
590 $newpmp = $price; // For this product, PMP was not yet set. We set it to input price.
591 }
592 //print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." ";
593 //print "qty=".$qty." newpmp=".$newpmp;
594 //exit;
595 } else {
596 $newpmp = $oldpmp;
597 }
598 } else {
599 // ($type == 1 || $type == 2)
600 // -> After a stock decrease, we don't change value of the AWP/PMP of a product.
601 // else
602 // Type of movement unknown
603 $newpmp = $oldpmp;
604 }
605 }
606 // Update stock quantity
607 if (!$error) {
608 if ($alreadyarecord > 0) {
609 $sql = "UPDATE ".$this->db->prefix()."product_stock SET reel = " . ((float) $oldqtywarehouse + (float) $qty);
610 $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product);
611 } else {
612 $sql = "INSERT INTO ".$this->db->prefix()."product_stock";
613 $sql .= " (reel, fk_entrepot, fk_product) VALUES ";
614 $sql .= " (".((float) $qty).", ".((int) $entrepot_id).", ".((int) $fk_product).")";
615 }
616
617 dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG);
618 $resql = $this->db->query($sql);
619 if (!$resql) {
620 $this->errors[] = $this->db->lasterror();
621 $error = -3;
622 } elseif (empty($fk_product_stock)) {
623 $fk_product_stock = $this->db->last_insert_id($this->db->prefix()."product_stock");
624 }
625 }
626
627 // Update detail of stock for the lot.
628 if (!$error && isModEnabled('productbatch') && (($product->hasbatch() && !$skip_batch) || $force_update_batch)) {
629 if ($id_product_batch > 0) {
630 $result = $this->createBatch($id_product_batch, $qty);
631 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
632 $param_batch = array('fk_product_stock' => $fk_product_stock, 'batchnumber' => (string) $batch);
633 $result = $this->createBatch($param_batch, $qty);
634 }
635 } else {
636 $param_batch = array('fk_product_stock' => $fk_product_stock, 'batchnumber' => (string) $batch);
637 $result = $this->createBatch($param_batch, $qty);
638 }
639 if ($result < 0) {
640 $error++;
641 }
642 }
643
644 // Update PMP and denormalized value of stock qty at product level
645 if (!$error) {
646 $newpmp = price2num($newpmp, 'MU');
647
648 // $sql = "UPDATE ".$this->db->prefix()."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty;
649 // $sql.= " WHERE rowid = ".((int) $fk_product);
650 // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
651 $sql = "UPDATE ".$this->db->prefix()."product as p SET pmp = ".((float) $newpmp).",";
652 $sql .= " stock=(SELECT SUM(ps.reel) FROM ".$this->db->prefix()."product_stock as ps WHERE ps.fk_product = p.rowid)";
653 $sql .= " WHERE rowid = ".((int) $fk_product);
654
655 dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG);
656 $resql = $this->db->query($sql);
657 if (!$resql) {
658 $this->errors[] = $this->db->lasterror();
659 $error = -4;
660 }
661 }
662
663 if (empty($donotcleanemptylines)) {
664 // 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
665 // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
666 $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)";
667 $resql = $this->db->query($sql);
668 // We do not test error, it can fails if there is child in batch details
669 }
670 }
671
672 // Add movement for sub products (recursive call)
673 if (!$error && getDolGlobalString('PRODUIT_SOUSPRODUITS') && !getDolGlobalString('PRODUIT_SOUSPRODUITS_ALWAYS_DISABLE_CHILDREN_STOCK_MOVE') && empty($disablestockchangeforsubproduct)) {
674 $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
675 }
676
677 if ($movestock && !$error) {
678 // Call trigger
679 if ($product->stockable_product != Product::DISABLED_STOCK ) {
680 $result = $this->call_trigger('STOCK_MOVEMENT', $user);
681 if ($result < 0) {
682 $error++;
683 }
684 }
685 // End call triggers
686 // Check unicity for serial numbered equipment once all movement were done.
687 if (!$error && isModEnabled('productbatch') && $product->hasbatch() && !$skip_batch) {
688 if ($product->status_batch == 2 && $qty > 0) { // We check only if we increased qty
689 if ($this->getBatchCount($fk_product, (string) $batch) > 1) {
690 $error++;
691 $this->errors[] = $langs->trans("TooManyQtyForSerialNumber", $product->ref, (string) $batch);
692 }
693 }
694 }
695 }
696
697 if (!$error) {
698 $this->db->commit();
699 return $mvid;
700 } else {
701 $this->db->rollback();
702 dol_syslog(get_class($this)."::_create error code=".$error, LOG_ERR);
703 return -6;
704 }
705 }
706
707
708
716 public function fetch($id)
717 {
718 dol_syslog(__METHOD__, LOG_DEBUG);
719
720 $sql = "SELECT";
721 $sql .= " t.rowid,";
722 $sql .= " t.tms,";
723 $sql .= " t.datem,";
724 $sql .= " t.fk_product,";
725 $sql .= " t.fk_entrepot,";
726 $sql .= " t.value,";
727 $sql .= " t.price,";
728 $sql .= " t.type_mouvement,";
729 $sql .= " t.fk_user_author,";
730 $sql .= " t.label,";
731 $sql .= " t.fk_origin as origin_id,";
732 $sql .= " t.origintype as origin_type,";
733 $sql .= " t.inventorycode as movementcode,";
734 $sql .= " t.batch,";
735 $sql .= " t.eatby,";
736 $sql .= " t.sellby,";
737 $sql .= " t.fk_projet as fk_project";
738 $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
739 $sql .= " WHERE t.rowid = ".((int) $id);
740
741 $resql = $this->db->query($sql);
742 if ($resql) {
743 $numrows = $this->db->num_rows($resql);
744 if ($numrows) {
745 $obj = $this->db->fetch_object($resql);
746
747 $this->id = $obj->rowid;
748
749 $this->product_id = $obj->fk_product;
750 $this->warehouse_id = $obj->fk_entrepot;
751 $this->qty = $obj->value;
752 $this->type = $obj->type_mouvement;
753
754 $this->tms = $this->db->jdate($obj->tms);
755 $this->datem = $this->db->jdate($obj->datem);
756 $this->price = $obj->price;
757 $this->fk_user_author = $obj->fk_user_author;
758 $this->label = $obj->label;
759 $this->fk_origin = $obj->origin_id; // For backward compatibility
760 $this->origintype = $obj->origin_type; // For backward compatibility
761 $this->origin_id = $obj->origin_id;
762 $this->origin_type = $obj->origin_type;
763 $this->inventorycode = $obj->movementcode; // For backward compatibility
764 $this->movementcode = $obj->movementcode;
765 $this->batch = $obj->batch;
766 $this->eatby = $this->db->jdate($obj->eatby);
767 $this->sellby = $this->db->jdate($obj->sellby);
768 $this->fk_project = $obj->fk_project;
769 }
770
771 // Retrieve all extrafield
772 $this->fetch_optionals();
773
774 // $this->fetch_lines();
775
776 $this->db->free($resql);
777
778 if ($numrows) {
779 return 1;
780 } else {
781 return 0;
782 }
783 } else {
784 $this->errors[] = 'Error '.$this->db->lasterror();
785 dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
786
787 return -1;
788 }
789 }
790
791
792
793
808 private function _createSubProduct($user, $idProduct, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '')
809 {
810 global $langs;
811
812 $error = 0;
813
814 $sql = "SELECT fk_product_pere, fk_product_fils, qty";
815 $sql .= " FROM ".$this->db->prefix()."product_association";
816 $sql .= " WHERE fk_product_pere = ".((int) $idProduct);
817 $sql .= " AND incdec = 1";
818
819 dol_syslog(__METHOD__.' for parent product '.$idProduct, LOG_DEBUG);
820 $resql = $this->db->query($sql);
821 if ($resql) {
822 // Create movement for each sub-product
823 while ($obj = $this->db->fetch_object($resql)) {
824 $tmpmove = dol_clone($this, 1);
825 $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
826 if ($result < 0) {
827 $this->error = $tmpmove->error;
828 $this->errors = array_merge($this->errors, $tmpmove->errors);
829 if ($result == -2) {
830 $this->errors[] = $langs->trans('ErrorNoteAlsoThatSubProductCantBeFollowedByLot');
831 }
832 $error = $result;
833 dol_syslog(__METHOD__ . ' Error : ' . $this->errorsToString(), LOG_ERR);
834 break;
835 }
836 unset($tmpmove);
837 }
838
839 $this->db->free($resql);
840 } else {
841 $error = -2;
842 }
843
844 return $error;
845 }
846
847
866 public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '', $donotcleanemptylines = 0)
867 {
868 $skip_batch = !isModEnabled('productbatch');
869
870 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);
871 }
872
892 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)
893 {
894 $skip_batch = !isModEnabled('productbatch');
895
896 return $this->_create($user, $fk_product, $entrepot_id, $qty, 3, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch, $disablestockchangeforsubproduct, $donotcleanemptylines);
897 }
898
906 public function calculateBalanceForProductBefore($productidselected, $datebefore)
907 {
908 $nb = 0;
909
910 $sql = "SELECT SUM(value) as nb from ".$this->db->prefix()."stock_mouvement";
911 $sql .= " WHERE fk_product = ".((int) $productidselected);
912 $sql .= " AND datem < '".$this->db->idate($datebefore)."'";
913
914 dol_syslog(get_class($this).__METHOD__, LOG_DEBUG);
915 $resql = $this->db->query($sql);
916 if ($resql) {
917 $obj = $this->db->fetch_object($resql);
918 if ($obj) {
919 $nb = (int) $obj->nb;
920 }
921 return (empty($nb) ? 0 : $nb);
922 } else {
923 dol_print_error($this->db);
924 return -1;
925 }
926 }
927
937 private function createBatch($dluo, $qty)
938 {
939 global $user, $langs;
940
941 $langs->load('productbatch');
942
943 $pdluo = new Productbatch($this->db);
944
945 $vbatchnumber = '';
946 $vfk_product_stock = 0;
947 $result = 0;
948
949 // Try to find an existing record with same batch number or id
950 if (is_numeric($dluo)) {
951 $result = $pdluo->fetch($dluo);
952 if (empty($pdluo->id)) {
953 // We didn't find the line. May be it was deleted before by a previous move in same transaction.
954 $this->error = $langs->trans('CantMoveNonExistantSerial');
955 $this->errors[] = $this->error;
956 $result = -2;
957 }
958 } elseif (is_array($dluo)) {
959 if (isset($dluo['fk_product_stock'])) {
960 $vfk_product_stock = $dluo['fk_product_stock'];
961 $vbatchnumber = $dluo['batchnumber'];
962
963 $result = $pdluo->find($vfk_product_stock, 0, 0, $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here)
964 } else {
965 dol_syslog(get_class($this)."::createBatch array param dluo must contain at least key fk_product_stock", LOG_ERR);
966 $result = -1;
967 }
968 } else {
969 dol_syslog(get_class($this)."::createBatch error invalid param dluo", LOG_ERR);
970 $result = -1;
971 }
972
973 if ($result >= 0) {
974 // No error
975 if ($pdluo->id > 0) { // product_batch record found
976 //print "Avant ".$pdluo->qty." Apres ".($pdluo->qty + $qty)."<br>";
977 $pdluo->qty += $qty;
978 if ($pdluo->qty == 0) {
979 $result = $pdluo->delete($user, 1);
980 } else {
981 $result = $pdluo->update($user, 1);
982 }
983 } else { // product_batch record not found
984 $pdluo->fk_product_stock = $vfk_product_stock;
985 $pdluo->qty = $qty;
986 $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.
987 $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.
988 $pdluo->batch = $vbatchnumber;
989
990 $result = $pdluo->create($user, 1);
991 if ($result < 0) {
992 $this->setErrorsFromObject($pdluo);
993 }
994 }
995 }
996
997 return $result;
998 }
999
1000 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1008 public function get_origin($origin_id, $origin_type)
1009 {
1010 // phpcs:enable
1011 $origin = '';
1012
1013 switch ($origin_type) {
1014 case 'commande':
1015 require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
1016 $origin = new Commande($this->db);
1017 break;
1018 case 'shipping':
1019 require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
1020 $origin = new Expedition($this->db);
1021 break;
1022 case 'facture':
1023 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
1024 $origin = new Facture($this->db);
1025 break;
1026 case 'order_supplier':
1027 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
1028 $origin = new CommandeFournisseur($this->db);
1029 break;
1030 case 'invoice_supplier':
1031 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
1032 $origin = new FactureFournisseur($this->db);
1033 break;
1034 case 'project':
1035 require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
1036 $origin = new Project($this->db);
1037 break;
1038 case 'mo':
1039 require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
1040 $origin = new Mo($this->db);
1041 break;
1042 case 'user':
1043 require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
1044 $origin = new User($this->db);
1045 break;
1046 case 'reception':
1047 require_once DOL_DOCUMENT_ROOT.'/reception/class/reception.class.php';
1048 $origin = new Reception($this->db);
1049 break;
1050 case 'inventory':
1051 require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
1052 $origin = new Inventory($this->db);
1053 break;
1054 default:
1055 if ($origin_type) {
1056 // Separate origin_type with "@" : left part is class name, right part is module name
1057 $origin_type_array = explode('@', $origin_type);
1058 $classname = $origin_type_array[0];
1059 $modulename = empty($origin_type_array[1]) ? strtolower($classname) : $origin_type_array[1];
1060
1061 // Dolibarr names its class files in lowercase, so use a lowercase file name whatever
1062 // the case of the class name (class names themselves are case insensitive in PHP).
1063 $result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php');
1064
1065 if ($result) {
1066 $classname = ucfirst($classname);
1067 $origin = new $classname($this->db);
1068 }
1069 }
1070 break;
1071 }
1072
1073 if (empty($origin) || !is_object($origin)) {
1074 return '';
1075 }
1076
1077 if ($origin->fetch($origin_id) > 0) {
1078 return $origin->getNomUrl(1);
1079 }
1080
1081 return '';
1082 }
1083
1094 public function setOrigin($origin_element, $origin_id, $line_id_object_src = 0, $line_id_object_origin = 0)
1095 {
1096 $this->origin_type = $origin_element;
1097 $this->origin_id = $origin_id;
1098 $this->line_id_object_src = $line_id_object_src;
1099 $this->line_id_object_origin = $line_id_object_origin;
1100 // For backward compatibility
1101 $this->origintype = $origin_element;
1102 $this->fk_origin = $origin_id;
1103 }
1104
1105
1113 public function initAsSpecimen()
1114 {
1115 // Initialize parameters
1116 $this->id = 0;
1117
1118 // There is no specific properties. All data into insert are provided as method parameter.
1119
1120 return 1;
1121 }
1122
1129 public function getTypeMovement($withlabel = 0)
1130 {
1131 global $langs;
1132
1133 $s = '';
1134 switch ($this->type) {
1135 case "0":
1136 $s = '<span class="fa fa-level-down-alt stockmovemententry stockmovementtransfer" title="'.$langs->trans('StockIncreaseAfterCorrectTransfer').'"></span>';
1137 if ($withlabel) {
1138 $s .= $langs->trans('StockIncreaseAfterCorrectTransfer');
1139 }
1140 break;
1141 case "1":
1142 $s = '<span class="fa fa-level-up-alt stockmovementexit stockmovementtransfer" title="'.$langs->trans('StockDecreaseAfterCorrectTransfer').'"></span>';
1143 if ($withlabel) {
1144 $s .= $langs->trans('StockDecreaseAfterCorrectTransfer');
1145 }
1146 break;
1147 case "2":
1148 $s = '<span class="fa fa-long-arrow-alt-up stockmovementexit stockmovement" title="'.$langs->trans('StockDecrease').'"></span>';
1149 if ($withlabel) {
1150 $s .= $langs->trans('StockDecrease');
1151 }
1152 break;
1153 case "3":
1154 $s = '<span class="fa fa-long-arrow-alt-down stockmovemententry stockmovement" title="'.$langs->trans('StockIncrease').'"></span>';
1155 if ($withlabel) {
1156 $s .= $langs->trans('StockIncrease');
1157 }
1158 break;
1159 }
1160
1161 return $s;
1162 }
1163
1175 public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
1176 {
1177 global $langs;
1178
1179 $result = '';
1180
1181 $label = img_picto('', 'stock', 'class="pictofixedwidth"').'<u>'.$langs->trans("StockMovement").'</u>';
1182 $label .= '<div width="100%">';
1183 $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->id;
1184 $label .= '<br><b>'.$langs->trans('Label').':</b> '.$this->label;
1185 $qtylabel = (($this->qty > 0) ? '<span class="stockmovemententry">+' : '<span class="stockmovementexit">') . $this->qty . '</span>';
1186 if ($this->inventorycode) {
1187 $label .= '<br><b>'.$langs->trans('InventoryCode').':</b> '.$this->inventorycode;
1188 }
1189 $label .= '<br><b>'.$langs->trans('Qty').':</b> ' . $qtylabel;
1190 if ($this->batch) {
1191 $label .= '<br><b>'.$langs->trans('Batch').':</b> '.$this->batch;
1192 }
1193 /* TODO Get also warehouse label in a property instead of id
1194 if ($this->warehouse_id > 0) {
1195 $label .= '<br><b>'.$langs->trans('Warehouse').':</b> '.$this->warehouse_id;
1196 }*/
1197 $label .= '</div>';
1198
1199 // Link to page of warehouse tab
1200 if ($option == 'movements') {
1201 $url = DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$this->id;
1202 } else {
1203 $url = DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$this->warehouse_id.'&msid='.$this->id;
1204 }
1205
1206 $link = '<a href="'.$url.'"'.($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
1207 $link .= '>';
1208 $linkend = '</a>';
1209
1210 if ($withpicto) {
1211 $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
1212 if ($withpicto != 2) {
1213 $result .= ' ';
1214 }
1215 }
1216 $result .= $link.$this->id.$linkend;
1217 return $result;
1218 }
1219
1226 public function getLibStatut($mode = 0)
1227 {
1228 return $this->LibStatut($mode);
1229 }
1230
1231 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1238 public function LibStatut($mode = 0)
1239 {
1240 // phpcs:enable
1241 global $langs;
1242
1243 if ($mode == 0 || $mode == 1) {
1244 return $langs->trans('StatusNotApplicable');
1245 } elseif ($mode == 2) {
1246 return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1247 } elseif ($mode == 3) {
1248 return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1249 } elseif ($mode == 4) {
1250 return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
1251 } elseif ($mode == 5) {
1252 return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9');
1253 }
1254
1255 return 'Bad value for mode';
1256 }
1257
1268 public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
1269 {
1270 global $langs;
1271
1272 $langs->load("stocks");
1273 $outputlangs->load("products");
1274
1275 if (!dol_strlen($modele)) {
1276 $modele = 'stdmovement';
1277
1278 if ($this->model_pdf) {
1279 $modele = $this->model_pdf;
1280 } elseif (getDolGlobalString('MOUVEMENT_ADDON_PDF')) {
1281 $modele = getDolGlobalString('MOUVEMENT_ADDON_PDF');
1282 }
1283 }
1284
1285 $modelpath = "core/modules/stock/doc/";
1286
1287 return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
1288 }
1289
1297 public function delete(User $user, $notrigger = 0)
1298 {
1299 return $this->deleteCommon($user, $notrigger);
1300 //return $this->deleteCommon($user, $notrigger, 1);
1301 }
1302
1310 private function getBatchCount($fk_product, $batch)
1311 {
1312 $cpt = 0;
1313
1314 $sql = "SELECT sum(pb.qty) as cpt";
1315 $sql .= " FROM ".$this->db->prefix()."product_batch as pb";
1316 $sql .= " INNER JOIN ".$this->db->prefix()."product_stock as ps ON ps.rowid = pb.fk_product_stock";
1317 $sql .= " WHERE ps.fk_product = " . ((int) $fk_product);
1318 $sql .= " AND pb.batch = '" . $this->db->escape($batch) . "'";
1319
1320 $result = $this->db->query($sql);
1321 if ($result) {
1322 if ($this->db->num_rows($result)) {
1323 $obj = $this->db->fetch_object($result);
1324 $cpt = $obj->cpt;
1325 }
1326
1327 $this->db->free($result);
1328 } else {
1329 dol_print_error($this->db);
1330 return -1;
1331 }
1332
1333 return $cpt;
1334 }
1335
1341 public function reverseMovement()
1342 {
1343 global $user;
1344
1345 $formattedDate = "REVERT-" .($this->inventorycode ? $this->inventorycode : dol_print_date($this->datem, '%Y%m%d%His'));
1346 if ($this->inventorycode == $formattedDate) {
1347 return -1;
1348 }
1349
1350 $newlabel = 'Revert '.$this->label;
1351 // 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)
1352 // Note that qty should be > 0 with 0 or 3, < 0 with 1 or 2.
1353 if ($this->type == 0) {
1354 $newtype = 1;
1355 } elseif ($this->type == 1) {
1356 $newtype = 0;
1357 } elseif ($this->type == 2) {
1358 $newtype = 3;
1359 } elseif ($this->type == 3) {
1360 $newtype = 2;
1361 } else {
1362 return -1;
1363 }
1364 $newqty = - $this->qty;
1365
1366 $this->db->begin();
1367
1368 $result = $this->_create($user, $this->product_id, $this->warehouse_id, $newqty, $newtype, 0, $newlabel, $formattedDate, '', 0, 0, $this->batch);
1369
1370 if ($result > 0) {
1371 $this->db->commit();
1372 return 1;
1373 } else {
1374 $this->db->rollback();
1375 return -1;
1376 }
1377 }
1378
1387 public function getDateLastMovementProductBatch($fk_entrepot, $fk_product, $batch)
1388 {
1389 $date = '';
1390
1391 $sql = "SELECT MAX(datem) as datem";
1392 $sql .= " FROM ".MAIN_DB_PREFIX."stock_mouvement";
1393 $sql .= " WHERE fk_product = " . ((int) $fk_product);
1394 $sql .= " AND fk_entrepot = " .((int) $fk_entrepot);
1395 $sql .= " AND batch = '" . $this->db->escape($batch) . "'";
1396
1397 $result = $this->db->query($sql);
1398 if ($result) {
1399 if ($this->db->num_rows($result)) {
1400 $dateObj = $this->db->fetch_object($result);
1401 $date = $dateObj->datem;
1402 }
1403 $this->db->free($result);
1404 } else {
1405 dol_print_error($this->db);
1406 return $date;
1407 }
1408
1409 return $date;
1410 }
1411}
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