productbatch.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561
  1. <?php
  2. /* Copyright (C) 2007-2021 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2013-2014 Cedric GROSS <c.gross@kreiz-it.fr>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. /**
  19. * \file product/class/productbatch.class.php
  20. * \ingroup productbatch
  21. * \brief Manage record and specific data for batch number management
  22. */
  23. require_once DOL_DOCUMENT_ROOT."/core/class/commonobject.class.php";
  24. /**
  25. * Manage record for batch number management
  26. */
  27. class Productbatch extends CommonObject
  28. {
  29. /**
  30. * Batches rules
  31. */
  32. const BATCH_RULE_SELLBY_EATBY_DATES_FIRST = 1;
  33. /**
  34. * @var string ID to identify managed object
  35. */
  36. public $element = 'productbatch';
  37. private static $_table_element = 'product_batch'; //!< Name of table without prefix where object is stored
  38. public $tms = '';
  39. public $fk_product_stock;
  40. public $sellby = ''; // dlc
  41. public $eatby = ''; // dmd/dluo
  42. public $batch = '';
  43. public $qty;
  44. public $warehouseid;
  45. /**
  46. * @var int ID
  47. */
  48. public $fk_product;
  49. /**
  50. * Constructor
  51. *
  52. * @param DoliDb $db Database handler
  53. */
  54. public function __construct($db)
  55. {
  56. $this->db = $db;
  57. }
  58. /**
  59. * Create object into database
  60. *
  61. * @param User $user User that creates
  62. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  63. * @return int <0 if KO, Id of created object if OK
  64. */
  65. public function create($user, $notrigger = 0)
  66. {
  67. global $conf, $langs;
  68. $error = 0;
  69. // Clean parameters
  70. $this->cleanParam();
  71. // Check parameters
  72. // Put here code to add control on parameters values
  73. // Insert request
  74. $sql = "INSERT INTO ".$this->db->prefix()."product_batch (";
  75. $sql .= "fk_product_stock,";
  76. $sql .= "sellby,"; // no more used
  77. $sql .= "eatby,"; // no more used
  78. $sql .= "batch,";
  79. $sql .= "qty,";
  80. $sql .= "import_key";
  81. $sql .= ") VALUES (";
  82. $sql .= " ".(!isset($this->fk_product_stock) ? 'NULL' : $this->fk_product_stock).",";
  83. $sql .= " ".(!isset($this->sellby) || dol_strlen($this->sellby) == 0 ? 'NULL' : "'".$this->db->idate($this->sellby)."'").","; // no more used
  84. $sql .= " ".(!isset($this->eatby) || dol_strlen($this->eatby) == 0 ? 'NULL' : "'".$this->db->idate($this->eatby)."'").","; // no more used
  85. $sql .= " ".(!isset($this->batch) ? 'NULL' : "'".$this->db->escape($this->batch)."'").",";
  86. $sql .= " ".(!isset($this->qty) ? 'NULL' : $this->qty).",";
  87. $sql .= " ".(!isset($this->import_key) ? 'NULL' : "'".$this->db->escape($this->import_key)."'")."";
  88. $sql .= ")";
  89. $this->db->begin();
  90. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  91. $resql = $this->db->query($sql);
  92. if (!$resql) {
  93. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  94. }
  95. if (!$error) {
  96. $this->id = $this->db->last_insert_id($this->db->prefix().self::$_table_element);
  97. }
  98. // Commit or rollback
  99. if ($error) {
  100. $this->db->rollback();
  101. return -1 * $error;
  102. } else {
  103. $this->db->commit();
  104. return $this->id;
  105. }
  106. }
  107. /**
  108. * Load object in memory from the database
  109. *
  110. * @param int $id Id object
  111. * @return int <0 if KO, >0 if OK
  112. */
  113. public function fetch($id)
  114. {
  115. global $langs;
  116. $sql = "SELECT";
  117. $sql .= " t.rowid,";
  118. $sql .= " t.tms,";
  119. $sql .= " t.fk_product_stock,";
  120. $sql .= " t.sellby as oldsellby,";
  121. $sql .= " t.eatby as oldeatby,";
  122. $sql .= " t.batch,";
  123. $sql .= " t.qty,";
  124. $sql .= " t.import_key,";
  125. $sql .= " w.fk_entrepot,";
  126. $sql .= " w.fk_product,";
  127. $sql .= " pl.eatby,";
  128. $sql .= " pl.sellby";
  129. $sql .= " FROM ".$this->db->prefix()."product_batch as t";
  130. $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
  131. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch";
  132. $sql .= " WHERE t.rowid = ".((int) $id);
  133. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  134. $resql = $this->db->query($sql);
  135. if ($resql) {
  136. if ($this->db->num_rows($resql)) {
  137. $obj = $this->db->fetch_object($resql);
  138. $this->id = $obj->rowid;
  139. $this->tms = $this->db->jdate($obj->tms);
  140. $this->fk_product_stock = $obj->fk_product_stock;
  141. $this->sellby = $this->db->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
  142. $this->eatby = $this->db->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
  143. $this->batch = $obj->batch;
  144. $this->qty = $obj->qty;
  145. $this->import_key = $obj->import_key;
  146. $this->warehouseid = $obj->fk_entrepot;
  147. $this->fk_product = $obj->fk_product;
  148. }
  149. $this->db->free($resql);
  150. return 1;
  151. } else {
  152. $this->error = "Error ".$this->db->lasterror();
  153. return -1;
  154. }
  155. }
  156. /**
  157. * Update object into database
  158. *
  159. * @param User $user User that modifies
  160. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  161. * @return int <0 if KO, >0 if OK
  162. */
  163. public function update($user = null, $notrigger = 0)
  164. {
  165. global $conf, $langs;
  166. $error = 0;
  167. // Clean parameters
  168. $this->cleanParam();
  169. // TODO Check qty is ok for stock move. Negative may not be allowed.
  170. if ($this->qty < 0) {
  171. }
  172. // Update request
  173. $sql = "UPDATE ".$this->db->prefix().self::$_table_element." SET";
  174. $sql .= " fk_product_stock=".(isset($this->fk_product_stock) ? $this->fk_product_stock : "null").",";
  175. $sql .= " sellby=".(dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').",";
  176. $sql .= " eatby=".(dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').",";
  177. $sql .= " batch=".(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").",";
  178. $sql .= " qty=".(isset($this->qty) ? $this->qty : "null").",";
  179. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
  180. $sql .= " WHERE rowid=".((int) $this->id);
  181. $this->db->begin();
  182. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  183. $resql = $this->db->query($sql);
  184. if (!$resql) {
  185. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  186. }
  187. // Commit or rollback
  188. if ($error) {
  189. foreach ($this->errors as $errmsg) {
  190. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  191. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  192. }
  193. $this->db->rollback();
  194. return -1 * $error;
  195. } else {
  196. $this->db->commit();
  197. return 1;
  198. }
  199. }
  200. /**
  201. * Delete object in database
  202. *
  203. * @param User $user User that deletes
  204. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  205. * @return int <0 if KO, >0 if OK
  206. */
  207. public function delete($user, $notrigger = 0)
  208. {
  209. global $conf, $langs;
  210. $error = 0;
  211. $this->db->begin();
  212. if (!$error) {
  213. $sql = "DELETE FROM ".$this->db->prefix().self::$_table_element."";
  214. $sql .= " WHERE rowid=".((int) $this->id);
  215. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  216. $resql = $this->db->query($sql);
  217. if (!$resql) {
  218. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  219. }
  220. }
  221. // Commit or rollback
  222. if ($error) {
  223. foreach ($this->errors as $errmsg) {
  224. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  225. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  226. }
  227. $this->db->rollback();
  228. return -1 * $error;
  229. } else {
  230. $this->db->commit();
  231. return 1;
  232. }
  233. }
  234. /**
  235. * Load an object from its id and create a new one in database
  236. *
  237. * @param User $user User making the clone
  238. * @param int $fromid Id of object to clone
  239. * @return int New id of clone
  240. */
  241. public function createFromClone(User $user, $fromid)
  242. {
  243. $error = 0;
  244. $object = new Productbatch($this->db);
  245. $this->db->begin();
  246. // Load source object
  247. $object->fetch($fromid);
  248. $object->id = 0;
  249. $object->statut = 0;
  250. // Clear fields
  251. // ...
  252. // Create clone
  253. $object->context['createfromclone'] = 'createfromclone';
  254. $result = $object->create($user);
  255. // Other options
  256. if ($result < 0) {
  257. $this->error = $object->error;
  258. $this->errors = array_merge($this->errors, $object->errors);
  259. $error++;
  260. }
  261. if (!$error) {
  262. }
  263. unset($object->context['createfromclone']);
  264. // End
  265. if (!$error) {
  266. $this->db->commit();
  267. return $object->id;
  268. } else {
  269. $this->db->rollback();
  270. return -1;
  271. }
  272. }
  273. /**
  274. * Initialise object with example values
  275. * Id must be 0 if object instance is a specimen
  276. *
  277. * @return void
  278. */
  279. public function initAsSpecimen()
  280. {
  281. $this->id = 0;
  282. $this->tms = '';
  283. $this->fk_product_stock = '';
  284. $this->sellby = '';
  285. $this->eatby = '';
  286. $this->batch = '';
  287. $this->import_key = '';
  288. }
  289. /**
  290. * Clean fields (triming)
  291. *
  292. * @return void
  293. */
  294. private function cleanParam()
  295. {
  296. if (isset($this->fk_product_stock)) {
  297. $this->fk_product_stock = (int) trim($this->fk_product_stock);
  298. }
  299. if (isset($this->batch)) {
  300. $this->batch = trim($this->batch);
  301. }
  302. if (isset($this->qty)) {
  303. $this->qty = (float) trim($this->qty);
  304. }
  305. if (isset($this->import_key)) {
  306. $this->import_key = trim($this->import_key);
  307. }
  308. }
  309. /**
  310. * Find first detail record that match eather eat-by or sell-by or batch within given warehouse
  311. *
  312. * @param int $fk_product_stock id product_stock for objet
  313. * @param integer $eatby eat-by date for object - deprecated: a search must be done on batch number
  314. * @param integer $sellby sell-by date for object - deprecated: a search must be done on batch number
  315. * @param string $batch_number batch number for object
  316. * @return int <0 if KO, >0 if OK
  317. */
  318. public function find($fk_product_stock = 0, $eatby = '', $sellby = '', $batch_number = '')
  319. {
  320. global $langs;
  321. $where = array();
  322. $sql = "SELECT";
  323. $sql .= " t.rowid,";
  324. $sql .= " t.tms,";
  325. $sql .= " t.fk_product_stock,";
  326. $sql .= " t.sellby,"; // deprecated
  327. $sql .= " t.eatby,"; // deprecated
  328. $sql .= " t.batch,";
  329. $sql .= " t.qty,";
  330. $sql .= " t.import_key";
  331. $sql .= " FROM ".$this->db->prefix().self::$_table_element." as t";
  332. $sql .= " WHERE fk_product_stock=".((int) $fk_product_stock);
  333. if (!empty($eatby)) {
  334. array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated
  335. }
  336. if (!empty($sellby)) {
  337. array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated
  338. }
  339. if (!empty($batch_number)) {
  340. $sql .= " AND batch = '".$this->db->escape($batch_number)."'";
  341. }
  342. if (!empty($where)) {
  343. $sql .= " AND (".implode(" OR ", $where).")";
  344. }
  345. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  346. $resql = $this->db->query($sql);
  347. if ($resql) {
  348. if ($this->db->num_rows($resql)) {
  349. $obj = $this->db->fetch_object($resql);
  350. $this->id = $obj->rowid;
  351. $this->tms = $this->db->jdate($obj->tms);
  352. $this->fk_product_stock = $obj->fk_product_stock;
  353. $this->sellby = $this->db->jdate($obj->sellby);
  354. $this->eatby = $this->db->jdate($obj->eatby);
  355. $this->batch = $obj->batch;
  356. $this->qty = $obj->qty;
  357. $this->import_key = $obj->import_key;
  358. }
  359. $this->db->free($resql);
  360. return 1;
  361. } else {
  362. $this->error = "Error ".$this->db->lasterror();
  363. return -1;
  364. }
  365. }
  366. /**
  367. * Return all batch detail records for a given product and warehouse
  368. *
  369. * @param DoliDB $dbs database object
  370. * @param int $fk_product_stock id product_stock for objet
  371. * @param int $with_qty 1 = doesn't return line with 0 quantity
  372. * @param int $fk_product If set to a product id, get eatby and sellby from table llx_product_lot
  373. * @return array <0 if KO, array of batch
  374. */
  375. public static function findAll($dbs, $fk_product_stock, $with_qty = 0, $fk_product = 0)
  376. {
  377. global $conf;
  378. $ret = array();
  379. $sql = "SELECT";
  380. $sql .= " t.rowid,";
  381. $sql .= " t.tms,";
  382. $sql .= " t.fk_product_stock,";
  383. $sql .= " t.sellby as oldsellby,"; // deprecated but may not be migrated into new table
  384. $sql .= " t.eatby as oldeatby,"; // deprecated but may not be migrated into new table
  385. $sql .= " t.batch,";
  386. $sql .= " t.qty,";
  387. $sql .= " t.import_key";
  388. if ($fk_product > 0) {
  389. $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby";
  390. // TODO May add extrafields to ?
  391. }
  392. $sql .= " FROM ".$dbs->prefix()."product_batch as t";
  393. if ($fk_product > 0) {
  394. $sql .= " LEFT JOIN ".$dbs->prefix()."product_lot as pl ON pl.fk_product = ".((int) $fk_product)." AND pl.batch = t.batch";
  395. // TODO May add extrafields to ?
  396. }
  397. $sql .= " WHERE fk_product_stock=".((int) $fk_product_stock);
  398. if ($with_qty) {
  399. $sql .= " AND t.qty <> 0";
  400. }
  401. $sql .= " ORDER BY ";
  402. // TODO : use product lifo and fifo when product will implement it
  403. if ($fk_product > 0) { $sql .= "pl.eatby ASC, pl.sellby ASC, "; }
  404. $sql .= "t.eatby ASC, t.sellby ASC ";
  405. $sql .= ", t.qty ".(!empty($conf->global->DO_NOT_TRY_TO_DEFRAGMENT_STOCKS_WAREHOUSE)?'DESC':'ASC'); // Note : qty ASC is important for expedition card, to avoid stock fragmentation
  406. dol_syslog("productbatch::findAll", LOG_DEBUG);
  407. $resql = $dbs->query($sql);
  408. if ($resql) {
  409. $num = $dbs->num_rows($resql);
  410. $i = 0;
  411. while ($i < $num) {
  412. $obj = $dbs->fetch_object($resql);
  413. $tmp = new Productbatch($dbs);
  414. $tmp->id = $obj->rowid;
  415. $tmp->lotid = $obj->lotid;
  416. $tmp->tms = $dbs->jdate($obj->tms);
  417. $tmp->fk_product_stock = $obj->fk_product_stock;
  418. $tmp->sellby = $dbs->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
  419. $tmp->eatby = $dbs->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
  420. $tmp->batch = $obj->batch;
  421. $tmp->qty = $obj->qty;
  422. $tmp->import_key = $obj->import_key;
  423. $ret[$tmp->batch] = $tmp; // $ret is for a $fk_product_stock and unique key is on $fk_product_stock+batch
  424. $i++;
  425. }
  426. $dbs->free($resql);
  427. return $ret;
  428. } else {
  429. $error = "Error ".$dbs->lasterror();
  430. return -1;
  431. }
  432. }
  433. /**
  434. * Return all batch for a product and a warehouse
  435. *
  436. * @param int $fk_product Id of product
  437. * @param int $fk_warehouse Id of warehouse
  438. * @param int $qty_min [=NULL] Minimum quantity
  439. * @param string $sortfield [=NULL] List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
  440. * @param string $sortorder [=NULL] Sort order, separated by comma. Example: 'ASC,DESC';
  441. * @return int|array <0 if KO, array of batch
  442. *
  443. * @throws Exception
  444. */
  445. public function findAllForProduct($fk_product, $fk_warehouse = 0, $qty_min = null, $sortfield = null, $sortorder = null)
  446. {
  447. $productBatchList = array();
  448. dol_syslog(__METHOD__.' fk_product='.$fk_product.', fk_warehouse='.$fk_warehouse.', qty_min='.$qty_min.', sortfield='.$sortfield.', sortorder='.$sortorder, LOG_DEBUG);
  449. $sql = "SELECT";
  450. $sql .= " pl.rowid";
  451. $sql .= ", pl.fk_product";
  452. $sql .= ", pl.batch";
  453. $sql .= ", pl.sellby";
  454. $sql .= ", pl.eatby";
  455. $sql .= ", pb.qty";
  456. $sql .= " FROM ".$this->db->prefix()."product_lot as pl";
  457. $sql .= " LEFT JOIN ".$this->db->prefix()."product as p ON p.rowid = pl.fk_product";
  458. $sql .= " LEFT JOIN ".$this->db->prefix()."product_batch AS pb ON pl.batch = pb.batch";
  459. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock AS ps ON ps.rowid = pb.fk_product_stock AND ps.fk_product = ".((int) $fk_product);
  460. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  461. $sql .= " AND pl.fk_product = ".((int) $fk_product);
  462. if ($fk_warehouse > 0) {
  463. $sql .= " AND ps.fk_entrepot = ".((int) $fk_warehouse);
  464. }
  465. if ($qty_min !== null) {
  466. $sql .= " AND pb.qty > ".((float) price2num($qty_min, 'MS'));
  467. }
  468. $sql .= $this->db->order($sortfield, $sortorder);
  469. $resql = $this->db->query($sql);
  470. if ($resql) {
  471. while ($obj = $this->db->fetch_object($resql)) {
  472. $productBatch = new self($this->db);
  473. $productBatch->id = $obj->rowid;
  474. $productBatch->fk_product = $obj->fk_product;
  475. $productBatch->batch = $obj->batch;
  476. $productBatch->eatby = $this->db->jdate($obj->eatby);
  477. $productBatch->sellby = $this->db->jdate($obj->sellby);
  478. $productBatch->qty = $obj->qty;
  479. $productBatchList[] = $productBatch;
  480. }
  481. $this->db->free($resql);
  482. return $productBatchList;
  483. } else {
  484. dol_syslog(__METHOD__.' Error: '.$this->db->lasterror(), LOG_ERR);
  485. return -1;
  486. }
  487. }
  488. }