productbatch.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562
  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 INNER JOIN ".$this->db->prefix()."product_stock w on t.fk_product_stock = w.rowid";
  130. $sql .= " LEFT JOIN ".$this->db->prefix()."product_lot as pl on pl.fk_product = w.fk_product and pl.batch = t.batch";
  131. $sql .= " WHERE t.rowid = ".((int) $id);
  132. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  133. $resql = $this->db->query($sql);
  134. if ($resql) {
  135. if ($this->db->num_rows($resql)) {
  136. $obj = $this->db->fetch_object($resql);
  137. $this->id = $obj->rowid;
  138. $this->tms = $this->db->jdate($obj->tms);
  139. $this->fk_product_stock = $obj->fk_product_stock;
  140. $this->sellby = $this->db->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
  141. $this->eatby = $this->db->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
  142. $this->batch = $obj->batch;
  143. $this->qty = $obj->qty;
  144. $this->import_key = $obj->import_key;
  145. $this->warehouseid = $obj->fk_entrepot;
  146. $this->fk_product = $obj->fk_product;
  147. }
  148. $this->db->free($resql);
  149. return 1;
  150. } else {
  151. $this->error = "Error ".$this->db->lasterror();
  152. return -1;
  153. }
  154. }
  155. /**
  156. * Update object into database
  157. *
  158. * @param User $user User that modifies
  159. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  160. * @return int <0 if KO, >0 if OK
  161. */
  162. public function update($user = null, $notrigger = 0)
  163. {
  164. global $conf, $langs;
  165. $error = 0;
  166. // Clean parameters
  167. $this->cleanParam();
  168. // TODO Check qty is ok for stock move. Negative may not be allowed.
  169. if ($this->qty < 0) {
  170. }
  171. // Update request
  172. $sql = "UPDATE ".$this->db->prefix().self::$_table_element." SET";
  173. $sql .= " fk_product_stock=".(isset($this->fk_product_stock) ? $this->fk_product_stock : "null").",";
  174. $sql .= " sellby=".(dol_strlen($this->sellby) != 0 ? "'".$this->db->idate($this->sellby)."'" : 'null').",";
  175. $sql .= " eatby=".(dol_strlen($this->eatby) != 0 ? "'".$this->db->idate($this->eatby)."'" : 'null').",";
  176. $sql .= " batch=".(isset($this->batch) ? "'".$this->db->escape($this->batch)."'" : "null").",";
  177. $sql .= " qty=".(isset($this->qty) ? $this->qty : "null").",";
  178. $sql .= " import_key=".(isset($this->import_key) ? "'".$this->db->escape($this->import_key)."'" : "null")."";
  179. $sql .= " WHERE rowid=".((int) $this->id);
  180. $this->db->begin();
  181. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  182. $resql = $this->db->query($sql);
  183. if (!$resql) {
  184. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  185. }
  186. // Commit or rollback
  187. if ($error) {
  188. foreach ($this->errors as $errmsg) {
  189. dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
  190. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  191. }
  192. $this->db->rollback();
  193. return -1 * $error;
  194. } else {
  195. $this->db->commit();
  196. return 1;
  197. }
  198. }
  199. /**
  200. * Delete object in database
  201. *
  202. * @param User $user User that deletes
  203. * @param int $notrigger 0=launch triggers after, 1=disable triggers
  204. * @return int <0 if KO, >0 if OK
  205. */
  206. public function delete($user, $notrigger = 0)
  207. {
  208. global $conf, $langs;
  209. $error = 0;
  210. $this->db->begin();
  211. if (!$error) {
  212. $sql = "DELETE FROM ".$this->db->prefix().self::$_table_element."";
  213. $sql .= " WHERE rowid=".((int) $this->id);
  214. dol_syslog(get_class($this)."::delete", LOG_DEBUG);
  215. $resql = $this->db->query($sql);
  216. if (!$resql) {
  217. $error++; $this->errors[] = "Error ".$this->db->lasterror();
  218. }
  219. }
  220. // Commit or rollback
  221. if ($error) {
  222. foreach ($this->errors as $errmsg) {
  223. dol_syslog(get_class($this)."::delete ".$errmsg, LOG_ERR);
  224. $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
  225. }
  226. $this->db->rollback();
  227. return -1 * $error;
  228. } else {
  229. $this->db->commit();
  230. return 1;
  231. }
  232. }
  233. /**
  234. * Load an object from its id and create a new one in database
  235. *
  236. * @param User $user User making the clone
  237. * @param int $fromid Id of object to clone
  238. * @return int New id of clone
  239. */
  240. public function createFromClone(User $user, $fromid)
  241. {
  242. $error = 0;
  243. $object = new Productbatch($this->db);
  244. $this->db->begin();
  245. // Load source object
  246. $object->fetch($fromid);
  247. $object->id = 0;
  248. $object->statut = 0;
  249. // Clear fields
  250. // ...
  251. // Create clone
  252. $object->context['createfromclone'] = 'createfromclone';
  253. $result = $object->create($user);
  254. // Other options
  255. if ($result < 0) {
  256. $this->error = $object->error;
  257. $this->errors = array_merge($this->errors, $object->errors);
  258. $error++;
  259. }
  260. if (!$error) {
  261. }
  262. unset($object->context['createfromclone']);
  263. // End
  264. if (!$error) {
  265. $this->db->commit();
  266. return $object->id;
  267. } else {
  268. $this->db->rollback();
  269. return -1;
  270. }
  271. }
  272. /**
  273. * Initialise object with example values
  274. * Id must be 0 if object instance is a specimen
  275. *
  276. * @return void
  277. */
  278. public function initAsSpecimen()
  279. {
  280. $this->id = 0;
  281. $this->tms = '';
  282. $this->fk_product_stock = '';
  283. $this->sellby = '';
  284. $this->eatby = '';
  285. $this->batch = '';
  286. $this->import_key = '';
  287. }
  288. /**
  289. * Clean fields (triming)
  290. *
  291. * @return void
  292. */
  293. private function cleanParam()
  294. {
  295. if (isset($this->fk_product_stock)) {
  296. $this->fk_product_stock = (int) trim($this->fk_product_stock);
  297. }
  298. if (isset($this->batch)) {
  299. $this->batch = trim($this->batch);
  300. }
  301. if (isset($this->qty)) {
  302. $this->qty = (float) trim($this->qty);
  303. }
  304. if (isset($this->import_key)) {
  305. $this->import_key = trim($this->import_key);
  306. }
  307. }
  308. /**
  309. * Find first detail record that match eather eat-by or sell-by or batch within given warehouse
  310. *
  311. * @param int $fk_product_stock id product_stock for objet
  312. * @param integer $eatby eat-by date for object - deprecated: a search must be done on batch number
  313. * @param integer $sellby sell-by date for object - deprecated: a search must be done on batch number
  314. * @param string $batch_number batch number for object
  315. * @return int <0 if KO, >0 if OK
  316. */
  317. public function find($fk_product_stock = 0, $eatby = '', $sellby = '', $batch_number = '')
  318. {
  319. global $langs;
  320. $where = array();
  321. $sql = "SELECT";
  322. $sql .= " t.rowid,";
  323. $sql .= " t.tms,";
  324. $sql .= " t.fk_product_stock,";
  325. $sql .= " t.sellby,"; // deprecated
  326. $sql .= " t.eatby,"; // deprecated
  327. $sql .= " t.batch,";
  328. $sql .= " t.qty,";
  329. $sql .= " t.import_key";
  330. $sql .= " FROM ".$this->db->prefix().self::$_table_element." as t";
  331. $sql .= " WHERE fk_product_stock=".((int) $fk_product_stock);
  332. if (!empty($eatby)) {
  333. array_push($where, " eatby = '".$this->db->idate($eatby)."'"); // deprecated
  334. }
  335. if (!empty($sellby)) {
  336. array_push($where, " sellby = '".$this->db->idate($sellby)."'"); // deprecated
  337. }
  338. if (!empty($batch_number)) {
  339. $sql .= " AND batch = '".$this->db->escape($batch_number)."'";
  340. }
  341. if (!empty($where)) {
  342. $sql .= " AND (".implode(" OR ", $where).")";
  343. }
  344. dol_syslog(get_class($this)."::fetch", LOG_DEBUG);
  345. $resql = $this->db->query($sql);
  346. if ($resql) {
  347. if ($this->db->num_rows($resql)) {
  348. $obj = $this->db->fetch_object($resql);
  349. $this->id = $obj->rowid;
  350. $this->tms = $this->db->jdate($obj->tms);
  351. $this->fk_product_stock = $obj->fk_product_stock;
  352. $this->sellby = $this->db->jdate($obj->sellby);
  353. $this->eatby = $this->db->jdate($obj->eatby);
  354. $this->batch = $obj->batch;
  355. $this->qty = $obj->qty;
  356. $this->import_key = $obj->import_key;
  357. }
  358. $this->db->free($resql);
  359. return 1;
  360. } else {
  361. $this->error = "Error ".$this->db->lasterror();
  362. return -1;
  363. }
  364. }
  365. /**
  366. * Return all batch detail records for a given product and warehouse
  367. *
  368. * @param DoliDB $dbs database object
  369. * @param int $fk_product_stock id product_stock for objet
  370. * @param int $with_qty 1 = doesn't return line with 0 quantity
  371. * @param int $fk_product If set to a product id, get eatby and sellby from table llx_product_lot
  372. * @return array <0 if KO, array of batch
  373. */
  374. public static function findAll($dbs, $fk_product_stock, $with_qty = 0, $fk_product = 0)
  375. {
  376. global $conf;
  377. $ret = array();
  378. $sql = "SELECT";
  379. $sql .= " t.rowid,";
  380. $sql .= " t.tms,";
  381. $sql .= " t.fk_product_stock,";
  382. $sql .= " t.sellby as oldsellby,"; // deprecated but may not be migrated into new table
  383. $sql .= " t.eatby as oldeatby,"; // deprecated but may not be migrated into new table
  384. $sql .= " t.batch,";
  385. $sql .= " t.qty,";
  386. $sql .= " t.import_key";
  387. if ($fk_product > 0) {
  388. $sql .= ", pl.rowid as lotid, pl.eatby as eatby, pl.sellby as sellby";
  389. // TODO May add extrafields to ?
  390. }
  391. $sql .= " FROM ".$dbs->prefix()."product_batch as t";
  392. if ($fk_product > 0) {
  393. $sql .= " LEFT JOIN ".$dbs->prefix()."product_lot as pl ON pl.fk_product = ".((int) $fk_product)." AND pl.batch = t.batch";
  394. // TODO May add extrafields to ?
  395. }
  396. $sql .= " WHERE fk_product_stock=".((int) $fk_product_stock);
  397. if ($with_qty) {
  398. $sql .= " AND t.qty <> 0";
  399. }
  400. $sql .= " ORDER BY ";
  401. // TODO : use product lifo and fifo when product will implement it
  402. if ($fk_product > 0) { $sql .= "pl.eatby ASC, pl.sellby ASC, "; }
  403. $sql .= "t.eatby ASC, t.sellby ASC ";
  404. $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
  405. dol_syslog("productbatch::findAll", LOG_DEBUG);
  406. $resql = $dbs->query($sql);
  407. if ($resql) {
  408. $num = $dbs->num_rows($resql);
  409. $i = 0;
  410. while ($i < $num) {
  411. $obj = $dbs->fetch_object($resql);
  412. $tmp = new Productbatch($dbs);
  413. $tmp->id = $obj->rowid;
  414. $tmp->lotid = $obj->lotid;
  415. $tmp->tms = $dbs->jdate($obj->tms);
  416. $tmp->fk_product_stock = $obj->fk_product_stock;
  417. $tmp->sellby = $dbs->jdate($obj->sellby ? $obj->sellby : $obj->oldsellby);
  418. $tmp->eatby = $dbs->jdate($obj->eatby ? $obj->eatby : $obj->oldeatby);
  419. $tmp->batch = $obj->batch;
  420. $tmp->qty = $obj->qty;
  421. $tmp->import_key = $obj->import_key;
  422. $ret[$tmp->batch] = $tmp; // $ret is for a $fk_product_stock and unique key is on $fk_product_stock+batch
  423. $i++;
  424. }
  425. $dbs->free($resql);
  426. return $ret;
  427. } else {
  428. $error = "Error ".$dbs->lasterror();
  429. return -1;
  430. }
  431. }
  432. /**
  433. * Return all batch for a product and a warehouse
  434. *
  435. * @param int $fk_product Id of product
  436. * @param int $fk_warehouse Id of warehouse
  437. * @param int $qty_min [=NULL] Minimum quantity
  438. * @param string $sortfield [=NULL] List of sort fields, separated by comma. Example: 't1.fielda,t2.fieldb'
  439. * @param string $sortorder [=NULL] Sort order, separated by comma. Example: 'ASC,DESC';
  440. * @return int|array <0 if KO, array of batch
  441. *
  442. * @throws Exception
  443. */
  444. public function findAllForProduct($fk_product, $fk_warehouse = 0, $qty_min = null, $sortfield = null, $sortorder = null)
  445. {
  446. $productBatchList = array();
  447. dol_syslog(__METHOD__.' fk_product='.$fk_product.', fk_warehouse='.$fk_warehouse.', qty_min='.$qty_min.', sortfield='.$sortfield.', sortorder='.$sortorder, LOG_DEBUG);
  448. $sql = "SELECT";
  449. $sql .= " pl.rowid";
  450. $sql .= ", pl.fk_product";
  451. $sql .= ", pl.batch";
  452. $sql .= ", pl.sellby";
  453. $sql .= ", pl.eatby";
  454. $sql .= ", pb.qty";
  455. $sql .= " FROM ".$this->db->prefix()."product_lot as pl";
  456. $sql .= " LEFT JOIN ".$this->db->prefix()."product as p ON p.rowid = pl.fk_product";
  457. $sql .= " LEFT JOIN ".$this->db->prefix()."product_batch AS pb ON pl.batch = pb.batch";
  458. $sql .= " LEFT JOIN ".$this->db->prefix()."product_stock AS ps ON ps.rowid = pb.fk_product_stock";
  459. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  460. $sql .= " AND pl.fk_product = ".((int) $fk_product);
  461. if ($fk_warehouse > 0) {
  462. $sql .= " AND ps.fk_entrepot = ".((int) $fk_warehouse);
  463. }
  464. if ($qty_min !== null) {
  465. $sql .= " AND pb.qty > ".((float) price2num($qty_min, 'MS'));
  466. }
  467. $sql .= $this->db->order($sortfield, $sortorder);
  468. $resql = $this->db->query($sql);
  469. if ($resql) {
  470. while ($obj = $this->db->fetch_object($resql)) {
  471. $productBatch = new self($this->db);
  472. $productBatch->id = $obj->rowid;
  473. $productBatch->fk_product = $obj->fk_product;
  474. $productBatch->batch = $obj->batch;
  475. $productBatch->eatby = $this->db->jdate($obj->eatby);
  476. $productBatch->sellby = $this->db->jdate($obj->sellby);
  477. $productBatch->qty = $obj->qty;
  478. $productBatchList[] = $productBatch;
  479. }
  480. $this->db->free($resql);
  481. return $productBatchList;
  482. } else {
  483. dol_syslog(__METHOD__.' Error: '.$this->db->lasterror(), LOG_ERR);
  484. return -1;
  485. }
  486. }
  487. }