mouvementstock.class.php 48 KB

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