mouvementstock.class.php 46 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243
  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. *
  7. * This program is free software; you can redistribute it and/or modify
  8. * it under the terms of the GNU General Public License as published by
  9. * the Free Software Foundation; either version 3 of the License, or
  10. * (at your option) any later version.
  11. *
  12. * This program is distributed in the hope that it will be useful,
  13. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. * GNU General Public License for more details.
  16. *
  17. * You should have received a copy of the GNU General Public License
  18. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  19. */
  20. /**
  21. * \file htdocs/product/stock/class/mouvementstock.class.php
  22. * \ingroup stock
  23. * \brief File of class to manage stock movement (input or output)
  24. */
  25. /**
  26. * Class to manage stock movements
  27. */
  28. class MouvementStock extends CommonObject
  29. {
  30. /**
  31. * @var string Id to identify managed objects
  32. */
  33. public $element = 'stockmouvement';
  34. /**
  35. * @var string Name of table without prefix where object is stored
  36. */
  37. public $table_element = 'stock_mouvement';
  38. /**
  39. * @var int ID product
  40. */
  41. public $product_id;
  42. /**
  43. * @var int ID warehouse
  44. */
  45. public $warehouse_id;
  46. public $qty;
  47. /**
  48. * @var int Type of movement
  49. * 0=input (stock increase by a manual/direct stock transfer, correction or inventory),
  50. * 1=output (stock decrease after by a manual/direct stock transfer, correction or inventory),
  51. * 2=output (stock decrease after a business event like sale, shipment or manufacturing, ...),
  52. * 3=input (stock increase after a business event like purchase, reception or manufacturing, ...)
  53. * Note that qty should be > 0 with 0 or 3, < 0 with 1 or 2.
  54. */
  55. public $type;
  56. public $tms = '';
  57. public $datem = '';
  58. public $price;
  59. /**
  60. * @var int ID user author
  61. */
  62. public $fk_user_author;
  63. /**
  64. * @var string stock movements label
  65. */
  66. public $label;
  67. /**
  68. * @var int ID
  69. * @deprecated
  70. * @see $origin_id
  71. */
  72. public $fk_origin;
  73. /**
  74. * @var int Origin id
  75. */
  76. public $origin_id;
  77. /**
  78. * @var string origintype
  79. * @deprecated
  80. * see $origin_type
  81. */
  82. public $origintype;
  83. /**
  84. * @var string Origin type ('project', ...)
  85. */
  86. public $origin_type;
  87. public $inventorycode;
  88. public $batch;
  89. public $fields = array(
  90. 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10, 'showoncombobox'=>1),
  91. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>15),
  92. 'datem' =>array('type'=>'datetime', 'label'=>'Datem', 'enabled'=>1, 'visible'=>-1, 'position'=>20),
  93. 'fk_product' =>array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Product', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>25),
  94. 'fk_entrepot' =>array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Warehouse', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>30),
  95. 'value' =>array('type'=>'double', 'label'=>'Value', 'enabled'=>1, 'visible'=>-1, 'position'=>35),
  96. 'price' =>array('type'=>'double(24,8)', 'label'=>'Price', 'enabled'=>1, 'visible'=>-1, 'position'=>40),
  97. 'type_mouvement' =>array('type'=>'smallint(6)', 'label'=>'Type mouvement', 'enabled'=>1, 'visible'=>-1, 'position'=>45),
  98. 'fk_user_author' =>array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-1, 'position'=>50),
  99. 'label' =>array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>1, 'visible'=>-1, 'position'=>55),
  100. 'fk_origin' =>array('type'=>'integer', 'label'=>'Fk origin', 'enabled'=>1, 'visible'=>-1, 'position'=>60),
  101. 'origintype' =>array('type'=>'varchar(32)', 'label'=>'Origintype', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
  102. 'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'Model pdf', 'enabled'=>1, 'visible'=>0, 'position'=>70),
  103. '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),
  104. 'inventorycode' =>array('type'=>'varchar(128)', 'label'=>'InventoryCode', 'enabled'=>1, 'visible'=>-1, 'position'=>80),
  105. 'batch' =>array('type'=>'varchar(30)', 'label'=>'Batch', 'enabled'=>1, 'visible'=>-1, 'position'=>85),
  106. 'eatby' =>array('type'=>'date', 'label'=>'Eatby', 'enabled'=>1, 'visible'=>-1, 'position'=>90),
  107. 'sellby' =>array('type'=>'date', 'label'=>'Sellby', 'enabled'=>1, 'visible'=>-1, 'position'=>95),
  108. 'fk_project' =>array('type'=>'integer:Project:projet/class/project.class.php:1:fk_statut=1', 'label'=>'Fk project', 'enabled'=>1, 'visible'=>-1, 'position'=>100),
  109. );
  110. /**
  111. * Constructor
  112. *
  113. * @param DoliDB $db Database handler
  114. */
  115. public function __construct($db)
  116. {
  117. $this->db = $db;
  118. }
  119. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
  120. /**
  121. * Add a movement of stock (in one direction only).
  122. * This is the lowest level method to record a stock change.
  123. * $this->origin_type and $this->origin_id can be also be set to save the source object of movement.
  124. *
  125. * @param User $user User object
  126. * @param int $fk_product Id of product
  127. * @param int $entrepot_id Id of warehouse
  128. * @param int $qty Qty of movement (can be <0 or >0 depending on parameter type)
  129. * @param int $type Direction of movement:
  130. * 0=input (stock increase by a stock transfer), 1=output (stock decrease by a stock transfer),
  131. * 2=output (stock decrease), 3=input (stock increase)
  132. * Note that qty should be > 0 with 0 or 3, < 0 with 1 or 2.
  133. * @param int $price Unit price HT of product, used to calculate average weighted price (AWP or PMP in french). If 0, average weighted price is not changed.
  134. * @param string $label Label of stock movement
  135. * @param string $inventorycode Inventory code
  136. * @param integer|string $datem Force date of movement
  137. * @param integer|string $eatby eat-by date. Will be used if lot does not exists yet and will be created.
  138. * @param integer|string $sellby sell-by date. Will be used if lot does not exists yet and will be created.
  139. * @param string $batch batch number
  140. * @param boolean $skip_batch If set to true, stock movement is done without impacting batch record
  141. * @param int $id_product_batch Id product_batch (when skip_batch is false and we already know which record of product_batch to use)
  142. * @param int $disablestockchangeforsubproduct Disable stock change for sub-products of kit (usefull only if product is a subproduct)
  143. * @param int $donotcleanemptylines Do not clean lines in stock table with qty=0 (because we want to have this done by the caller)
  144. * @return int <0 if KO, 0 if fk_product is null or product id does not exists, >0 if OK
  145. */
  146. public function _create($user, $fk_product, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $skip_batch = false, $id_product_batch = 0, $disablestockchangeforsubproduct = 0, $donotcleanemptylines = 0)
  147. {
  148. // phpcs:enable
  149. global $conf, $langs;
  150. require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
  151. require_once DOL_DOCUMENT_ROOT.'/product/stock/class/productlot.class.php';
  152. $error = 0;
  153. 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=".$skip_batch);
  154. // Call hook at beginning
  155. global $action, $hookmanager;
  156. if (empty($hookmanager))
  157. $hookmanager = new HookManager($this->db);
  158. $hookmanager->initHooks(array('mouvementstock'));
  159. if (is_object($hookmanager)) {
  160. $parameters = array(
  161. 'currentcontext' => 'mouvementstock',
  162. 'user' => &$user,
  163. 'fk_product' => &$fk_product,
  164. 'entrepot_id' => &$entrepot_id,
  165. 'qty' => &$qty,
  166. 'type' => &$type,
  167. 'price' => &$price,
  168. 'label' => &$label,
  169. 'inventorycode' => &$inventorycode,
  170. 'datem' => &$datem,
  171. 'eatby' => &$eatby,
  172. 'sellby' => &$sellby,
  173. 'batch' => &$batch,
  174. 'skip_batch' => &$skip_batch,
  175. 'id_product_batch' => &$id_product_batch
  176. );
  177. $reshook = $hookmanager->executeHooks('stockMovementCreate', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  178. if ($reshook < 0) {
  179. if (!empty($hookmanager->resPrint)) {
  180. dol_print_error('', $hookmanager->resPrint);
  181. }
  182. return $reshook;
  183. } elseif ($reshook > 0) {
  184. return $hookmanager->resPrint;
  185. }
  186. }
  187. // end hook at beginning
  188. // Clean parameters
  189. $price = price2num($price, 'MU'); // Clean value for the casse we receive a float zero value, to have it a real zero value.
  190. if (empty($price)) $price = 0;
  191. $now = (!empty($datem) ? $datem : dol_now());
  192. // Check parameters
  193. if (!($fk_product > 0)) return 0;
  194. if (!($entrepot_id > 0)) return 0;
  195. if (is_numeric($eatby) && $eatby < 0) {
  196. dol_syslog(get_class($this)."::_create start ErrorBadValueForParameterEatBy eatby = ".$eatby);
  197. $this->errors[] = 'ErrorBadValueForParameterEatBy';
  198. return -1;
  199. }
  200. if (is_numeric($sellby) && $sellby < 0) {
  201. dol_syslog(get_class($this)."::_create start ErrorBadValueForParameterSellBy sellby = ".$sellby);
  202. $this->errors[] = 'ErrorBadValueForParameterSellBy';
  203. return -1;
  204. }
  205. // Set properties of movement
  206. $this->product_id = $fk_product;
  207. $this->entrepot_id = $entrepot_id; // deprecated
  208. $this->warehouse_id = $entrepot_id;
  209. $this->qty = $qty;
  210. $this->type = $type;
  211. $this->price = price2num($price);
  212. $this->label = $label;
  213. $this->inventorycode = $inventorycode;
  214. $this->datem = $now;
  215. $this->batch = $batch;
  216. $mvid = 0;
  217. $product = new Product($this->db);
  218. $result = $product->fetch($fk_product);
  219. if ($result < 0) {
  220. $this->error = $product->error;
  221. $this->errors = $product->errors;
  222. dol_print_error('', "Failed to fetch product");
  223. return -1;
  224. }
  225. if ($product->id <= 0) { // Can happen if database is corrupted (a product id exist in stock with product that has been removed)
  226. return 0;
  227. }
  228. // Define if we must make the stock change (If product type is a service or if stock is used also for services)
  229. // Only record into stock tables wil be disabled by this (the rest like writing into lot table or movement of subproucts are done)
  230. $movestock = 0;
  231. if ($product->type != Product::TYPE_SERVICE || !empty($conf->global->STOCK_SUPPORTS_SERVICES)) $movestock = 1;
  232. $this->db->begin();
  233. // Set value $product->stock_reel and detail per warehouse into $product->stock_warehouse array
  234. if ($movestock) {
  235. $product->load_stock('novirtual');
  236. }
  237. // Test if product require batch data. If yes, and there is not or values are not correct, we throw an error.
  238. if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) {
  239. if (empty($batch)) {
  240. $langs->load("errors");
  241. $this->errors[] = $langs->transnoentitiesnoconv("ErrorTryToMakeMoveOnProductRequiringBatchData", $product->ref);
  242. dol_syslog("Try to make a movement of a product with status_batch on without any batch data", LOG_ERR);
  243. $this->db->rollback();
  244. return -2;
  245. }
  246. // Check table llx_product_lot from batchnumber for same product
  247. // If found and eatby/sellby defined into table and provided and differs, return error
  248. // If found and eatby/sellby defined into table and not provided, we take value from table
  249. // If found and eatby/sellby not defined into table and provided, we update table
  250. // If found and eatby/sellby not defined into table and not provided, we do nothing
  251. // If not found, we add record
  252. $sql = "SELECT pb.rowid, pb.batch, pb.eatby, pb.sellby FROM ".$this->db->prefix()."product_lot as pb";
  253. $sql .= " WHERE pb.fk_product = ".((int) $fk_product)." AND pb.batch = '".$this->db->escape($batch)."'";
  254. dol_syslog(get_class($this)."::_create scan serial for this product to check if eatby and sellby match", LOG_DEBUG);
  255. $resql = $this->db->query($sql);
  256. if ($resql) {
  257. $num = $this->db->num_rows($resql);
  258. $i = 0;
  259. if ($num > 0) {
  260. while ($i < $num) {
  261. $obj = $this->db->fetch_object($resql);
  262. if ($obj->eatby) {
  263. if ($eatby) {
  264. $tmparray = dol_getdate($eatby, true);
  265. $eatbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
  266. if ($this->db->jdate($obj->eatby) != $eatby && $this->db->jdate($obj->eatby) != $eatbywithouthour) { // We test date without hours and with hours for backward compatibility
  267. // If found and eatby/sellby defined into table and provided and differs, return error
  268. $langs->load("stocks");
  269. $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->eatby), 'dayhour'), dol_print_date($eatbywithouthour, 'dayhour'));
  270. 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);
  271. $this->db->rollback();
  272. return -3;
  273. }
  274. } else {
  275. $eatby = $obj->eatby; // If found and eatby/sellby defined into table and not provided, we take value from table
  276. }
  277. } else {
  278. if ($eatby) { // If found and eatby/sellby not defined into table and provided, we update table
  279. $productlot = new Productlot($this->db);
  280. $result = $productlot->fetch($obj->rowid);
  281. $productlot->eatby = $eatby;
  282. $result = $productlot->update($user);
  283. if ($result <= 0) {
  284. $this->error = $productlot->error;
  285. $this->errors = $productlot->errors;
  286. $this->db->rollback();
  287. return -5;
  288. }
  289. }
  290. }
  291. if ($obj->sellby) {
  292. if ($sellby) {
  293. $tmparray = dol_getdate($sellby, true);
  294. $sellbywithouthour = dol_mktime(0, 0, 0, $tmparray['mon'], $tmparray['mday'], $tmparray['year']);
  295. if ($this->db->jdate($obj->sellby) != $sellby && $this->db->jdate($obj->sellby) != $sellbywithouthour) { // We test date without hours and with hours for backward compatibility
  296. // If found and eatby/sellby defined into table and provided and differs, return error
  297. $this->errors[] = $langs->transnoentitiesnoconv("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby));
  298. dol_syslog($langs->transnoentities("ThisSerialAlreadyExistWithDifferentDate", $batch, dol_print_date($this->db->jdate($obj->sellby)), dol_print_date($sellby)), LOG_ERR);
  299. $this->db->rollback();
  300. return -3;
  301. }
  302. } else {
  303. $sellby = $obj->sellby; // If found and eatby/sellby defined into table and not provided, we take value from table
  304. }
  305. } else {
  306. if ($sellby) { // If found and eatby/sellby not defined into table and provided, we update table
  307. $productlot = new Productlot($this->db);
  308. $result = $productlot->fetch($obj->rowid);
  309. $productlot->sellby = $sellby;
  310. $result = $productlot->update($user);
  311. if ($result <= 0) {
  312. $this->error = $productlot->error;
  313. $this->errors = $productlot->errors;
  314. $this->db->rollback();
  315. return -5;
  316. }
  317. }
  318. }
  319. $i++;
  320. }
  321. } else { // If not found, we add record
  322. $productlot = new Productlot($this->db);
  323. $productlot->entity = $conf->entity;
  324. $productlot->fk_product = $fk_product;
  325. $productlot->batch = $batch;
  326. // If we are here = first time we manage this batch, so we used dates provided by users to create lot
  327. $productlot->eatby = $eatby;
  328. $productlot->sellby = $sellby;
  329. $result = $productlot->create($user);
  330. if ($result <= 0) {
  331. $this->error = $productlot->error;
  332. $this->errors = $productlot->errors;
  333. $this->db->rollback();
  334. return -4;
  335. }
  336. }
  337. } else {
  338. dol_print_error($this->db);
  339. $this->db->rollback();
  340. return -1;
  341. }
  342. }
  343. // Check if stock is enough when qty is < 0
  344. // Note that qty should be > 0 with type 0 or 3, < 0 with type 1 or 2.
  345. if ($movestock && $qty < 0 && empty($conf->global->STOCK_ALLOW_NEGATIVE_TRANSFER)) {
  346. if (!empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) {
  347. $foundforbatch = 0;
  348. $qtyisnotenough = 0;
  349. foreach ($product->stock_warehouse[$entrepot_id]->detail_batch as $batchcursor => $prodbatch) {
  350. if ((string) $batch != (string) $batchcursor) { // Lot '59' must be different than lot '59c'
  351. continue;
  352. }
  353. $foundforbatch = 1;
  354. if ($prodbatch->qty < abs($qty)) $qtyisnotenough = $prodbatch->qty;
  355. break;
  356. }
  357. if (!$foundforbatch || $qtyisnotenough) {
  358. $langs->load("stocks");
  359. include_once DOL_DOCUMENT_ROOT.'/product/stock/class/entrepot.class.php';
  360. $tmpwarehouse = new Entrepot($this->db);
  361. $tmpwarehouse->fetch($entrepot_id);
  362. $this->error = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
  363. $this->errors[] = $langs->trans('qtyToTranferLotIsNotEnough', $product->ref, $batch, $qtyisnotenough, $tmpwarehouse->ref);
  364. $this->db->rollback();
  365. return -8;
  366. }
  367. } else {
  368. if (empty($product->stock_warehouse[$entrepot_id]->real) || $product->stock_warehouse[$entrepot_id]->real < abs($qty)) {
  369. $langs->load("stocks");
  370. $this->error = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
  371. $this->errors[] = $langs->trans('qtyToTranferIsNotEnough').' : '.$product->ref;
  372. $this->db->rollback();
  373. return -8;
  374. }
  375. }
  376. }
  377. if ($movestock) { // Change stock for current product, change for subproduct is done after
  378. // Set $origin_type, origin_id and fk_project
  379. $fk_project = $this->fk_project;
  380. if (!empty($this->origin_type)) { // This is set by caller for tracking reason
  381. $origin_type = $this->origin_type;
  382. $origin_id = $this->origin_id;
  383. if (empty($fk_project) && $origin_type == 'project') {
  384. $fk_project = $origin_id;
  385. $origin_type = '';
  386. $origin_id = 0;
  387. }
  388. } else {
  389. $fk_project = 0;
  390. $origin_type = '';
  391. $origin_id = 0;
  392. }
  393. $sql = "INSERT INTO ".$this->db->prefix()."stock_mouvement(";
  394. $sql .= " datem, fk_product, batch, eatby, sellby,";
  395. $sql .= " fk_entrepot, value, type_mouvement, fk_user_author, label, inventorycode, price, fk_origin, origintype, fk_projet";
  396. $sql .= ")";
  397. $sql .= " VALUES ('".$this->db->idate($this->datem)."', ".((int) $this->product_id).", ";
  398. $sql .= " ".($batch ? "'".$this->db->escape($batch)."'" : "null").", ";
  399. $sql .= " ".($eatby ? "'".$this->db->idate($eatby)."'" : "null").", ";
  400. $sql .= " ".($sellby ? "'".$this->db->idate($sellby)."'" : "null").", ";
  401. $sql .= " ".((int) $this->entrepot_id).", ".((float) $this->qty).", ".((int) $this->type).",";
  402. $sql .= " ".((int) $user->id).",";
  403. $sql .= " '".$this->db->escape($label)."',";
  404. $sql .= " ".($inventorycode ? "'".$this->db->escape($inventorycode)."'" : "null").",";
  405. $sql .= " ".((float) price2num($price)).",";
  406. $sql .= " ".((int) $origin_id).",";
  407. $sql .= " '".$this->db->escape($origin_type)."',";
  408. $sql .= " ".((int) $fk_project);
  409. $sql .= ")";
  410. dol_syslog(get_class($this)."::_create insert record into stock_mouvement", LOG_DEBUG);
  411. $resql = $this->db->query($sql);
  412. if ($resql) {
  413. $mvid = $this->db->last_insert_id($this->db->prefix()."stock_mouvement");
  414. $this->id = $mvid;
  415. } else {
  416. $this->error = $this->db->lasterror();
  417. $this->errors[] = $this->error;
  418. $error = -1;
  419. }
  420. // Define current values for qty and pmp
  421. $oldqty = $product->stock_reel;
  422. $oldpmp = $product->pmp;
  423. $oldqtywarehouse = 0;
  424. // Test if there is already a record for couple (warehouse / product), so later we will make an update or create.
  425. $alreadyarecord = 0;
  426. if (!$error) {
  427. $sql = "SELECT rowid, reel FROM ".$this->db->prefix()."product_stock";
  428. $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product); // This is a unique key
  429. dol_syslog(get_class($this)."::_create check if a record already exists in product_stock", LOG_DEBUG);
  430. $resql = $this->db->query($sql);
  431. if ($resql) {
  432. $obj = $this->db->fetch_object($resql);
  433. if ($obj) {
  434. $alreadyarecord = 1;
  435. $oldqtywarehouse = $obj->reel;
  436. $fk_product_stock = $obj->rowid;
  437. }
  438. $this->db->free($resql);
  439. } else {
  440. $this->errors[] = $this->db->lasterror();
  441. $error = -2;
  442. }
  443. }
  444. // Calculate new AWP (PMP)
  445. $newpmp = 0;
  446. if (!$error) {
  447. if ($type == 0 || $type == 3) {
  448. // After a stock increase
  449. // Note: PMP is calculated on stock input only (type of movement = 0 or 3). If type == 0 or 3, qty should be > 0.
  450. // Note: Price should always be >0 or 0. PMP should be always >0 (calculated on input)
  451. if ($price > 0 || (!empty($conf->global->STOCK_UPDATE_AWP_EVEN_WHEN_ENTRY_PRICE_IS_NULL) && $price == 0)) {
  452. $oldqtytouse = ($oldqty >= 0 ? $oldqty : 0);
  453. // We make a test on oldpmp>0 to avoid to use normal rule on old data with no pmp field defined
  454. if ($oldpmp > 0) {
  455. $newpmp = price2num((($oldqtytouse * $oldpmp) + ($qty * $price)) / ($oldqtytouse + $qty), 'MU');
  456. } else {
  457. $newpmp = $price; // For this product, PMP was not yet set. We set it to input price.
  458. }
  459. //print "oldqtytouse=".$oldqtytouse." oldpmp=".$oldpmp." oldqtywarehousetouse=".$oldqtywarehousetouse." ";
  460. //print "qty=".$qty." newpmp=".$newpmp;
  461. //exit;
  462. } else {
  463. $newpmp = $oldpmp;
  464. }
  465. } elseif ($type == 1 || $type == 2) {
  466. // After a stock decrease, we don't change value of the AWP/PMP of a product.
  467. $newpmp = $oldpmp;
  468. } else {
  469. // Type of movement unknown
  470. $newpmp = $oldpmp;
  471. }
  472. }
  473. // Update stock quantity
  474. if (!$error) {
  475. if ($alreadyarecord > 0) {
  476. $sql = "UPDATE ".$this->db->prefix()."product_stock SET reel = reel + ".((float) $qty);
  477. $sql .= " WHERE fk_entrepot = ".((int) $entrepot_id)." AND fk_product = ".((int) $fk_product);
  478. } else {
  479. $sql = "INSERT INTO ".$this->db->prefix()."product_stock";
  480. $sql .= " (reel, fk_entrepot, fk_product) VALUES ";
  481. $sql .= " (".((float) $qty).", ".((int) $entrepot_id).", ".((int) $fk_product).")";
  482. }
  483. dol_syslog(get_class($this)."::_create update stock value", LOG_DEBUG);
  484. $resql = $this->db->query($sql);
  485. if (!$resql) {
  486. $this->errors[] = $this->db->lasterror();
  487. $error = -3;
  488. } elseif (empty($fk_product_stock)) {
  489. $fk_product_stock = $this->db->last_insert_id($this->db->prefix()."product_stock");
  490. }
  491. }
  492. // Update detail of stock for the lot.
  493. if (!$error && !empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) {
  494. if ($id_product_batch > 0) {
  495. $result = $this->createBatch($id_product_batch, $qty);
  496. } else {
  497. $param_batch = array('fk_product_stock' =>$fk_product_stock, 'batchnumber'=>$batch);
  498. $result = $this->createBatch($param_batch, $qty);
  499. }
  500. if ($result < 0) {
  501. $error++;
  502. }
  503. }
  504. // Update PMP and denormalized value of stock qty at product level
  505. if (!$error) {
  506. $newpmp = price2num($newpmp, 'MU');
  507. // $sql = "UPDATE ".$this->db->prefix()."product SET pmp = ".$newpmp.", stock = ".$this->db->ifsql("stock IS NULL", 0, "stock") . " + ".$qty;
  508. // $sql.= " WHERE rowid = ".((int) $fk_product);
  509. // Update pmp + denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
  510. $sql = "UPDATE ".$this->db->prefix()."product as p SET pmp = ".((float) $newpmp).",";
  511. $sql .= " stock=(SELECT SUM(ps.reel) FROM ".$this->db->prefix()."product_stock as ps WHERE ps.fk_product = p.rowid)";
  512. $sql .= " WHERE rowid = ".((int) $fk_product);
  513. dol_syslog(get_class($this)."::_create update AWP", LOG_DEBUG);
  514. $resql = $this->db->query($sql);
  515. if (!$resql) {
  516. $this->errors[] = $this->db->lasterror();
  517. $error = -4;
  518. }
  519. }
  520. if (empty($donotcleanemptylines) && empty($conf->global->STOCK_KEEP_EMPTY_IN_DB)) {
  521. // 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
  522. // having a lot1/qty=X and lot2/qty=-X, so 0 but we must not loose repartition of different lot.
  523. // Added by MMI Mathieu Moulin iProspective
  524. // DO NOT DELETE STOCK !!
  525. $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)";
  526. $resql = $this->db->query($sql);
  527. // We do not test error, it can fails if there is child in batch details
  528. }
  529. }
  530. // Add movement for sub products (recursive call)
  531. if (!$error && !empty($conf->global->PRODUIT_SOUSPRODUITS) && empty($conf->global->INDEPENDANT_SUBPRODUCT_STOCK) && empty($disablestockchangeforsubproduct)) {
  532. $error = $this->_createSubProduct($user, $fk_product, $entrepot_id, $qty, $type, 0, $label, $inventorycode); // we use 0 as price, because AWP must not change for subproduct
  533. }
  534. if ($movestock && !$error) {
  535. // Call trigger
  536. $result = $this->call_trigger('STOCK_MOVEMENT', $user);
  537. if ($result < 0) $error++;
  538. // End call triggers
  539. // Check unicity for serial numbered equipments once all movement were done.
  540. if (!$error && !empty($conf->productbatch->enabled) && $product->hasbatch() && !$skip_batch) {
  541. if ($product->status_batch == 2 && $qty > 0) { // We check only if we increased qty
  542. if ($this->getBatchCount($fk_product, $batch) > 1) {
  543. $error++;
  544. $this->errors[] = $langs->trans("TooManyQtyForSerialNumber", $product->ref, $batch);
  545. }
  546. }
  547. }
  548. }
  549. if (!$error) {
  550. $this->db->commit();
  551. return $mvid;
  552. } else {
  553. $this->db->rollback();
  554. dol_syslog(get_class($this)."::_create error code=".$error, LOG_ERR);
  555. return -6;
  556. }
  557. }
  558. /**
  559. * Load object in memory from the database
  560. *
  561. * @param int $id Id object
  562. *
  563. * @return int <0 if KO, 0 if not found, >0 if OK
  564. */
  565. public function fetch($id)
  566. {
  567. dol_syslog(__METHOD__, LOG_DEBUG);
  568. $sql = "SELECT";
  569. $sql .= " t.rowid,";
  570. $sql .= " t.tms,";
  571. $sql .= " t.datem,";
  572. $sql .= " t.fk_product,";
  573. $sql .= " t.fk_entrepot,";
  574. $sql .= " t.value,";
  575. $sql .= " t.price,";
  576. $sql .= " t.type_mouvement,";
  577. $sql .= " t.fk_user_author,";
  578. $sql .= " t.label,";
  579. $sql .= " t.fk_origin as origin_id,";
  580. $sql .= " t.origintype as origin_type,";
  581. $sql .= " t.inventorycode,";
  582. $sql .= " t.batch,";
  583. $sql .= " t.eatby,";
  584. $sql .= " t.sellby,";
  585. $sql .= " t.fk_projet as fk_project";
  586. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  587. $sql .= " WHERE t.rowid = ".((int) $id);
  588. $resql = $this->db->query($sql);
  589. if ($resql) {
  590. $numrows = $this->db->num_rows($resql);
  591. if ($numrows) {
  592. $obj = $this->db->fetch_object($resql);
  593. $this->id = $obj->rowid;
  594. $this->product_id = $obj->fk_product;
  595. $this->warehouse_id = $obj->fk_entrepot;
  596. $this->qty = $obj->value;
  597. $this->type = $obj->type_mouvement;
  598. $this->tms = $this->db->jdate($obj->tms);
  599. $this->datem = $this->db->jdate($obj->datem);
  600. $this->price = $obj->price;
  601. $this->fk_user_author = $obj->fk_user_author;
  602. $this->label = $obj->label;
  603. $this->fk_origin = $obj->origin_id; // For backward compatibility
  604. $this->origintype = $obj->origin_type; // For backward compatibility
  605. $this->origin_id = $obj->origin_id;
  606. $this->origin_type = $obj->origin_type;
  607. $this->inventorycode = $obj->inventorycode;
  608. $this->batch = $obj->batch;
  609. $this->eatby = $this->db->jdate($obj->eatby);
  610. $this->sellby = $this->db->jdate($obj->sellby);
  611. $this->fk_project = $obj->fk_project;
  612. }
  613. // Retrieve all extrafield
  614. $this->fetch_optionals();
  615. // $this->fetch_lines();
  616. $this->db->free($resql);
  617. if ($numrows) {
  618. return 1;
  619. } else {
  620. return 0;
  621. }
  622. } else {
  623. $this->errors[] = 'Error '.$this->db->lasterror();
  624. dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
  625. return -1;
  626. }
  627. }
  628. /**
  629. * Create movement in database for all subproducts
  630. *
  631. * @param User $user Object user
  632. * @param int $idProduct Id product
  633. * @param int $entrepot_id Warehouse id
  634. * @param int $qty Quantity
  635. * @param int $type Type
  636. * @param int $price Price
  637. * @param string $label Label of movement
  638. * @param string $inventorycode Inventory code
  639. * @return int <0 if KO, 0 if OK
  640. */
  641. private function _createSubProduct($user, $idProduct, $entrepot_id, $qty, $type, $price = 0, $label = '', $inventorycode = '')
  642. {
  643. global $langs;
  644. $error = 0;
  645. $pids = array();
  646. $pqtys = array();
  647. $sql = "SELECT fk_product_pere, fk_product_fils, qty";
  648. $sql .= " FROM ".$this->db->prefix()."product_association";
  649. $sql .= " WHERE fk_product_pere = ".((int) $idProduct);
  650. $sql .= " AND incdec = 1";
  651. dol_syslog(get_class($this)."::_createSubProduct for parent product ".$idProduct, LOG_DEBUG);
  652. $resql = $this->db->query($sql);
  653. if ($resql) {
  654. $i = 0;
  655. while ($obj = $this->db->fetch_object($resql)) {
  656. $pids[$i] = $obj->fk_product_fils;
  657. $pqtys[$i] = $obj->qty;
  658. $i++;
  659. }
  660. $this->db->free($resql);
  661. } else {
  662. $error = -2;
  663. }
  664. // Create movement for each subproduct
  665. foreach ($pids as $key => $value) {
  666. if (!$error) {
  667. $tmpmove = dol_clone($this, 1);
  668. $result = $tmpmove->_create($user, $pids[$key], $entrepot_id, ($qty * $pqtys[$key]), $type, 0, $label, $inventorycode); // This will also call _createSubProduct making this recursive
  669. if ($result < 0) {
  670. $this->error = $tmpmove->error;
  671. $this->errors = array_merge($this->errors, $tmpmove->errors);
  672. if ($result == -2) {
  673. $this->errors[] = $langs->trans("ErrorNoteAlsoThatSubProductCantBeFollowedByLot");
  674. }
  675. $error = $result;
  676. }
  677. unset($tmpmove);
  678. }
  679. }
  680. return $error;
  681. }
  682. /**
  683. * Decrease stock for product and subproducts
  684. *
  685. * @param User $user Object user
  686. * @param int $fk_product Id product
  687. * @param int $entrepot_id Warehouse id
  688. * @param int $qty Quantity
  689. * @param int $price Price
  690. * @param string $label Label of stock movement
  691. * @param integer|string $datem Force date of movement
  692. * @param integer $eatby eat-by date
  693. * @param integer $sellby sell-by date
  694. * @param string $batch batch number
  695. * @param int $id_product_batch Id product_batch
  696. * @param string $inventorycode Inventory code
  697. * @param int $donotcleanemptylines Do not clean lines that remains in stock table with qty=0 (because we want to have this done by the caller)
  698. * @return int <0 if KO, >0 if OK
  699. */
  700. public function livraison($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $datem = '', $eatby = '', $sellby = '', $batch = '', $id_product_batch = 0, $inventorycode = '', $donotcleanemptylines = 0)
  701. {
  702. global $conf;
  703. $skip_batch = empty($conf->productbatch->enabled);
  704. 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);
  705. }
  706. /**
  707. * Increase stock for product and subproducts
  708. *
  709. * @param User $user Object user
  710. * @param int $fk_product Id product
  711. * @param int $entrepot_id Warehouse id
  712. * @param int $qty Quantity
  713. * @param int $price Price
  714. * @param string $label Label of stock movement
  715. * @param integer|string $eatby eat-by date
  716. * @param integer|string $sellby sell-by date
  717. * @param string $batch batch number
  718. * @param integer|string $datem Force date of movement
  719. * @param int $id_product_batch Id product_batch
  720. * @param string $inventorycode Inventory code
  721. * @param int $donotcleanemptylines Do not clean lines that remains in stock table with qty=0 (because we want to have this done by the caller)
  722. * @return int <0 if KO, >0 if OK
  723. */
  724. public function reception($user, $fk_product, $entrepot_id, $qty, $price = 0, $label = '', $eatby = '', $sellby = '', $batch = '', $datem = '', $id_product_batch = 0, $inventorycode = '', $donotcleanemptylines = 0)
  725. {
  726. global $conf;
  727. $skip_batch = empty($conf->productbatch->enabled);
  728. return $this->_create($user, $fk_product, $entrepot_id, $qty, 3, $price, $label, $inventorycode, $datem, $eatby, $sellby, $batch, $skip_batch, $id_product_batch, 0, $donotcleanemptylines);
  729. }
  730. /**
  731. * Count number of product in stock before a specific date
  732. *
  733. * @param int $productidselected Id of product to count
  734. * @param integer $datebefore Date limit
  735. * @return int Number
  736. */
  737. public function calculateBalanceForProductBefore($productidselected, $datebefore)
  738. {
  739. $nb = 0;
  740. $sql = "SELECT SUM(value) as nb from ".$this->db->prefix()."stock_mouvement";
  741. $sql .= " WHERE fk_product = ".((int) $productidselected);
  742. $sql .= " AND datem < '".$this->db->idate($datebefore)."'";
  743. dol_syslog(get_class($this).__METHOD__.'', LOG_DEBUG);
  744. $resql = $this->db->query($sql);
  745. if ($resql) {
  746. $obj = $this->db->fetch_object($resql);
  747. if ($obj) $nb = $obj->nb;
  748. return (empty($nb) ? 0 : $nb);
  749. } else {
  750. dol_print_error($this->db);
  751. return -1;
  752. }
  753. }
  754. /**
  755. * Create or update batch record (update table llx_product_batch). No check is done here, done by parent.
  756. *
  757. * @param array|int $dluo Could be either
  758. * - int if row id of product_batch table
  759. * - or complete array('fk_product_stock'=>, 'batchnumber'=>)
  760. * @param int $qty Quantity of product with batch number. May be a negative amount.
  761. * @return int <0 if KO, else return productbatch id
  762. */
  763. private function createBatch($dluo, $qty)
  764. {
  765. // Added by MMI Mathieu Moulin iProspective
  766. global $user, $langs, $conf;
  767. $langs->load('productbatch');
  768. $pdluo = new Productbatch($this->db);
  769. $result = 0;
  770. // Try to find an existing record with same batch number or id
  771. if (is_numeric($dluo)) {
  772. $result = $pdluo->fetch($dluo);
  773. if (empty($pdluo->id)) {
  774. // We didn't find the line. May be it was deleted before by a previous move in same transaction.
  775. $this->error = $langs->trans('CantMoveNonExistantSerial');
  776. $this->errors[] = $this->error;
  777. $result = -2;
  778. }
  779. } elseif (is_array($dluo)) {
  780. if (isset($dluo['fk_product_stock'])) {
  781. $vfk_product_stock = $dluo['fk_product_stock'];
  782. $vbatchnumber = $dluo['batchnumber'];
  783. $result = $pdluo->find($vfk_product_stock, '', '', $vbatchnumber); // Search on batch number only (eatby and sellby are deprecated here)
  784. } else {
  785. dol_syslog(get_class($this)."::createBatch array param dluo must contain at least key fk_product_stock", LOG_ERR);
  786. $result = -1;
  787. }
  788. } else {
  789. dol_syslog(get_class($this)."::createBatch error invalid param dluo", LOG_ERR);
  790. $result = -1;
  791. }
  792. if ($result >= 0) {
  793. // No error
  794. if ($pdluo->id > 0) { // product_batch record found
  795. //print "Avant ".$pdluo->qty." Apres ".($pdluo->qty + $qty)."<br>";
  796. $pdluo->qty += $qty;
  797. if ($pdluo->qty == 0) {
  798. // Added by MMI Mathieu Moulin iProspective
  799. // DO NOT DELETE !
  800. if (!empty($conf->global->STOCK_KEEP_EMPTY_IN_DB))
  801. $result = $pdluo->update($user, 1);
  802. else
  803. $result = $pdluo->delete($user, 1);
  804. } else {
  805. $result = $pdluo->update($user, 1);
  806. }
  807. } else { // product_batch record not found
  808. $pdluo->fk_product_stock = $vfk_product_stock;
  809. $pdluo->qty = $qty;
  810. $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.
  811. $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.
  812. $pdluo->batch = $vbatchnumber;
  813. $result = $pdluo->create($user, 1);
  814. if ($result < 0) {
  815. $this->error = $pdluo->error;
  816. $this->errors = $pdluo->errors;
  817. }
  818. }
  819. }
  820. return $result;
  821. }
  822. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  823. /**
  824. * Return Url link of origin object
  825. *
  826. * @param int $origin_id Id origin
  827. * @param int $origin_type Type origin
  828. * @return string
  829. */
  830. public function get_origin($origin_id, $origin_type)
  831. {
  832. // phpcs:enable
  833. $origin = '';
  834. switch ($origin_type) {
  835. case 'commande':
  836. require_once DOL_DOCUMENT_ROOT.'/commande/class/commande.class.php';
  837. $origin = new Commande($this->db);
  838. break;
  839. case 'shipping':
  840. require_once DOL_DOCUMENT_ROOT.'/expedition/class/expedition.class.php';
  841. $origin = new Expedition($this->db);
  842. break;
  843. case 'facture':
  844. require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
  845. $origin = new Facture($this->db);
  846. break;
  847. case 'order_supplier':
  848. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.commande.class.php';
  849. $origin = new CommandeFournisseur($this->db);
  850. break;
  851. case 'invoice_supplier':
  852. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php';
  853. $origin = new FactureFournisseur($this->db);
  854. break;
  855. case 'project':
  856. require_once DOL_DOCUMENT_ROOT.'/projet/class/project.class.php';
  857. $origin = new Project($this->db);
  858. break;
  859. case 'mo':
  860. require_once DOL_DOCUMENT_ROOT.'/mrp/class/mo.class.php';
  861. $origin = new Mo($this->db);
  862. break;
  863. case 'user':
  864. require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
  865. $origin = new User($this->db);
  866. break;
  867. case 'reception':
  868. require_once DOL_DOCUMENT_ROOT.'/reception/class/reception.class.php';
  869. $origin = new Reception($this->db);
  870. break;
  871. case 'inventory':
  872. require_once DOL_DOCUMENT_ROOT.'/product/inventory/class/inventory.class.php';
  873. $origin = new Inventory($this->db);
  874. break;
  875. default:
  876. if ($origin_type) {
  877. // Separate originetype with "@" : left part is class name, right part is module name
  878. $origin_type_array = explode('@', $origin_type);
  879. $classname = ucfirst($origin_type_array[0]);
  880. $modulename = empty($origin_type_array[1]) ? $classname : $origin_type_array[1];
  881. $result = dol_include_once('/'.$modulename.'/class/'.strtolower($classname).'.class.php');
  882. if ($result) {
  883. $classname = ucfirst($classname);
  884. $origin = new $classname($this->db);
  885. }
  886. }
  887. break;
  888. }
  889. if (empty($origin) || !is_object($origin)) {
  890. return '';
  891. }
  892. if ($origin->fetch($origin_id) > 0) {
  893. return $origin->getNomUrl(1);
  894. }
  895. return '';
  896. }
  897. /**
  898. * Set attribute origin_type and fk_origin to object
  899. *
  900. * @param string $origin_element Type of element
  901. * @param int $origin_id Id of element
  902. *
  903. * @return void
  904. */
  905. public function setOrigin($origin_element, $origin_id)
  906. {
  907. $this->origin_type = $origin_element;
  908. $this->origin_id = $origin_id;
  909. // For backward compatibility
  910. $this->origintype = $origin_element;
  911. $this->fk_origin = $origin_id;
  912. }
  913. /**
  914. * Initialise an instance with random values.
  915. * Used to build previews or test instances.
  916. * id must be 0 if object instance is a specimen.
  917. *
  918. * @return void
  919. */
  920. public function initAsSpecimen()
  921. {
  922. global $user, $langs, $conf, $mysoc;
  923. // Initialize parameters
  924. $this->id = 0;
  925. // There is no specific properties. All data into insert are provided as method parameter.
  926. }
  927. /**
  928. * Return html string with picto for type of movement
  929. *
  930. * @param int $withlabel With label
  931. * @return string String with URL
  932. */
  933. public function getTypeMovement($withlabel = 0)
  934. {
  935. global $langs;
  936. $s = '';
  937. switch ($this->type) {
  938. case "0":
  939. $s = '<span class="fa fa-level-down-alt stockmovemententry stockmovementtransfer" title="'.$langs->trans('StockIncreaseAfterCorrectTransfer').'"></span>';
  940. if ($withlabel) {
  941. $s .= $langs->trans('StockIncreaseAfterCorrectTransfer');
  942. }
  943. break;
  944. case "1":
  945. $s = '<span class="fa fa-level-up-alt stockmovementexit stockmovementtransfer" title="'.$langs->trans('StockDecreaseAfterCorrectTransfer').'"></span>';
  946. if ($withlabel) {
  947. $s .= $langs->trans('StockDecreaseAfterCorrectTransfer');
  948. }
  949. break;
  950. case "2":
  951. $s = '<span class="fa fa-long-arrow-alt-up stockmovementexit stockmovement" title="'.$langs->trans('StockDecrease').'"></span>';
  952. if ($withlabel) {
  953. $s .= $langs->trans('StockDecrease');
  954. }
  955. break;
  956. case "3":
  957. $s = '<span class="fa fa-long-arrow-alt-down stockmovemententry stockmovement" title="'.$langs->trans('StockIncrease').'"></span>';
  958. if ($withlabel) {
  959. $s .= $langs->trans('StockIncrease');
  960. }
  961. break;
  962. }
  963. return $s;
  964. }
  965. /**
  966. * Return a link (with optionaly the picto)
  967. * Use this->id,this->lastname, this->firstname
  968. *
  969. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  970. * @param string $option On what the link point to ('' = Tab of stock movement of warehouse, 'movements' = list of movements)
  971. * @param integer $notooltip 1=Disable tooltip
  972. * @param int $maxlen Max length of visible user name
  973. * @param string $morecss Add more css on link
  974. * @return string String with URL
  975. */
  976. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $maxlen = 24, $morecss = '')
  977. {
  978. global $langs, $conf, $db;
  979. $result = '';
  980. $label = img_picto('', 'stock', 'class="pictofixedwidth"').'<u>'.$langs->trans("Movement").' '.$this->id.'</u>';
  981. $label .= '<div width="100%">';
  982. $label .= '<b>'.$langs->trans('Label').':</b> '.$this->label;
  983. $label .= '<br><b>'.$langs->trans('Qty').':</b> '.($this->qty > 0 ? '+' : '').$this->qty;
  984. $label .= '</div>';
  985. // Link to page of warehouse tab
  986. if ($option == 'movements') {
  987. $url = DOL_URL_ROOT.'/product/stock/movement_list.php?search_ref='.$this->id;
  988. } else {
  989. $url = DOL_URL_ROOT.'/product/stock/movement_list.php?id='.$this->warehouse_id.'&msid='.$this->id;
  990. }
  991. $link = '<a href="'.$url.'"'.($notooltip ? '' : ' title="'.dol_escape_htmltag($label, 1).'" class="classfortooltip'.($morecss ? ' '.$morecss : '').'"');
  992. $link .= '>';
  993. $linkend = '</a>';
  994. if ($withpicto) {
  995. $result .= ($link.img_object(($notooltip ? '' : $label), 'stock', ($notooltip ? '' : 'class="classfortooltip"')).$linkend);
  996. if ($withpicto != 2) {
  997. $result .= ' ';
  998. }
  999. }
  1000. $result .= $link.$this->id.$linkend;
  1001. return $result;
  1002. }
  1003. /**
  1004. * Return label statut
  1005. *
  1006. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1007. * @return string Label of status
  1008. */
  1009. public function getLibStatut($mode = 0)
  1010. {
  1011. return $this->LibStatut($mode);
  1012. }
  1013. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1014. /**
  1015. * Renvoi le libelle d'un status donne
  1016. *
  1017. * @param int $mode 0=libelle long, 1=libelle court, 2=Picto + Libelle court, 3=Picto, 4=Picto + Libelle long, 5=Libelle court + Picto
  1018. * @return string Label of status
  1019. */
  1020. public function LibStatut($mode = 0)
  1021. {
  1022. // phpcs:enable
  1023. global $langs;
  1024. if ($mode == 0 || $mode == 1) {
  1025. return $langs->trans('StatusNotApplicable');
  1026. } elseif ($mode == 2) {
  1027. return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
  1028. } elseif ($mode == 3) {
  1029. return img_picto($langs->trans('StatusNotApplicable'), 'statut9');
  1030. } elseif ($mode == 4) {
  1031. return img_picto($langs->trans('StatusNotApplicable'), 'statut9').' '.$langs->trans('StatusNotApplicable');
  1032. } elseif ($mode == 5) {
  1033. return $langs->trans('StatusNotApplicable').' '.img_picto($langs->trans('StatusNotApplicable'), 'statut9');
  1034. }
  1035. }
  1036. /**
  1037. * Create object on disk
  1038. *
  1039. * @param string $modele force le modele a utiliser ('' to not force)
  1040. * @param Translate $outputlangs Object langs to use for output
  1041. * @param int $hidedetails Hide details of lines
  1042. * @param int $hidedesc Hide description
  1043. * @param int $hideref Hide ref
  1044. * @return int 0 if KO, 1 if OK
  1045. */
  1046. public function generateDocument($modele, $outputlangs = '', $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  1047. {
  1048. global $conf, $user, $langs;
  1049. $langs->load("stocks");
  1050. $outputlangs->load("products");
  1051. if (!dol_strlen($modele)) {
  1052. $modele = 'stdmovement';
  1053. if ($this->model_pdf) {
  1054. $modele = $this->model_pdf;
  1055. } elseif (!empty($conf->global->MOUVEMENT_ADDON_PDF)) {
  1056. $modele = $conf->global->MOUVEMENT_ADDON_PDF;
  1057. }
  1058. }
  1059. $modelpath = "core/modules/stock/doc/";
  1060. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  1061. }
  1062. /**
  1063. * Delete object in database
  1064. *
  1065. * @param User $user User that deletes
  1066. * @param bool $notrigger false=launch triggers after, true=disable triggers
  1067. * @return int <0 if KO, >0 if OK
  1068. */
  1069. public function delete(User $user, $notrigger = false)
  1070. {
  1071. return $this->deleteCommon($user, $notrigger);
  1072. //return $this->deleteCommon($user, $notrigger, 1);
  1073. }
  1074. /**
  1075. * Retrieve number of equipments for a product lot/serial
  1076. *
  1077. * @param int $fk_product Product id
  1078. * @param string $batch batch number
  1079. * @return int <0 if KO, number of equipments found if OK
  1080. */
  1081. private function getBatchCount($fk_product, $batch)
  1082. {
  1083. $cpt = 0;
  1084. $sql = "SELECT sum(pb.qty) as cpt";
  1085. $sql .= " FROM ".$this->db->prefix()."product_batch as pb";
  1086. $sql .= " INNER JOIN ".$this->db->prefix()."product_stock as ps ON ps.rowid = pb.fk_product_stock";
  1087. $sql .= " WHERE ps.fk_product = " . ((int) $fk_product);
  1088. $sql .= " AND pb.batch = '" . $this->db->escape($batch) . "'";
  1089. $result = $this->db->query($sql);
  1090. if ($result) {
  1091. if ($this->db->num_rows($result)) {
  1092. $obj = $this->db->fetch_object($result);
  1093. $cpt = $obj->cpt;
  1094. }
  1095. $this->db->free($result);
  1096. } else {
  1097. dol_print_error($this->db);
  1098. return -1;
  1099. }
  1100. return $cpt;
  1101. }
  1102. }