dolibarr 23.0.3
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-2025 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2024 Ferran Marcet <fmarcet@2byte.es>
6 * Copyright (C) 2024-2025 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
29require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
30
31
36{
41
45 public $element = 'productbatch';
46
50 private static $_table_element = 'product_batch';
51
55 public $fk_product_stock;
56
60 public $batch = '';
61
65 public $qty;
66
70 public $warehouseid;
71
75 public $fk_product;
76
81 public $lotid;
82
87 public $sellby = ''; // dlc
88
93 public $eatby = ''; // dmd/dluo
94
95
101 public function __construct($db)
102 {
103 $this->db = $db;
104 }
105
106
114 public function create($user, $notrigger = 0)
115 {
116 $error = 0;
117
118 // Clean parameters
119 $this->cleanParam();
120
121 // Check parameters
122 // Put here code to add control on parameters values
123
124 // Insert request
125 $sql = "INSERT INTO ".$this->db->prefix()."product_batch (";
126 $sql .= "fk_product_stock,";
127 $sql .= "sellby,"; // no more used
128 $sql .= "eatby,"; // no more used
129 $sql .= "batch,";
130 $sql .= "qty,";
131 $sql .= "import_key";
132 $sql .= ") VALUES (";
133 $sql .= " ".(!isset($this->fk_product_stock) ? 'NULL' : $this->fk_product_stock).",";
134 $sql .= " ".(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").","; // no more used
135 $sql .= " ".(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").","; // no more used
136 $sql .= " ".(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").",";
137 $sql .= " ".(!isset($this->qty) ? 'NULL' : $this->qty).",";
138 $sql .= " ".(!isset($this->import_key) ? 'NULL' : "'".$this->db->escape($this->import_key)."'");
139 $sql .= ")";
140
141 $this->db->begin();
142
143 dol_syslog(get_class($this)."::create", LOG_DEBUG);
144 $resql = $this->db->query($sql);
145 if (!$resql) {
146 $error++;
147 $this->errors[] = "Error ".$this->db->lasterror();
148 }
149 if (!$error) {
150 $this->id = $this->db->last_insert_id($this->db->prefix().self::$_table_element);
151 }
152
153 // Commit or rollback
154 if ($error) {
155 $this->db->rollback();
156 return -1 * $error;
157 } else {
158 $this->db->commit();
159 return $this->id;
160 }
161 }
162
163
170 public function fetch($id)
171 {
172 $sql = "SELECT";
173 $sql .= " t.rowid,";
174 $sql .= " t.tms,";
175 $sql .= " t.fk_product_stock,";
176 $sql .= " t.sellby as oldsellby,";
177 $sql .= " t.eatby as oldeatby,";
178 $sql .= " t.batch,";
179 $sql .= " t.qty,";
180 $sql .= " t.import_key,";
181 $sql .= " w.fk_entrepot,";
182 $sql .= " w.fk_product,";
183 $sql .= " pl.eatby,";
184 $sql .= " pl.sellby";
185 $sql .= " FROM ".$this->db->prefix()."product_batch as t";
186 $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
187 $sql .= " LEFT JOIN ".$this->db->prefix()."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch";
188 $sql .= " WHERE t.rowid = ".((int) $id);
189
190 dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
191 $resql = $this->db->query($sql);
192 if ($resql) {
193 if ($this->db->num_rows($resql)) {
194 $obj = $this->db->fetch_object($resql);
195
196 $this->id = $obj->rowid;
197 $this->tms = $this->db->jdate($obj->tms);
198 $this->fk_product_stock = $obj->fk_product_stock;
199 $this->sellby = $this->db->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
200 $this->eatby = $this->db->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
201 $this->batch = $obj->batch;
202 $this->qty = $obj->qty;
203 $this->import_key = $obj->import_key;
204 $this->warehouseid = $obj->fk_entrepot;
205 $this->fk_product = $obj->fk_product;
206 }
207 $this->db->free($resql);
208
209 return 1;
210 } else {
211 $this->error = "Error ".$this->db->lasterror();
212 return -1;
213 }
214 }
215
223 public function update($user = null, $notrigger = 0)
224 {
225 $error = 0;
226
227 // Clean parameters
228 $this->cleanParam();
229
230 // TODO Check qty is ok for stock move. Negative may not be allowed.
231 /*
232 if ($this->qty < 0) {
233 }
234 */
235
236 // Update request
237 $sql = "UPDATE ".$this->db->prefix().self::$_table_element." SET";
238 $sql .= " fk_product_stock=".(isset($this->fk_product_stock) ? $this->fk_product_stock : "null").",";
239 $sql .= " sellby=".(dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').",";
240 $sql .= " eatby=".(dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').",";
241 $sql .= " batch=".(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").",";
242 $sql .= " qty=".(isset($this->qty) ? $this->qty : "null").",";
243 $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null");
244 $sql .= " WHERE rowid=".((int) $this->id);
245
246 $this->db->begin();
247
248 dol_syslog(get_class($this)."::update", LOG_DEBUG);
249 $resql = $this->db->query($sql);
250 if (!$resql) {
251 $error++;
252 $this->errors[] = "Error ".$this->db->lasterror();
253 }
254
255 // Commit or rollback
256 if ($error) {
257 foreach ($this->errors as $errmsg) {
258 dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
259 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
260 }
261 $this->db->rollback();
262 return -1 * $error;
263 } else {
264 $this->db->commit();
265 return 1;
266 }
267 }
268
276 public function delete($user, $notrigger = 0)
277 {
278 $error = 0;
279
280 $this->db->begin();
281
282 if (!$error) {
283 $sql = "DELETE FROM ".$this->db->prefix().self::$_table_element;
284 $sql .= " WHERE rowid=".((int) $this->id);
285
286 dol_syslog(get_class($this)."::delete", LOG_DEBUG);
287 $resql = $this->db->query($sql);
288 if (!$resql) {
289 $error++;
290 $this->errors[] = "Error ".$this->db->lasterror();
291 }
292 }
293
294 // Commit or rollback
295 if ($error) {
296 foreach ($this->errors as $errmsg) {
297 dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
298 $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
299 }
300 $this->db->rollback();
301 return -1 * $error;
302 } else {
303 $this->db->commit();
304 return 1;
305 }
306 }
307
308
309
317 public function createFromClone(User $user, $fromid)
318 {
319 $error = 0;
320
321 $object = new Productbatch($this->db);
322
323 $this->db->begin();
324
325 // Load source object
326 $object->fetch($fromid);
327 $object->id = 0;
328 $object->statut = 0;
329
330 // Clear fields
331 // ...
332
333 // Create clone
334 $object->context['createfromclone'] = 'createfromclone';
335 $result = $object->create($user);
336
337 // Other options
338 if ($result < 0) {
340 $error++;
341 }
342
343 if (!$error) {
344 }
345
346 unset($object->context['createfromclone']);
347
348 // End
349 if (!$error) {
350 $this->db->commit();
351 return $object->id;
352 } else {
353 $this->db->rollback();
354 return -1;
355 }
356 }
357
358
365 public function initAsSpecimen()
366 {
367 $this->id = 0;
368
369 $this->tms = dol_now();
370 $this->fk_product_stock = 0;
371 $this->sellby = '';
372 $this->eatby = '';
373 $this->batch = '';
374 $this->import_key = '';
375
376 return 1;
377 }
378
384 private function cleanParam()
385 {
386 if (isset($this->fk_product_stock)) {
387 $this->fk_product_stock = (int) trim((string) $this->fk_product_stock);
388 }
389 if (isset($this->batch)) {
390 $this->batch = trim($this->batch);
391 }
392 if (isset($this->qty)) {
393 $this->qty = (float) trim((string) $this->qty);
394 }
395 if (isset($this->import_key)) {
396 $this->import_key = trim($this->import_key);
397 }
398 }
399
412 public function find($fk_product_stock = 0, $eatby = '', $sellby = '', $batch_number = '', $fk_warehouse = 0, $fk_product = 0)
413 {
414 $where = array();
415
416 $sql = "SELECT";
417 $sql .= " t.rowid,";
418 $sql .= " t.tms,";
419 $sql .= " t.fk_product_stock,";
420 $sql .= " t.sellby,"; // deprecated
421 $sql .= " t.eatby,"; // deprecated
422 $sql .= " t.batch,";
423 $sql .= " t.qty,";
424 $sql .= " t.import_key";
425 $sql .= " FROM ".$this->db->prefix().self::$_table_element." as t";
426 if ($fk_product_stock > 0 || empty($fk_warehouse)) {
427 $sql .= " WHERE t.fk_product_stock = ".((int) $fk_product_stock);
428 } else {
429 $sql .= ", ".$this->db->prefix()."product_stock as ps";
430 $sql .= " WHERE t.fk_product_stock = ps.rowid AND ps.fk_entrepot = ".((int) $fk_warehouse);
431 if ($fk_product > 0) {
432 $sql .= " AND ps.fk_product = ".((int) $fk_product);
433 }
434 }
435 if (!empty($eatby)) {
436 array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated
437 }
438 if (!empty($sellby)) {
439 array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated
440 }
441
442 if (!empty($batch_number)) {
443 $sql .= " AND batch = '".$this->db->escape($batch_number)."'";
444 }
445
446 if (!empty($where)) {
447 $sql .= " AND (".$this->db->sanitize(implode(" OR ", $where), 1, 1, 1).")";
448 }
449 // Take the first one found
450 $sql .= $this->db->order("t.tms,t.rowid");
451 $sql .= $this->db->plimit(1);
452
453 $resql = $this->db->query($sql);
454 if ($resql) {
455 if ($this->db->num_rows($resql)) {
456 $obj = $this->db->fetch_object($resql);
457
458 $this->id = $obj->rowid;
459
460 $this->tms = $this->db->jdate($obj->tms);
461 $this->fk_product_stock = $obj->fk_product_stock;
462 $this->sellby = $this->db->jdate($obj->sellby); // deprecated. do not use this data.
463 $this->eatby = $this->db->jdate($obj->eatby); // deprecated. do not use this data.
464 $this->batch = $obj->batch;
465 $this->qty = $obj->qty;
466 $this->import_key = $obj->import_key;
467 }
468 $this->db->free($resql);
469
470 return 1;
471 } else {
472 $this->error = "Error ".$this->db->lasterror();
473 return -1;
474 }
475 }
485 public static function findAll($dbs, $fk_product_stock, $with_qty = 0, $fk_product = 0)
486 {
487 global $conf;
488
489 $ret = array();
490
491 $sql = "SELECT";
492 $sql .= " t.rowid,";
493 $sql .= " t.tms,";
494 $sql .= " t.fk_product_stock,";
495 $sql .= " t.sellby as oldsellby,"; // deprecated but may not be migrated into new table
496 $sql .= " t.eatby as oldeatby,"; // deprecated but may not be migrated into new table
497 $sql .= " t.batch,";
498 $sql .= " t.qty,";
499 if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
500 $sql .= " MAX(sm.datem) as date_entree,";
501 }
502 $sql .= " t.import_key";
503 if ($fk_product > 0) {
504 $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby";
505 // TODO May add extrafields to ?
506 }
507 $sql .= " FROM ".$dbs->prefix()."product_batch as t";
508 if ($fk_product > 0) { // Add link to the table of details of a lot
509 $sql .= " LEFT JOIN ".$dbs->prefix()."product_lot as pl ON pl.fk_product = ".((int) $fk_product)." AND pl.batch = t.batch";
510 // TODO May add extrafields to ?
511 }
512 if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
513 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock AS ps ON (ps.rowid = fk_product_stock)';
514 $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))';
515 }
516 $sql .= " WHERE fk_product_stock=".((int) $fk_product_stock);
517 if ($with_qty) {
518 $sql .= " AND t.qty <> 0";
519 }
520 if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
521 $sql .= ' GROUP BY t.rowid, t.tms, t.fk_product_stock,t.sellby,t.eatby , t.batch,t.qty,t.import_key';
522 if ($fk_product > 0) {
523 $sql .= ', pl.rowid, pl.eatby, pl.sellby';
524 }
525 }
526 $sql .= " ORDER BY ";
527 // TODO : use product lifo and fifo when product will implement it
528 if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
529 $sql .= 'date_entree ASC,t.batch ASC,';
530 }
531 if ($fk_product > 0) {
532 $sql .= "pl.eatby ASC, pl.sellby ASC, ";
533 }
534 $sql .= "t.eatby ASC, t.sellby ASC ";
535 $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
536 $sql .= ", t.batch ASC";
537
538 dol_syslog("productbatch::findAll", LOG_DEBUG);
539
540 $resql = $dbs->query($sql);
541 if ($resql) {
542 $num = $dbs->num_rows($resql);
543 $i = 0;
544 while ($i < $num) {
545 $obj = $dbs->fetch_object($resql);
546
547 $tmp = new Productbatch($dbs);
548 $tmp->id = $obj->rowid;
549 $tmp->tms = $dbs->jdate($obj->tms);
550 $tmp->fk_product_stock = $obj->fk_product_stock;
551 $tmp->batch = $obj->batch;
552 $tmp->qty = $obj->qty;
553 $tmp->import_key = $obj->import_key;
554
555 if (getDolGlobalString('SHIPPING_DISPLAY_STOCK_ENTRY_DATE')) {
556 $tmp->context['stock_entry_date'] = $dbs->jdate($obj->date_entree);
557 }
558
559 if ($fk_product > 0) {
560 // Some properties of the lot
561 $tmp->lotid = $obj->lotid; // ID in table of the details of properties of each lots
562 $tmp->sellby = $dbs->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
563 $tmp->eatby = $dbs->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
564 }
565
566 $ret[$tmp->batch] = $tmp; // $ret is for a $fk_product_stock and unique key is on $fk_product_stock+batch
567 $i++;
568 }
569 $dbs->free($resql);
570
571 return $ret;
572 } else {
573 //$error = "Error ".$dbs->lasterror();
574 return -1;
575 }
576 }
577
590 public function findAllForProduct($fk_product, $fk_warehouse = 0, $qty_min = null, $sortfield = null, $sortorder = null)
591 {
592 $productBatchList = array();
593
594 dol_syslog(__METHOD__.' fk_product='.$fk_product.', fk_warehouse='.$fk_warehouse.', qty_min='.$qty_min.', sortfield='.$sortfield.', sortorder='.$sortorder, LOG_DEBUG);
595
596 $sql = "SELECT";
597 $sql .= " pl.rowid";
598 $sql .= ", pl.fk_product";
599 $sql .= ", pl.batch";
600 $sql .= ", pl.sellby";
601 $sql .= ", pl.eatby";
602 $sql .= ", pb.qty";
603 $sql .= " FROM ".$this->db->prefix()."product_lot as pl";
604 $sql .= " LEFT JOIN ".$this->db->prefix()."product as p ON p.rowid = pl.fk_product";
605 $sql .= " LEFT JOIN ".$this->db->prefix()."product_batch AS pb ON pl.batch = pb.batch";
606 $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock AS ps ON ps.rowid = pb.fk_product_stock AND ps.fk_product = ".((int) $fk_product);
607 $sql .= " WHERE p.entity IN (".getEntity('product').")";
608 $sql .= " AND pl.fk_product = ".((int) $fk_product);
609 if ($fk_warehouse > 0) {
610 $sql .= " AND ps.fk_entrepot = ".((int) $fk_warehouse);
611 }
612 if ($qty_min !== null) {
613 $sql .= " AND pb.qty > ".((float) price2num($qty_min, 'MS'));
614 }
615 $sql .= $this->db->order($sortfield, $sortorder);
616
617 $resql = $this->db->query($sql);
618 if ($resql) {
619 while ($obj = $this->db->fetch_object($resql)) {
620 $productBatch = new self($this->db);
621 $productBatch->id = $obj->rowid;
622 $productBatch->fk_product = $obj->fk_product;
623 $productBatch->batch = $obj->batch;
624 $productBatch->eatby = $this->db->jdate($obj->eatby);
625 $productBatch->sellby = $this->db->jdate($obj->sellby);
626 $productBatch->qty = $obj->qty;
627 $productBatchList[] = $productBatch;
628 }
629 $this->db->free($resql);
630
631 return $productBatchList;
632 } else {
633 dol_syslog(__METHOD__.' Error: '.$this->db->lasterror(), LOG_ERR);
634 return -1;
635 }
636 }
637}
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Parent class of all other business classes (invoices, contracts, proposals, orders,...
setErrorsFromObject($object)
setErrorsFromObject
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.
const BATCH_RULE_SELLBY_EATBY_DATES_FIRST
Batches rules.
find($fk_product_stock=0, $eatby='', $sellby='', $batch_number='', $fk_warehouse=0, $fk_product=0)
Load first detailed record that match batch within the warehouse (for a given product or not).
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.
dol_now($mode='gmt')
Return date for now.
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.
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.