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