inventory.class.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910
  1. <?php
  2. /* Copyright (C) 2007-2019 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2014-2016 Juanjo Menent <jmenent@2byte.es>
  4. * Copyright (C) 2015 Florian Henry <florian.henry@open-concept.pro>
  5. * Copyright (C) 2015 Raphaël Doursenaud <rdoursenaud@gpcsolutions.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 product/inventory/class/inventory.class.php
  22. * \ingroup inventory
  23. * \brief This file is a CRUD class file for Inventory (Create/Read/Update/Delete)
  24. */
  25. // Put here all includes required by your class file
  26. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  28. //require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
  29. //require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
  30. /**
  31. * Class for Inventory
  32. */
  33. class Inventory extends CommonObject
  34. {
  35. /**
  36. * @var string ID to identify managed object
  37. */
  38. public $element = 'inventory';
  39. /**
  40. * @var string Name of table without prefix where object is stored
  41. */
  42. public $table_element = 'inventory';
  43. /**
  44. * @var int Does inventory support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  45. */
  46. public $ismultientitymanaged = 1;
  47. /**
  48. * @var int Does object support extrafields ? 0=No, 1=Yes
  49. */
  50. public $isextrafieldmanaged = 0;
  51. /**
  52. * @var string String with name of icon for inventory
  53. */
  54. public $picto = 'inventory';
  55. const STATUS_DRAFT = 0; // Draft
  56. const STATUS_VALIDATED = 1; // Inventory is in process
  57. const STATUS_RECORDED = 2; // Inventory is finisged. Stock movement has been recorded.
  58. const STATUS_CANCELED = 9; // Canceled
  59. /**
  60. * 'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
  61. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  62. * 'label' the translation key.
  63. * 'picto' is code of a picto to show before value in forms
  64. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  65. * 'position' is the sort order of field.
  66. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  67. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
  68. * 'noteditable' says if field is not editable (1 or 0)
  69. * 'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
  70. * 'index' if we want an index in database.
  71. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  72. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  73. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  74. * 'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'maxwidth200', 'wordbreak', 'tdoverflowmax200', 'minwidth300 maxwidth500 widthcentpercentminusx'
  75. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  76. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  77. * 'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
  78. * 'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
  79. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  80. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  81. *
  82. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  83. */
  84. // BEGIN MODULEBUILDER PROPERTIES
  85. /**
  86. * @var array Array with all fields and their property
  87. */
  88. public $fields = array(
  89. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',),
  90. 'ref' => array('type'=>'varchar(64)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>10, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>'Reference of object', 'css'=>'maxwidth150'),
  91. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'visible'=>0, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1,),
  92. 'title' => array('type'=>'varchar(255)', 'label'=>'Label', 'visible'=>1, 'enabled'=>1, 'position'=>25, 'css'=>'minwidth300', 'csslist'=>'tdoverflowmax150', 'alwayseditable'=>1),
  93. 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Warehouse', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'index'=>1, 'help'=>'InventoryForASpecificWarehouse', 'picto'=>'stock', 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'csslist'=>'tdoverflowmax150'),
  94. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'get_name_url_params' => '0::0:-1:0::1', 'visible'=>1, 'enabled'=>1, 'position'=>32, 'index'=>1, 'help'=>'InventoryForASpecificProduct', 'picto'=>'product', 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'csslist'=>'tdoverflowmax150'),
  95. 'categories_product' => array('type'=>'chkbxlst:categorie:label:rowid::type=0:0:', 'label'=>'OrProductsWithCategories', 'visible'=>3, 'enabled'=>1, 'position'=>33, 'help'=>'', 'picto'=>'category', 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx'),
  96. 'date_inventory' => array('type'=>'date', 'label'=>'DateValue', 'visible'=>1, 'enabled'=>'$conf->global->STOCK_INVENTORY_ADD_A_VALUE_DATE', 'position'=>35, 'csslist'=>'nowraponall'), // This date is not used so disabled by default.
  97. 'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500, 'csslist'=>'nowraponall'),
  98. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501, 'csslist'=>'nowraponall'),
  99. 'date_validation' => array('type'=>'datetime', 'label'=>'DateValidation', 'visible'=>-2, 'enabled'=>1, 'position'=>502, 'csslist'=>'nowraponall'),
  100. 'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>510, 'foreignkey'=>'user.rowid', 'csslist'=>'tdoverflowmax150'),
  101. 'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'position'=>511, 'csslist'=>'tdoverflowmax150'),
  102. 'fk_user_valid' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserValidation', 'visible'=>-2, 'enabled'=>1, 'position'=>512, 'csslist'=>'tdoverflowmax150'),
  103. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'notnull'=>-1, 'index'=>0, 'position'=>1000),
  104. 'status' => array('type'=>'integer', 'label'=>'Status', 'visible'=>4, 'enabled'=>1, 'position'=>1000, 'notnull'=>1, 'default'=>0, 'index'=>1, 'arrayofkeyval'=>array(0=>'Draft', 1=>'Validated', 2=>'Closed', 9=>'Canceled'))
  105. );
  106. /**
  107. * @var int ID
  108. */
  109. public $rowid;
  110. /**
  111. * @var string Ref
  112. */
  113. public $ref;
  114. /**
  115. * @var int Entity
  116. */
  117. public $entity;
  118. /**
  119. * @var int ID
  120. */
  121. public $fk_warehouse;
  122. /**
  123. * @var int ID
  124. */
  125. public $fk_product;
  126. /**
  127. * @var string Categories id separated by comma
  128. */
  129. public $categories_product;
  130. public $date_inventory;
  131. public $title;
  132. /**
  133. * @var int Status
  134. */
  135. public $status;
  136. /**
  137. * @var integer|string date_creation
  138. */
  139. public $date_creation;
  140. /**
  141. * @var integer|string date_validation
  142. */
  143. public $date_validation;
  144. public $tms;
  145. /**
  146. * @var int ID
  147. */
  148. public $fk_user_creat;
  149. /**
  150. * @var int ID
  151. */
  152. public $fk_user_modif;
  153. /**
  154. * @var int ID
  155. */
  156. public $fk_user_valid;
  157. /**
  158. * @var string import key
  159. */
  160. public $import_key;
  161. // END MODULEBUILDER PROPERTIES
  162. // If this object has a subtable with lines
  163. /**
  164. * @var string Name of subtable line
  165. */
  166. public $table_element_line = 'inventorydet';
  167. /**
  168. * @var string Field with ID of parent key if this field has a parent
  169. */
  170. public $fk_element = 'fk_inventory';
  171. /**
  172. * @var string Name of subtable class that manage subtable lines
  173. */
  174. public $class_element_line = 'Inventoryline';
  175. /**
  176. * @var array List of child tables. To test if we can delete object.
  177. */
  178. protected $childtables = array();
  179. /**
  180. * @var array List of child tables. To know object to delete on cascade.
  181. */
  182. protected $childtablesoncascade = array('inventorydet');
  183. /**
  184. * @var InventoryLine[] Array of subtable lines
  185. */
  186. public $lines = array();
  187. /**
  188. * Constructor
  189. *
  190. * @param DoliDb $db Database handler
  191. */
  192. public function __construct(DoliDB $db)
  193. {
  194. global $conf;
  195. $this->db = $db;
  196. if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID')) {
  197. $this->fields['rowid']['visible'] = 0;
  198. }
  199. if (!isModEnabled('multicompany')) {
  200. $this->fields['entity']['enabled'] = 0;
  201. }
  202. }
  203. /**
  204. * Create object into database
  205. *
  206. * @param User $user User that creates
  207. * @param bool $notrigger false=launch triggers after, true=disable triggers
  208. * @return int Return integer <0 if KO, Id of created object if OK
  209. */
  210. public function create(User $user, $notrigger = false)
  211. {
  212. $result = $this->createCommon($user, $notrigger);
  213. return $result;
  214. }
  215. /**
  216. * Validate inventory (start it)
  217. *
  218. * @param User $user User that creates
  219. * @param bool $notrigger false=launch triggers after, true=disable triggers
  220. * @param int $include_sub_warehouse Include sub warehouses
  221. * @return int Return integer <0 if KO, Id of created object if OK
  222. */
  223. public function validate(User $user, $notrigger = false, $include_sub_warehouse = 0)
  224. {
  225. global $conf;
  226. $this->db->begin();
  227. $result = 0;
  228. if ($this->status == self::STATUS_DRAFT) {
  229. // Delete inventory
  230. $sql = 'DELETE FROM '.$this->db->prefix().'inventorydet WHERE fk_inventory = '.((int) $this->id);
  231. $resql = $this->db->query($sql);
  232. if (!$resql) {
  233. $this->error = $this->db->lasterror();
  234. $this->db->rollback();
  235. return -1;
  236. }
  237. // Scan existing stock to prefill the inventory
  238. $sql = "SELECT ps.rowid, ps.fk_entrepot as fk_warehouse, ps.fk_product, ps.reel,";
  239. $sql .= " pb.batch, pb.qty";
  240. $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
  241. $sql .= " LEFT JOIN ".$this->db->prefix()."product_batch as pb ON pb.fk_product_stock = ps.rowid,";
  242. $sql .= " ".$this->db->prefix()."product as p, ".$this->db->prefix()."entrepot as e";
  243. $sql .= " WHERE p.entity IN (".getEntity('product').")";
  244. $sql .= " AND ps.fk_product = p.rowid AND ps.fk_entrepot = e.rowid";
  245. if (!getDolGlobalString('STOCK_SUPPORTS_SERVICES')) {
  246. $sql .= " AND p.fk_product_type = 0";
  247. }
  248. if ($this->fk_product > 0) {
  249. $sql .= " AND ps.fk_product = ".((int) $this->fk_product);
  250. }
  251. if ($this->fk_warehouse > 0) {
  252. $sql .= " AND (ps.fk_entrepot = ".((int) $this->fk_warehouse);
  253. if (!empty($include_sub_warehouse) && getDolGlobalInt('INVENTORY_INCLUDE_SUB_WAREHOUSE')) {
  254. $TChildWarehouses = array();
  255. $this->getChildWarehouse($this->fk_warehouse, $TChildWarehouses);
  256. $sql .= " OR ps.fk_entrepot IN (".$this->db->sanitize(join(',', $TChildWarehouses)).")";
  257. }
  258. $sql .= ')';
  259. }
  260. if (!empty($this->categories_product)) {
  261. $sql .= " AND EXISTS (";
  262. $sql .= " SELECT cp.fk_product";
  263. $sql .= " FROM ".$this->db->prefix()."categorie_product AS cp";
  264. $sql .= " WHERE cp.fk_product = ps.fk_product";
  265. $sql .= " AND cp.fk_categorie IN (".$this->db->sanitize($this->categories_product).")";
  266. $sql .= ")";
  267. }
  268. if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
  269. $sql .= " AND NOT EXISTS (";
  270. $sql .= " SELECT pa.rowid";
  271. $sql .= " FROM ".$this->db->prefix()."product_association as pa";
  272. $sql .= " WHERE pa.fk_product_pere = ps.fk_product";
  273. $sql .= ")";
  274. }
  275. $inventoryline = new InventoryLine($this->db);
  276. $resql = $this->db->query($sql);
  277. if ($resql) {
  278. $num = $this->db->num_rows($resql);
  279. $i = 0;
  280. while ($i < $num) {
  281. $obj = $this->db->fetch_object($resql);
  282. $inventoryline->fk_inventory = $this->id;
  283. $inventoryline->fk_warehouse = $obj->fk_warehouse;
  284. $inventoryline->fk_product = $obj->fk_product;
  285. $inventoryline->batch = $obj->batch;
  286. $inventoryline->datec = dol_now();
  287. if (isModEnabled('productbatch')) {
  288. $inventoryline->qty_stock = ($obj->batch ? $obj->qty : $obj->reel); // If there is batch detail, we take qty for batch, else global qty
  289. } else {
  290. $inventoryline->qty_stock = $obj->reel;
  291. }
  292. $resultline = $inventoryline->create($user);
  293. if ($resultline <= 0) {
  294. $this->error = $inventoryline->error;
  295. $this->errors = $inventoryline->errors;
  296. $result = -1;
  297. break;
  298. }
  299. $i++;
  300. }
  301. } else {
  302. $result = -1;
  303. $this->error = $this->db->lasterror();
  304. }
  305. }
  306. if ($result >= 0) {
  307. $result = $this->setStatut($this::STATUS_VALIDATED, null, '', 'INVENTORY_VALIDATED');
  308. }
  309. if ($result > 0) {
  310. $this->db->commit();
  311. } else {
  312. $this->db->rollback();
  313. }
  314. return $result;
  315. }
  316. /**
  317. * Go back to draft
  318. *
  319. * @param User $user User that creates
  320. * @param bool $notrigger false=launch triggers after, true=disable triggers
  321. * @return int Return integer <0 if KO, Id of created object if OK
  322. */
  323. public function setDraft(User $user, $notrigger = false)
  324. {
  325. $this->db->begin();
  326. // Delete inventory
  327. $sql = 'DELETE FROM '.$this->db->prefix().'inventorydet WHERE fk_inventory = '.((int) $this->id);
  328. $resql = $this->db->query($sql);
  329. if (!$resql) {
  330. $this->error = $this->db->lasterror();
  331. $this->db->rollback();
  332. return -1;
  333. }
  334. $result = $this->setStatut($this::STATUS_DRAFT, null, '', 'INVENTORY_DRAFT');
  335. if ($result > 0) {
  336. $this->db->commit();
  337. } else {
  338. $this->db->rollback();
  339. }
  340. return $result;
  341. }
  342. /**
  343. * Set to inventory to status "Closed". It means all stock movements were recorded.
  344. *
  345. * @param User $user User that creates
  346. * @param bool $notrigger false=launch triggers after, true=disable triggers
  347. * @return int Return integer <0 if KO, Id of created object if OK
  348. */
  349. public function setRecorded(User $user, $notrigger = false)
  350. {
  351. $this->db->begin();
  352. $result = $this->setStatut($this::STATUS_RECORDED, null, '', 'INVENTORY_RECORDED');
  353. if ($result > 0) {
  354. $this->db->commit();
  355. } else {
  356. $this->db->rollback();
  357. return -1;
  358. }
  359. return $result;
  360. }
  361. /**
  362. * Set to Canceled
  363. *
  364. * @param User $user User that creates
  365. * @param bool $notrigger false=launch triggers after, true=disable triggers
  366. * @return int Return integer <0 if KO, Id of created object if OK
  367. */
  368. public function setCanceled(User $user, $notrigger = false)
  369. {
  370. $this->db->begin();
  371. $result = $this->setStatut($this::STATUS_CANCELED, null, '', 'INVENTORY_CANCELED');
  372. if ($result > 0) {
  373. $this->db->commit();
  374. } else {
  375. $this->db->rollback();
  376. return -1;
  377. }
  378. return $result;
  379. }
  380. /**
  381. * Clone and object into another one
  382. *
  383. * @param User $user User that creates
  384. * @param int $fromid Id of object to clone
  385. * @return mixed New object created, <0 if KO
  386. */
  387. public function createFromClone(User $user, $fromid)
  388. {
  389. global $hookmanager, $langs;
  390. $error = 0;
  391. dol_syslog(__METHOD__, LOG_DEBUG);
  392. $object = new self($this->db);
  393. $this->db->begin();
  394. // Load source object
  395. $object->fetchCommon($fromid);
  396. // Reset some properties
  397. unset($object->id);
  398. unset($object->fk_user_creat);
  399. unset($object->import_key);
  400. // Clear fields
  401. $object->ref = "copy_of_".$object->ref;
  402. $object->title = $langs->trans("CopyOf")." ".$object->title;
  403. // ...
  404. // Create clone
  405. $object->context['createfromclone'] = 'createfromclone';
  406. $result = $object->createCommon($user);
  407. if ($result < 0) {
  408. $error++;
  409. $this->error = $object->error;
  410. $this->errors = $object->errors;
  411. }
  412. unset($object->context['createfromclone']);
  413. // End
  414. if (!$error) {
  415. $this->db->commit();
  416. return $object;
  417. } else {
  418. $this->db->rollback();
  419. return -1;
  420. }
  421. }
  422. /**
  423. * Load object in memory from the database
  424. *
  425. * @param int $id Id object
  426. * @param string $ref Ref
  427. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  428. */
  429. public function fetch($id, $ref = null)
  430. {
  431. $result = $this->fetchCommon($id, $ref);
  432. //if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
  433. return $result;
  434. }
  435. /**
  436. * Load object lines in memory from the database
  437. *
  438. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  439. */
  440. /*public function fetchLines()
  441. {
  442. $this->lines=array();
  443. // Load lines with object MyObjectLine
  444. return count($this->lines)?1:0;
  445. }*/
  446. /**
  447. * Update object into database
  448. *
  449. * @param User $user User that modifies
  450. * @param bool $notrigger false=launch triggers after, true=disable triggers
  451. * @return int Return integer <0 if KO, >0 if OK
  452. */
  453. public function update(User $user, $notrigger = false)
  454. {
  455. return $this->updateCommon($user, $notrigger);
  456. }
  457. /**
  458. * Delete object in database
  459. *
  460. * @param User $user User that deletes
  461. * @param bool $notrigger false=launch triggers after, true=disable triggers
  462. * @return int Return integer <0 if KO, >0 if OK
  463. */
  464. public function delete(User $user, $notrigger = false)
  465. {
  466. return $this->deleteCommon($user, $notrigger);
  467. }
  468. /**
  469. * Delete a line of object in database
  470. *
  471. * @param User $user User that delete
  472. * @param int $idline Id of line to delete
  473. * @param bool $notrigger false=launch triggers after, true=disable triggers
  474. * @return int >0 if OK, <0 if KO
  475. */
  476. public function deleteLine(User $user, $idline, $notrigger = false)
  477. {
  478. if ($this->status < 0) {
  479. $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
  480. return -2;
  481. }
  482. return $this->deleteLineCommon($user, $idline, $notrigger);
  483. }
  484. /**
  485. * Return a link to the object card (with optionaly the picto)
  486. *
  487. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  488. * @param string $option On what the link point to
  489. * @param int $notooltip 1=Disable tooltip
  490. * @param string $morecss Add more css on link
  491. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  492. * @return string String with URL
  493. */
  494. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  495. {
  496. global $db, $conf, $langs;
  497. global $dolibarr_main_authentication, $dolibarr_main_demo;
  498. global $menumanager;
  499. if (!empty($conf->dol_no_mouse_hover)) {
  500. $notooltip = 1; // Force disable tooltips
  501. }
  502. $result = '';
  503. $companylink = '';
  504. $label = '<u>'.$langs->trans("Inventory").'</u>';
  505. $label .= '<br>';
  506. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  507. $url = dol_buildpath('/product/inventory/card.php', 1).'?id='.$this->id;
  508. $linkclose = '';
  509. if (empty($notooltip)) {
  510. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  511. $label = $langs->trans("ShowInventory");
  512. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  513. }
  514. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  515. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  516. } else {
  517. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  518. }
  519. $linkstart = '<a href="'.$url.'"';
  520. $linkstart .= $linkclose.'>';
  521. $linkend = '</a>';
  522. $result .= $linkstart;
  523. if ($withpicto) {
  524. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
  525. }
  526. if ($withpicto != 2) {
  527. $result .= $this->ref;
  528. }
  529. $result .= $linkend;
  530. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  531. return $result;
  532. }
  533. /**
  534. * Return the label of the status
  535. *
  536. * @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
  537. * @return string Label of status
  538. */
  539. public function getLibStatut($mode = 0)
  540. {
  541. return $this->LibStatut($this->status, $mode);
  542. }
  543. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  544. /**
  545. * Return the status
  546. *
  547. * @param int $status Id status
  548. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 5=Long label + Picto, 6=Long label + Picto
  549. * @return string Label of status
  550. */
  551. public static function LibStatut($status, $mode = 0)
  552. {
  553. // phpcs:enable
  554. global $langs;
  555. $labelStatus = array();
  556. $labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  557. $labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Validated').' ('.$langs->transnoentitiesnoconv('InventoryStartedShort').')';
  558. $labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
  559. $labelStatus[self::STATUS_RECORDED] = $langs->transnoentitiesnoconv('Closed');
  560. $labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  561. $labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('InventoryStartedShort');
  562. $labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Canceled');
  563. $labelStatusShort[self::STATUS_RECORDED] = $langs->transnoentitiesnoconv('Closed');
  564. $statusType = 'status'.$status;
  565. if ($status == self::STATUS_RECORDED) {
  566. $statusType = 'status6';
  567. }
  568. return dolGetStatus($labelStatus[$status], $labelStatusShort[$status], '', $statusType, $mode);
  569. }
  570. /**
  571. * Return a thumb for kanban views
  572. *
  573. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  574. * @param array $arraydata Array of data
  575. * @return string HTML Code for Kanban thumb.
  576. */
  577. public function getKanbanView($option = '', $arraydata = null)
  578. {
  579. global $conf, $langs;
  580. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  581. $return = '<div class="box-flex-item box-flex-grow-zero">';
  582. $return .= '<div class="info-box info-box-sm">';
  583. $return .= '<span class="info-box-icon bg-infobox-action">';
  584. $return .= img_picto('', $this->picto);
  585. $return .= '</span>';
  586. $return .= '<div class="info-box-content">';
  587. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  588. if ($selected >= 0) {
  589. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  590. }
  591. if (property_exists($this, 'label')) {
  592. $return .= ' <div class="inline-block opacitymedium valignmiddle tdoverflowmax100">'.$this->label.'</div>';
  593. }
  594. if (property_exists($this, 'amount')) {
  595. $return .= '<br>';
  596. $return .= '<span class="info-box-label amount">'.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).'</span>';
  597. }
  598. if (method_exists($this, 'getLibStatut')) {
  599. $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
  600. }
  601. $return .= '</div>';
  602. $return .= '</div>';
  603. $return .= '</div>';
  604. return $return;
  605. }
  606. /**
  607. * Charge les informations d'ordre info dans l'objet commande
  608. *
  609. * @param int $id Id of order
  610. * @return void
  611. */
  612. public function info($id)
  613. {
  614. $sql = "SELECT rowid, date_creation as datec, tms as datem, date_validation as datev,";
  615. $sql .= " fk_user_creat, fk_user_modif, fk_user_valid";
  616. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  617. $sql .= " WHERE t.rowid = ".((int) $id);
  618. $result = $this->db->query($sql);
  619. if ($result) {
  620. if ($this->db->num_rows($result)) {
  621. $obj = $this->db->fetch_object($result);
  622. $this->id = $obj->rowid;
  623. $this->user_creation_id = $obj->fk_user_creat;
  624. $this->user_modification_id = $obj->fk_user_modif;
  625. $this->user_validation_id = $obj->fk_user_valid;
  626. $this->date_creation = $this->db->jdate($obj->datec);
  627. $this->date_modification = $this->db->jdate($obj->datem);
  628. $this->date_validation = $this->db->jdate($obj->datev);
  629. }
  630. $this->db->free($result);
  631. } else {
  632. dol_print_error($this->db);
  633. }
  634. }
  635. /**
  636. * Initialise object with example values
  637. * Id must be 0 if object instance is a specimen
  638. *
  639. * @return void
  640. */
  641. public function initAsSpecimen()
  642. {
  643. $this->initAsSpecimenCommon();
  644. $this->title = '';
  645. }
  646. /**
  647. * Return the child warehouse of the current one
  648. *
  649. * @param int $id Id of warehouse
  650. * @param array $TChildWarehouse Array of child warehouses
  651. * @return int Return integer <0 if KO, >0 if OK
  652. */
  653. public function getChildWarehouse($id, &$TChildWarehouse)
  654. {
  655. $sql = 'SELECT rowid FROM '.MAIN_DB_PREFIX.'entrepot';
  656. $sql.= ' WHERE fk_parent='.(int) $id;
  657. $sql.= ' ORDER BY rowid';
  658. $resql = $this->db->query($sql);
  659. if ($resql && $this->db->num_rows($resql)>0) {
  660. while ($obj = $this->db->fetch_object($resql)) {
  661. $TChildWarehouse[] = $obj->rowid;
  662. $this->getChildWarehouse($obj->rowid, $TChildWarehouse);
  663. }
  664. return 1;
  665. } else {
  666. return -1;
  667. }
  668. }
  669. }
  670. /**
  671. * Class InventoryLine
  672. */
  673. class InventoryLine extends CommonObjectLine
  674. {
  675. /**
  676. * @var string ID to identify managed object
  677. */
  678. public $element = 'inventoryline';
  679. /**
  680. * @var string Name of table without prefix where object is stored
  681. */
  682. public $table_element = 'inventorydet';
  683. /**
  684. * @var int Does inventory support multicompany module ? 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  685. */
  686. public $ismultientitymanaged = 0;
  687. /**
  688. * @var int Does object support extrafields ? 0=No, 1=Yes
  689. */
  690. public $isextrafieldmanaged = 0;
  691. /**
  692. * @var string String with name of icon for inventory
  693. */
  694. public $picto = 'stock';
  695. /**
  696. * 'type' if the field format.
  697. * 'label' the translation key.
  698. * 'enabled' is a condition when the field must be managed.
  699. * 'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only. Using a negative value means field is not shown by default on list but can be selected for viewing)
  700. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  701. * 'index' if we want an index in database.
  702. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  703. * 'position' is the sort order of field.
  704. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  705. * 'isameasure' must be set to 1 if you want to have a total on list for this field. Field type must be summable like integer or double(24,8).
  706. * 'help' is a string visible as a tooltip on field
  707. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  708. * 'default' is a default value for creation (can still be replaced by the global setup of default values)
  709. * 'showoncombobox' if field must be shown into the label of combobox
  710. */
  711. // BEGIN MODULEBUILDER PROPERTIES
  712. /**
  713. * @var array Array with all fields and their property
  714. */
  715. public $fields = array(
  716. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'visible'=>-1, 'enabled'=>1, 'position'=>1, 'notnull'=>1, 'index'=>1, 'comment'=>'Id',),
  717. 'fk_inventory' => array('type'=>'integer:Inventory:product/inventory/class/inventory.class.php', 'label'=>'Inventory', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'index'=>1, 'help'=>'LinkToInventory'),
  718. 'fk_warehouse' => array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php', 'label'=>'Warehouse', 'visible'=>1, 'enabled'=>1, 'position'=>30, 'index'=>1, 'help'=>'LinkToThirdparty'),
  719. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php', 'label'=>'Product', 'visible'=>1, 'enabled'=>1, 'position'=>32, 'index'=>1, 'help'=>'LinkToProduct'),
  720. 'batch' => array('type'=>'string', 'label'=>'Batch', 'visible'=>1, 'enabled'=>1, 'position'=>32, 'index'=>1, 'help'=>'LinkToProduct'),
  721. 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>500),
  722. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>501),
  723. 'qty_stock' => array('type'=>'double', 'label'=>'QtyFound', 'visible'=>1, 'enabled'=>1, 'position'=>32, 'index'=>1, 'help'=>'Qty we found/want (to define during draft edition)'),
  724. 'qty_view' => array('type'=>'double', 'label'=>'QtyBefore', 'visible'=>1, 'enabled'=>1, 'position'=>33, 'index'=>1, 'help'=>'Qty before (filled once movements are validated)'),
  725. 'qty_regulated' => array('type'=>'double', 'label'=>'QtyDelta', 'visible'=>1, 'enabled'=>1, 'position'=>34, 'index'=>1, 'help'=>'Qty aadded or removed (filled once movements are validated)'),
  726. 'pmp_real' => array('type'=>'double', 'label'=>'PMPReal', 'visible'=>1, 'enabled'=>1, 'position'=>35),
  727. 'pmp_expected' => array('type'=>'double', 'label'=>'PMPExpected', 'visible'=>1, 'enabled'=>1, 'position'=>36),
  728. );
  729. /**
  730. * @var int ID
  731. */
  732. public $rowid;
  733. public $fk_inventory;
  734. public $fk_warehouse;
  735. public $fk_product;
  736. public $batch;
  737. public $datec;
  738. public $tms;
  739. public $qty_stock;
  740. public $qty_view;
  741. public $qty_regulated;
  742. public $pmp_real;
  743. public $pmp_expected;
  744. /**
  745. * Create object in database
  746. *
  747. * @param User $user User that creates
  748. * @param bool $notrigger false=launch triggers after, true=disable triggers
  749. * @return int Return integer <0 if KO, >0 if OK
  750. */
  751. public function create(User $user, $notrigger = false)
  752. {
  753. return $this->createCommon($user, $notrigger);
  754. }
  755. /**
  756. * Load object in memory from the database
  757. *
  758. * @param int $id Id object
  759. * @param string $ref Ref
  760. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  761. */
  762. public function fetch($id, $ref = null)
  763. {
  764. $result = $this->fetchCommon($id, $ref);
  765. //if ($result > 0 && !empty($this->table_element_line)) $this->fetchLines();
  766. return $result;
  767. }
  768. /**
  769. * Update object into database
  770. *
  771. * @param User $user User that modifies
  772. * @param bool $notrigger false=launch triggers after, true=disable triggers
  773. * @return int Return integer <0 if KO, >0 if OK
  774. */
  775. public function update(User $user, $notrigger = false)
  776. {
  777. return $this->updateCommon($user, $notrigger);
  778. }
  779. /**
  780. * Delete object in database
  781. *
  782. * @param User $user User that deletes
  783. * @param bool $notrigger false=launch triggers after, true=disable triggers
  784. * @return int Return integer <0 if KO, >0 if OK
  785. */
  786. public function delete(User $user, $notrigger = false)
  787. {
  788. return $this->deleteCommon($user, $notrigger);
  789. //return $this->deleteCommon($user, $notrigger, 1);
  790. }
  791. }