dolibarr  20.0.0-beta
productbatch.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2007-2023 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
4  * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5  * Copyright (C) 2024 Ferran Marcet <fmarcet@2byte.es>
6  * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 3 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program. If not, see <https://www.gnu.org/licenses/>.
20  */
21 
29 require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
30 
31 
36 {
41 
45  public $element = 'productbatch';
46 
47  private static $_table_element = 'product_batch';
48 
49  public $fk_product_stock;
50 
51  public $batch = '';
52  public $qty;
53  public $warehouseid;
54 
58  public $fk_product;
59 
60  // Properties of the lot
61  public $lotid; // ID in table of the details of properties of each lots
62 
67  public $sellby = ''; // dlc
72  public $eatby = ''; // dmd/dluo
73 
74 
80  public function __construct($db)
81  {
82  $this->db = $db;
83  }
84 
85 
93  public function create($user, $notrigger = 0)
94  {
95  $error = 0;
96 
97  // Clean parameters
98  $this->cleanParam();
99 
100  // Check parameters
101  // Put here code to add control on parameters values
102 
103  // Insert request
104  $sql = "INSERT INTO ".$this->db->prefix()."product_batch (";
105  $sql .= "fk_product_stock,";
106  $sql .= "sellby,"; // no more used
107  $sql .= "eatby,"; // no more used
108  $sql .= "batch,";
109  $sql .= "qty,";
110  $sql .= "import_key";
111  $sql .= ") VALUES (";
112  $sql .= " ".(!isset($this->fk_product_stock) ? 'NULL' : $this->fk_product_stock).",";
113  $sql .= " ".(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").","; // no more used
114  $sql .= " ".(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").","; // no more used
115  $sql .= " ".(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").",";
116  $sql .= " ".(!isset($this->qty) ? 'NULL' : $this->qty).",";
117  $sql .= " ".(!isset($this->import_key) ? 'NULL' : "'".$this->db->escape($this->import_key)."'");
118  $sql .= ")";
119 
120  $this->db->begin();
121 
122  dol_syslog(get_class($this)."::create", LOG_DEBUG);
123  $resql = $this->db->query($sql);
124  if (!$resql) {
125  $error++;
126  $this->errors[] = "Error ".$this->db->lasterror();
127  }
128  if (!$error) {
129  $this->id = $this->db->last_insert_id($this->db->prefix().self::$_table_element);
130  }
131 
132  // Commit or rollback
133  if ($error) {
134  $this->db->rollback();
135  return -1 * $error;
136  } else {
137  $this->db->commit();
138  return $this->id;
139  }
140  }
141 
142 
149  public function fetch($id)
150  {
151  $sql = "SELECT";
152  $sql .= " t.rowid,";
153  $sql .= " t.tms,";
154  $sql .= " t.fk_product_stock,";
155  $sql .= " t.sellby as oldsellby,";
156  $sql .= " t.eatby as oldeatby,";
157  $sql .= " t.batch,";
158  $sql .= " t.qty,";
159  $sql .= " t.import_key,";
160  $sql .= " w.fk_entrepot,";
161  $sql .= " w.fk_product,";
162  $sql .= " pl.eatby,";
163  $sql .= " pl.sellby";
164  $sql .= " FROM ".$this->db->prefix()."product_batch as t";
165  $sql .= " INNER JOIN ".$this->db->prefix()."product_stock w on t.fk_product_stock = w.rowid"; // llx_product_stock is a parent table so this link does NOT generate duplicate record
166  $sql .= " LEFT JOIN ".$this->db->prefix()."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch";
167  $sql .= " WHERE t.rowid = ".((int) $id);
168 
169  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
170  $resql = $this->db->query($sql);
171  if ($resql) {
172  if ($this->db->num_rows($resql)) {
173  $obj = $this->db->fetch_object($resql);
174 
175  $this->id = $obj->rowid;
176  $this->tms = $this->db->jdate($obj->tms);
177  $this->fk_product_stock = $obj->fk_product_stock;
178  $this->sellby = $this->db->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
179  $this->eatby = $this->db->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
180  $this->batch = $obj->batch;
181  $this->qty = $obj->qty;
182  $this->import_key = $obj->import_key;
183  $this->warehouseid = $obj->fk_entrepot;
184  $this->fk_product = $obj->fk_product;
185  }
186  $this->db->free($resql);
187 
188  return 1;
189  } else {
190  $this->error = "Error ".$this->db->lasterror();
191  return -1;
192  }
193  }
194 
202  public function update($user = null, $notrigger = 0)
203  {
204  $error = 0;
205 
206  // Clean parameters
207  $this->cleanParam();
208 
209  // TODO Check qty is ok for stock move. Negative may not be allowed.
210  if ($this->qty < 0) {
211  }
212 
213  // Update request
214  $sql = "UPDATE ".$this->db->prefix().self::$_table_element." SET";
215  $sql .= " fk_product_stock=".(isset($this->fk_product_stock) ? $this->fk_product_stock : "null").",";
216  $sql .= " sellby=".(dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').",";
217  $sql .= " eatby=".(dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').",";
218  $sql .= " batch=".(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").",";
219  $sql .= " qty=".(isset($this->qty) ? $this->qty : "null").",";
220  $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
221  $sql .= " WHERE rowid=".((int) $this->id);
222 
223  $this->db->begin();
224 
225  dol_syslog(get_class($this)."::update", LOG_DEBUG);
226  $resql = $this->db->query($sql);
227  if (!$resql) {
228  $error++;
229  $this->errors[] = "Error ".$this->db->lasterror();
230  }
231 
232  // Commit or rollback
233  if ($error) {
234  foreach ($this->errors as $errmsg) {
235  dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
236  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
237  }
238  $this->db->rollback();
239  return -1 * $error;
240  } else {
241  $this->db->commit();
242  return 1;
243  }
244  }
245 
253  public function delete($user, $notrigger = 0)
254  {
255  $error = 0;
256 
257  $this->db->begin();
258 
259  if (!$error) {
260  $sql = "DELETE FROM ".$this->db->prefix().self::$_table_element;
261  $sql .= " WHERE rowid=".((int) $this->id);
262 
263  dol_syslog(get_class($this)."::delete", LOG_DEBUG);
264  $resql = $this->db->query($sql);
265  if (!$resql) {
266  $error++;
267  $this->errors[] = "Error ".$this->db->lasterror();
268  }
269  }
270 
271  // Commit or rollback
272  if ($error) {
273  foreach ($this->errors as $errmsg) {
274  dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
275  $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
276  }
277  $this->db->rollback();
278  return -1 * $error;
279  } else {
280  $this->db->commit();
281  return 1;
282  }
283  }
284 
285 
286 
294  public function createFromClone(User $user, $fromid)
295  {
296  $error = 0;
297 
298  $object = new Productbatch($this->db);
299 
300  $this->db->begin();
301 
302  // Load source object
303  $object->fetch($fromid);
304  $object->id = 0;
305  $object->statut = 0;
306 
307  // Clear fields
308  // ...
309 
310  // Create clone
311  $object->context['createfromclone'] = 'createfromclone';
312  $result = $object->create($user);
313 
314  // Other options
315  if ($result < 0) {
316  $this->error = $object->error;
317  $this->errors = array_merge($this->errors, $object->errors);
318  $error++;
319  }
320 
321  if (!$error) {
322  }
323 
324  unset($object->context['createfromclone']);
325 
326  // End
327  if (!$error) {
328  $this->db->commit();
329  return $object->id;
330  } else {
331  $this->db->rollback();
332  return -1;
333  }
334  }
335 
336 
343  public function initAsSpecimen()
344  {
345  $this->id = 0;
346 
347  $this->tms = dol_now();
348  $this->fk_product_stock = '';
349  $this->sellby = '';
350  $this->eatby = '';
351  $this->batch = '';
352  $this->import_key = '';
353 
354  return 1;
355  }
356 
362  private function cleanParam()
363  {
364  if (isset($this->fk_product_stock)) {
365  $this->fk_product_stock = (int) trim($this->fk_product_stock);
366  }
367  if (isset($this->batch)) {
368  $this->batch = trim($this->batch);
369  }
370  if (isset($this->qty)) {
371  $this->qty = (float) trim((string) $this->qty);
372  }
373  if (isset($this->import_key)) {
374  $this->import_key = trim($this->import_key);
375  }
376  }
377 
388  public function find($fk_product_stock = 0, $eatby = null, $sellby = null, $batch_number = '', $fk_warehouse = 0)
389  {
390  $where = array();
391 
392  $sql = "SELECT";
393  $sql .= " t.rowid,";
394  $sql .= " t.tms,";
395  $sql .= " t.fk_product_stock,";
396  $sql .= " t.sellby,"; // deprecated
397  $sql .= " t.eatby,"; // deprecated
398  $sql .= " t.batch,";
399  $sql .= " t.qty,";
400  $sql .= " t.import_key";
401  $sql .= " FROM ".$this->db->prefix().self::$_table_element." as t";
402  if ($fk_product_stock > 0 || empty($fk_warehouse)) {
403  $sql .= " WHERE t.fk_product_stock = ".((int) $fk_product_stock);
404  } else {
405  $sql .= ", ".$this->db->prefix()."product_stock as ps";
406  $sql .= " WHERE t.fk_product_stock = ps.rowid AND ps.fk_entrepot = ".((int) $fk_warehouse);
407  }
408  if (!empty($eatby)) {
409  array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated
410  }
411  if (!empty($sellby)) {
412  array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated
413  }
414 
415  if (!empty($batch_number)) {
416  $sql .= " AND batch = '".$this->db->escape($batch_number)."'";
417  }
418 
419  if (!empty($where)) {
420  $sql .= " AND (".$this->db->sanitize(implode(" OR ", $where), 1, 1, 1).")";
421  }
422 
423  dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
424  $resql = $this->db->query($sql);
425  if ($resql) {
426  if ($this->db->num_rows($resql)) {
427  $obj = $this->db->fetch_object($resql);
428 
429  $this->id = $obj->rowid;
430 
431  $this->tms = $this->db->jdate($obj->tms);
432  $this->fk_product_stock = $obj->fk_product_stock;
433  $this->sellby = $this->db->jdate($obj->sellby); // deprecated. do no tuse this data.
434  $this->eatby = $this->db->jdate($obj->eatby); // deprecated. do not use this data.
435  $this->batch = $obj->batch;
436  $this->qty = $obj->qty;
437  $this->import_key = $obj->import_key;
438  }
439  $this->db->free($resql);
440 
441  return 1;
442  } else {
443  $this->error = "Error ".$this->db->lasterror();
444  return -1;
445  }
446  }
456  public static function findAll($dbs, $fk_product_stock, $with_qty = 0, $fk_product = 0)
457  {
458  global $conf;
459 
460  $ret = array();
461 
462  $sql = "SELECT";
463  $sql .= " t.rowid,";
464  $sql .= " t.tms,";
465  $sql .= " t.fk_product_stock,";
466  $sql .= " t.sellby as oldsellby,"; // deprecated but may not be migrated into new table
467  $sql .= " t.eatby as oldeatby,"; // deprecated but may not be migrated into new table
468  $sql .= " t.batch,";
469  $sql .= " t.qty,";
470  if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
471  $sql .= " MAX(sm.datem) as date_entree,";
472  }
473  $sql .= " t.import_key";
474  if ($fk_product > 0) {
475  $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby";
476  // TODO May add extrafields to ?
477  }
478  $sql .= " FROM ".$dbs->prefix()."product_batch as t";
479  if ($fk_product > 0) { // Add link to the table of details of a lot
480  $sql .= " LEFT JOIN ".$dbs->prefix()."product_lot as pl ON pl.fk_product = ".((int) $fk_product)." AND pl.batch = t.batch";
481  // TODO May add extrafields to ?
482  }
483  if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
484  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock AS ps ON (ps.rowid = fk_product_stock)';
485  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'stock_mouvement AS sm ON (sm.batch = t.batch AND ps.fk_entrepot=sm.fk_entrepot AND sm.type_mouvement IN (0,3))';
486  }
487  $sql .= " WHERE fk_product_stock=".((int) $fk_product_stock);
488  if ($with_qty) {
489  $sql .= " AND t.qty <> 0";
490  }
491  if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
492  $sql .= ' GROUP BY t.rowid, t.tms, t.fk_product_stock,t.sellby,t.eatby , t.batch,t.qty,t.import_key';
493  if ($fk_product > 0) {
494  $sql .= ', pl.rowid, pl.eatby, pl.sellby';
495  }
496  }
497  $sql .= " ORDER BY ";
498  // TODO : use product lifo and fifo when product will implement it
499  if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
500  $sql .= 'date_entree ASC,t.batch ASC,';
501  }
502  if ($fk_product > 0) {
503  $sql .= "pl.eatby ASC, pl.sellby ASC, ";
504  }
505  $sql .= "t.eatby ASC, t.sellby ASC ";
506  $sql .= ", t.qty ".(!getDolGlobalString('DO_NOT_TRY_TO_DEFRAGMENT_STOCKS_WAREHOUSE') ? 'ASC' : 'DESC'); // Note : qty ASC is important for expedition card, to avoid stock fragmentation
507  $sql .= ", t.batch ASC";
508 
509  dol_syslog("productbatch::findAll", LOG_DEBUG);
510 
511  $resql = $dbs->query($sql);
512  if ($resql) {
513  $num = $dbs->num_rows($resql);
514  $i = 0;
515  while ($i < $num) {
516  $obj = $dbs->fetch_object($resql);
517 
518  $tmp = new Productbatch($dbs);
519  $tmp->id = $obj->rowid;
520  $tmp->tms = $dbs->jdate($obj->tms);
521  $tmp->fk_product_stock = $obj->fk_product_stock;
522  $tmp->batch = $obj->batch;
523  $tmp->qty = $obj->qty;
524  $tmp->import_key = $obj->import_key;
525 
526  if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
527  $tmp->context['stock_entry_date'] = $dbs->jdate($obj->date_entree);
528  }
529 
530  if ($fk_product > 0) {
531  // Some properties of the lot
532  $tmp->lotid = $obj->lotid; // ID in table of the details of properties of each lots
533  $tmp->sellby = $dbs->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
534  $tmp->eatby = $dbs->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
535  }
536 
537  $ret[$tmp->batch] = $tmp; // $ret is for a $fk_product_stock and unique key is on $fk_product_stock+batch
538  $i++;
539  }
540  $dbs->free($resql);
541 
542  return $ret;
543  } else {
544  //$error = "Error ".$dbs->lasterror();
545  return -1;
546  }
547  }
548 
561  public function findAllForProduct($fk_product, $fk_warehouse = 0, $qty_min = null, $sortfield = null, $sortorder = null)
562  {
563  $productBatchList = array();
564 
565  dol_syslog(__METHOD__.' fk_product='.$fk_product.', fk_warehouse='.$fk_warehouse.', qty_min='.$qty_min.', sortfield='.$sortfield.', sortorder='.$sortorder, LOG_DEBUG);
566 
567  $sql = "SELECT";
568  $sql .= " pl.rowid";
569  $sql .= ", pl.fk_product";
570  $sql .= ", pl.batch";
571  $sql .= ", pl.sellby";
572  $sql .= ", pl.eatby";
573  $sql .= ", pb.qty";
574  $sql .= " FROM ".$this->db->prefix()."product_lot as pl";
575  $sql .= " LEFT JOIN ".$this->db->prefix()."product as p ON p.rowid = pl.fk_product";
576  $sql .= " LEFT JOIN ".$this->db->prefix()."product_batch AS pb ON pl.batch = pb.batch";
577  $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock AS ps ON ps.rowid = pb.fk_product_stock AND ps.fk_product = ".((int) $fk_product);
578  $sql .= " WHERE p.entity IN (".getEntity('product').")";
579  $sql .= " AND pl.fk_product = ".((int) $fk_product);
580  if ($fk_warehouse > 0) {
581  $sql .= " AND ps.fk_entrepot = ".((int) $fk_warehouse);
582  }
583  if ($qty_min !== null) {
584  $sql .= " AND pb.qty > ".((float) price2num($qty_min, 'MS'));
585  }
586  $sql .= $this->db->order($sortfield, $sortorder);
587 
588  $resql = $this->db->query($sql);
589  if ($resql) {
590  while ($obj = $this->db->fetch_object($resql)) {
591  $productBatch = new self($this->db);
592  $productBatch->id = $obj->rowid;
593  $productBatch->fk_product = $obj->fk_product;
594  $productBatch->batch = $obj->batch;
595  $productBatch->eatby = $this->db->jdate($obj->eatby);
596  $productBatch->sellby = $this->db->jdate($obj->sellby);
597  $productBatch->qty = $obj->qty;
598  $productBatchList[] = $productBatch;
599  }
600  $this->db->free($resql);
601 
602  return $productBatchList;
603  } else {
604  dol_syslog(__METHOD__.' Error: '.$this->db->lasterror(), LOG_ERR);
605  return -1;
606  }
607  }
608 }
if($user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition: card.php:58
Parent class of all other business classes (invoices, contracts, proposals, orders,...
Manage record for batch number management.
update($user=null, $notrigger=0)
Update object into database.
create($user, $notrigger=0)
Create object into database.
fetch($id)
Load object in memory from the database.
cleanParam()
Clean fields (trimming)
createFromClone(User $user, $fromid)
Load an object from its id and create a new one in database.
find($fk_product_stock=0, $eatby=null, $sellby=null, $batch_number='', $fk_warehouse=0)
Find first detailed record that match either eat-by, sell-by or batch within the warehouse.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
static $_table_element
Name of table without prefix where object is stored.
static findAll($dbs, $fk_product_stock, $with_qty=0, $fk_product=0)
Return all batch detail records for a given product and warehouse.
findAllForProduct($fk_product, $fk_warehouse=0, $qty_min=null, $sortfield=null, $sortorder=null)
Return all batch known for a product and a warehouse (batch that was one day used)
__construct($db)
Constructor.
initAsSpecimen()
Initialise object with example values Id must be 0 if object instance is a specimen.
Class to manage Dolibarr users.
Definition: user.class.php:50
if(isModEnabled('invoice') && $user->hasRight('facture', 'lire')) if((isModEnabled('fournisseur') &&!getDolGlobalString('MAIN_USE_NEW_SUPPLIERMOD') && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') && $user->hasRight('don', 'lire')) if(isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) if(isModEnabled('invoice') &&isModEnabled('order') && $user->hasRight("commande", "lire") &&!getDolGlobalString('WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER')) $sql
Social contributions to pay.
Definition: index.php:745
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.
dol_now($mode='auto')
Return date for now.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
div float
Buy price without taxes.
Definition: style.css.php:960