mouvementstock.class.php 46 KB

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