entrepot.class.php 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018
  1. <?php
  2. /* Copyright (C) 2003-2006 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  3. * Copyright (C) 2004-2010 Laurent Destailleur <eldy@users.sourceforge.net>
  4. * Copyright (C) 2005-2008 Regis Houssin <regis.houssin@inodbox.com>
  5. * Copyright (C) 2011 Juanjo Menent <jmenent@2byte.es>
  6. * Copyright (C) 2016 Francis Appels <francis.appels@yahoo.com>
  7. * Copyright (C) 2019-2023 Frédéric France <frederic.france@netlogic.fr>
  8. *
  9. * This program is free software; you can redistribute it and/or modify
  10. * it under the terms of the GNU General Public License as published by
  11. * the Free Software Foundation; either version 3 of the License, or
  12. * (at your option) any later version.
  13. *
  14. * This program is distributed in the hope that it will be useful,
  15. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  17. * GNU General Public License for more details.
  18. *
  19. * You should have received a copy of the GNU General Public License
  20. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  21. */
  22. /**
  23. * \file htdocs/product/stock/class/entrepot.class.php
  24. * \ingroup stock
  25. * \brief Fichier de la classe de gestion des entrepots
  26. */
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  28. /**
  29. * Class to manage warehouses
  30. */
  31. class Entrepot extends CommonObject
  32. {
  33. /**
  34. * @var string ID to identify managed object
  35. */
  36. public $element = 'stock';
  37. /**
  38. * @var string Name of table without prefix where object is stored
  39. */
  40. public $table_element = 'entrepot';
  41. /**
  42. * @var string String with name of icon for myobject. Must be the part after the 'object_' into object_myobject.png
  43. */
  44. public $picto = 'stock';
  45. /**
  46. * @var int 0=No test on entity, 1=Test with field entity, 2=Test with link by societe
  47. */
  48. public $ismultientitymanaged = 1;
  49. /**
  50. * @var string Label
  51. * @deprecated
  52. * @see $label
  53. */
  54. public $libelle;
  55. /**
  56. * @var string Label
  57. */
  58. public $label;
  59. /**
  60. * @var string description
  61. */
  62. public $description;
  63. public $statut;
  64. /**
  65. * @var string Place
  66. */
  67. public $lieu;
  68. /**
  69. * @var string Address
  70. */
  71. public $address;
  72. /**
  73. * @var string Zipcode
  74. */
  75. public $zip;
  76. /**
  77. * @var string Town
  78. */
  79. public $town;
  80. /**
  81. * @var string Phone
  82. */
  83. public $phone;
  84. /**
  85. * @var string Fax
  86. */
  87. public $fax;
  88. /**
  89. * @var int ID of parent
  90. */
  91. public $fk_parent;
  92. /**
  93. * @var int ID of project
  94. */
  95. public $fk_project;
  96. /**
  97. * @var array List of short language codes for status
  98. */
  99. public $labelStatus = array();
  100. /**
  101. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  102. */
  103. public $fields = array(
  104. 'rowid' =>array('type'=>'integer', 'label'=>'ID', 'enabled'=>1, 'visible'=>0, 'notnull'=>1, 'position'=>10),
  105. 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'enabled'=>1, 'visible'=>0, 'default'=>1, 'notnull'=>1, 'index'=>1, 'position'=>15),
  106. 'ref' =>array('type'=>'varchar(255)', 'label'=>'Ref', 'enabled'=>1, 'visible'=>1, 'showoncombobox'=>1, 'position'=>25, 'searchall'=>1),
  107. 'description' =>array('type'=>'text', 'label'=>'Description', 'enabled'=>1, 'visible'=>-2, 'position'=>35, 'searchall'=>1),
  108. 'lieu' =>array('type'=>'varchar(64)', 'label'=>'LocationSummary', 'enabled'=>1, 'visible'=>1, 'position'=>40, 'showoncombobox'=>2, 'searchall'=>1),
  109. 'fk_parent' =>array('type'=>'integer:Entrepot:product/stock/class/entrepot.class.php:1:((statut:=:1) AND (entity:IN:__SHARED_ENTITIES__))', 'label'=>'ParentWarehouse', 'enabled'=>1, 'visible'=>-2, 'position'=>41),
  110. 'fk_project' =>array('type'=>'integer:Project:projet/class/project.class.php:1:(fk_statut:=:1)', 'label'=>'Project', 'enabled'=>'$conf->project->enabled', 'visible'=>-1, 'position'=>25),
  111. 'address' =>array('type'=>'varchar(255)', 'label'=>'Address', 'enabled'=>1, 'visible'=>-2, 'position'=>45, 'searchall'=>1),
  112. 'zip' =>array('type'=>'varchar(10)', 'label'=>'Zip', 'enabled'=>1, 'visible'=>-2, 'position'=>50, 'searchall'=>1),
  113. 'town' =>array('type'=>'varchar(50)', 'label'=>'Town', 'enabled'=>1, 'visible'=>-2, 'position'=>55, 'searchall'=>1),
  114. 'fk_departement' =>array('type'=>'integer', 'label'=>'State', 'enabled'=>1, 'visible'=>0, 'position'=>60),
  115. 'fk_pays' =>array('type'=>'integer:Ccountry:core/class/ccountry.class.php', 'label'=>'Country', 'enabled'=>1, 'visible'=>-1, 'position'=>65),
  116. 'phone' =>array('type'=>'varchar(20)', 'label'=>'Phone', 'enabled'=>1, 'visible'=>-2, 'position'=>70, 'searchall'=>1),
  117. 'fax' =>array('type'=>'varchar(20)', 'label'=>'Fax', 'enabled'=>1, 'visible'=>-2, 'position'=>75, 'searchall'=>1),
  118. //'fk_user_author' =>array('type'=>'integer', 'label'=>'Fk user author', 'enabled'=>1, 'visible'=>-2, 'position'=>82),
  119. 'datec' =>array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>1, 'visible'=>-2, 'position'=>300),
  120. 'tms' =>array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>1, 'visible'=>-2, 'notnull'=>1, 'position'=>301),
  121. 'warehouse_usage' => array('type'=>'integer', 'label' => 'WarehouseUsage', 'enabled'=>'getDolGlobalInt("MAIN_FEATURES_LEVEL")', 'visible'=>1, 'position'=>400, 'arrayofkeyval'=>array(1=>'InternalWarehouse', 2=>'ExternalWarehouse')),
  122. //'import_key' =>array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>1, 'visible'=>-2, 'position'=>1000),
  123. //'model_pdf' =>array('type'=>'varchar(255)', 'label'=>'ModelPDF', 'enabled'=>1, 'visible'=>0, 'position'=>1010),
  124. 'statut' =>array('type'=>'tinyint(4)', 'label'=>'Status', 'enabled'=>1, 'visible'=>1, 'position'=>500, 'css'=>'minwidth50'),
  125. );
  126. /**
  127. * Warehouse closed, inactive
  128. */
  129. const STATUS_CLOSED = 0;
  130. /**
  131. * Warehouse open and any operations are allowed (customer shipping, supplier dispatch, internal stock transfers/corrections).
  132. */
  133. const STATUS_OPEN_ALL = 1;
  134. /**
  135. * Warehouse open and only operations for stock transfers/corrections allowed (not for customer shipping and supplier dispatch).
  136. */
  137. const STATUS_OPEN_INTERNAL = 2;
  138. /**
  139. * Warehouse open and any operations are allowed, but warehouse is not included into calculation of stock.
  140. */
  141. const STATUS_OPENEXT_ALL = 3; // TODO Implement this
  142. /**
  143. * Constructor
  144. *
  145. * @param DoliDB $db Database handler
  146. */
  147. public function __construct($db)
  148. {
  149. global $conf;
  150. $this->db = $db;
  151. $this->labelStatus[self::STATUS_CLOSED] = 'Closed2';
  152. if (getDolGlobalString('ENTREPOT_EXTRA_STATUS')) {
  153. $this->labelStatus[self::STATUS_OPEN_ALL] = 'OpenAnyMovement';
  154. $this->labelStatus[self::STATUS_OPEN_INTERNAL] = 'OpenInternal';
  155. } else {
  156. $this->labelStatus[self::STATUS_OPEN_ALL] = 'Opened';
  157. }
  158. }
  159. /**
  160. * Creation d'un entrepot en base
  161. *
  162. * @param User $user Object user that create the warehouse
  163. * @param bool $notrigger false=launch triggers after, true=disable triggers
  164. * @return int >0 if OK, =<0 if KO
  165. */
  166. public function create($user, $notrigger = false)
  167. {
  168. global $conf;
  169. $error = 0;
  170. $this->label = trim($this->label);
  171. // Error if label not defined
  172. if ($this->label == '') {
  173. $this->error = "ErrorFieldRequired";
  174. return 0;
  175. }
  176. $now = dol_now();
  177. $this->db->begin();
  178. $sql = "INSERT INTO ".$this->db->prefix()."entrepot (ref, entity, datec, fk_user_author, fk_parent, fk_project)";
  179. $sql .= " VALUES ('".$this->db->escape($this->label)."', ".((int) $conf->entity).", '".$this->db->idate($now)."', ".((int) $user->id).", ".($this->fk_parent > 0 ? ((int) $this->fk_parent) : "NULL").", ".($this->fk_project > 0 ? ((int) $this->fk_project) : "NULL").")";
  180. dol_syslog(get_class($this)."::create", LOG_DEBUG);
  181. $result = $this->db->query($sql);
  182. if ($result) {
  183. $id = $this->db->last_insert_id($this->db->prefix()."entrepot");
  184. if ($id > 0) {
  185. $this->id = $id;
  186. if (!$error) {
  187. $result = $this->update($id, $user);
  188. if ($result <= 0) {
  189. $error++;
  190. }
  191. }
  192. // Actions on extra fields
  193. if (!$error) {
  194. $result = $this->insertExtraFields();
  195. if ($result < 0) {
  196. $error++;
  197. }
  198. }
  199. if (!$error && !$notrigger) {
  200. // Call triggers
  201. $result = $this->call_trigger('WAREHOUSE_CREATE', $user);
  202. if ($result < 0) {
  203. $error++;
  204. }
  205. // End call triggers
  206. }
  207. if (!$error) {
  208. $this->db->commit();
  209. return $id;
  210. } else {
  211. dol_syslog(get_class($this)."::create return -3");
  212. $this->db->rollback();
  213. return -3;
  214. }
  215. } else {
  216. $this->error = "Failed to get insert id";
  217. dol_syslog(get_class($this)."::create return -2");
  218. return -2;
  219. }
  220. } else {
  221. $this->error = $this->db->error();
  222. dol_syslog(get_class($this)."::create Error ".$this->db->error());
  223. $this->db->rollback();
  224. return -1;
  225. }
  226. }
  227. /**
  228. * Update properties of a warehouse
  229. *
  230. * @param int $id id of warehouse to modify
  231. * @param User $user User object
  232. * @param bool $notrigger false=launch triggers after, true=disable trigge
  233. * @return int >0 if OK, <0 if KO
  234. */
  235. public function update($id, $user, $notrigger = false)
  236. {
  237. global $conf;
  238. $error = 0;
  239. if (empty($id)) {
  240. $id = $this->id;
  241. }
  242. // Check if new parent is already a child of current warehouse
  243. if (!empty($this->fk_parent)) {
  244. $TChildWarehouses = array($id);
  245. $TChildWarehouses = $this->get_children_warehouses($this->id, $TChildWarehouses);
  246. if (in_array($this->fk_parent, $TChildWarehouses)) {
  247. $this->error = 'ErrorCannotAddThisParentWarehouse';
  248. return -2;
  249. }
  250. }
  251. $this->label = trim($this->label);
  252. $this->description = trim($this->description);
  253. $this->lieu = trim($this->lieu);
  254. $this->address = trim($this->address);
  255. $this->zip = trim($this->zip);
  256. $this->town = trim($this->town);
  257. $this->country_id = ($this->country_id > 0 ? $this->country_id : 0);
  258. $sql = "UPDATE ".$this->db->prefix()."entrepot";
  259. $sql .= " SET ref = '".$this->db->escape($this->label)."'";
  260. $sql .= ", fk_parent = ".(($this->fk_parent > 0) ? $this->fk_parent : "NULL");
  261. $sql .= ", fk_project = ".(($this->fk_project > 0) ? $this->fk_project : "NULL");
  262. $sql .= ", description = '".$this->db->escape($this->description)."'";
  263. $sql .= ", statut = ".((int) $this->statut);
  264. $sql .= ", lieu = '".$this->db->escape($this->lieu)."'";
  265. $sql .= ", address = '".$this->db->escape($this->address)."'";
  266. $sql .= ", zip = '".$this->db->escape($this->zip)."'";
  267. $sql .= ", town = '".$this->db->escape($this->town)."'";
  268. $sql .= ", fk_pays = ".((int) $this->country_id);
  269. $sql .= ", phone = '".$this->db->escape($this->phone)."'";
  270. $sql .= ", fax = '".$this->db->escape($this->fax)."'";
  271. $sql .= " WHERE rowid = ".((int) $id);
  272. $this->db->begin();
  273. dol_syslog(get_class($this)."::update", LOG_DEBUG);
  274. $resql = $this->db->query($sql);
  275. if (!$resql) {
  276. $error++;
  277. $this->errors[] = "Error ".$this->db->lasterror();
  278. }
  279. if (!$error) {
  280. $result = $this->insertExtraFields();
  281. if ($result < 0) {
  282. $error++;
  283. }
  284. }
  285. if (!$error && !$notrigger) {
  286. // Call triggers
  287. $result = $this->call_trigger('WAREHOUSE_MODIFY', $user);
  288. if ($result < 0) {
  289. $error++;
  290. }
  291. // End call triggers
  292. }
  293. if (!$error) {
  294. $this->db->commit();
  295. return 1;
  296. } else {
  297. $this->db->rollback();
  298. $this->error = $this->db->lasterror();
  299. return -1;
  300. }
  301. }
  302. /**
  303. * Delete a warehouse
  304. *
  305. * @param User $user Object user that made deletion
  306. * @param int $notrigger 1=No trigger
  307. * @return int Return integer <0 if KO, >0 if OK
  308. */
  309. public function delete($user, $notrigger = 0)
  310. {
  311. global $conf;
  312. $error = 0;
  313. dol_syslog(get_class($this)."::delete id=".$this->id, LOG_DEBUG);
  314. $this->db->begin();
  315. if (!$error && empty($notrigger)) {
  316. // Call trigger
  317. $result = $this->call_trigger('WAREHOUSE_DELETE', $user);
  318. if ($result < 0) {
  319. $error++;
  320. }
  321. // End call triggers
  322. }
  323. if (!$error) {
  324. $sql = "DELETE FROM ".$this->db->prefix()."product_batch";
  325. $sql .= " WHERE fk_product_stock IN (SELECT rowid FROM ".$this->db->prefix()."product_stock as ps WHERE ps.fk_entrepot = ".((int) $this->id).")";
  326. $result = $this->db->query($sql);
  327. if (!$result) {
  328. $error++;
  329. $this->errors[] = $this->db->lasterror();
  330. }
  331. }
  332. if (!$error) {
  333. $elements = array('stock_mouvement', 'product_stock');
  334. foreach ($elements as $table) {
  335. if (!$error) {
  336. $sql = "DELETE FROM ".$this->db->prefix().$table;
  337. $sql .= " WHERE fk_entrepot = ".((int) $this->id);
  338. $result = $this->db->query($sql);
  339. if (!$result) {
  340. $error++;
  341. $this->errors[] = $this->db->lasterror();
  342. }
  343. }
  344. }
  345. }
  346. // Removed extrafields
  347. if (!$error) {
  348. if (!$error) {
  349. $result = $this->deleteExtraFields();
  350. if ($result < 0) {
  351. $error++;
  352. dol_syslog(get_class($this)."::delete Error ".$this->error, LOG_ERR);
  353. }
  354. }
  355. }
  356. if (!$error) {
  357. $sql = "DELETE FROM ".$this->db->prefix()."entrepot";
  358. $sql .= " WHERE rowid = ".((int) $this->id);
  359. $resql1 = $this->db->query($sql);
  360. if (!$resql1) {
  361. $error++;
  362. $this->errors[] = $this->db->lasterror();
  363. dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR);
  364. }
  365. }
  366. if (!$error) {
  367. // Update denormalized fields because we change content of produt_stock. Warning: Do not use "SET p.stock", does not works with pgsql
  368. $sql = "UPDATE ".$this->db->prefix()."product as p SET stock = (SELECT SUM(ps.reel) FROM ".$this->db->prefix()."product_stock as ps WHERE ps.fk_product = p.rowid)";
  369. $resql2 = $this->db->query($sql);
  370. if (!$resql2) {
  371. $error++;
  372. $this->errors[] = $this->db->lasterror();
  373. dol_syslog(get_class($this)."::delete Error ".$this->db->lasterror(), LOG_ERR);
  374. }
  375. }
  376. if (!$error) {
  377. $this->db->commit();
  378. return 1;
  379. } else {
  380. $this->db->rollback();
  381. return -1;
  382. }
  383. }
  384. /**
  385. * Load warehouse data
  386. *
  387. * @param int $id Warehouse id
  388. * @param string $ref Warehouse label
  389. * @return int >0 if OK, <0 if KO
  390. */
  391. public function fetch($id, $ref = '')
  392. {
  393. global $conf;
  394. dol_syslog(get_class($this)."::fetch id=".$id." ref=".$ref);
  395. // Check parameters
  396. if (!$id && !$ref) {
  397. $this->error = 'ErrorWrongParameters';
  398. dol_syslog(get_class($this)."::fetch ".$this->error);
  399. return -1;
  400. }
  401. $sql = "SELECT rowid, entity, fk_parent, fk_project, ref as label, description, statut, lieu, address, zip, town, fk_pays as country_id, phone, fax,";
  402. $sql .= " model_pdf, import_key";
  403. $sql .= " FROM ".$this->db->prefix()."entrepot";
  404. if ($id) {
  405. $sql .= " WHERE rowid = ".((int) $id);
  406. } else {
  407. $sql .= " WHERE entity IN (".getEntity('stock').")";
  408. if ($ref) {
  409. $sql .= " AND ref = '".$this->db->escape($ref)."'";
  410. }
  411. }
  412. $result = $this->db->query($sql);
  413. if ($result) {
  414. if ($this->db->num_rows($result) > 0) {
  415. $obj = $this->db->fetch_object($result);
  416. $this->id = $obj->rowid;
  417. $this->entity = $obj->entity;
  418. $this->fk_parent = $obj->fk_parent;
  419. $this->fk_project = $obj->fk_project;
  420. $this->ref = $obj->label;
  421. $this->label = $obj->label;
  422. $this->description = $obj->description;
  423. $this->statut = $obj->statut;
  424. $this->lieu = $obj->lieu;
  425. $this->address = $obj->address;
  426. $this->zip = $obj->zip;
  427. $this->town = $obj->town;
  428. $this->country_id = $obj->country_id;
  429. $this->phone = $obj->phone;
  430. $this->fax = $obj->fax;
  431. $this->model_pdf = $obj->model_pdf;
  432. $this->import_key = $obj->import_key;
  433. // Retrieve all extrafield
  434. // fetch optionals attributes and labels
  435. $this->fetch_optionals();
  436. include_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php';
  437. $tmp = getCountry($this->country_id, 'all');
  438. $this->country = $tmp['label'];
  439. $this->country_code = $tmp['code'];
  440. return 1;
  441. } else {
  442. $this->error = "Record Not Found";
  443. return 0;
  444. }
  445. } else {
  446. $this->error = $this->db->error();
  447. return -1;
  448. }
  449. }
  450. /**
  451. * Load warehouse info data
  452. *
  453. * @param int $id warehouse id
  454. * @return void
  455. */
  456. public function info($id)
  457. {
  458. $sql = "SELECT e.rowid, e.datec, e.tms as datem, e.fk_user_author";
  459. $sql .= " FROM ".$this->db->prefix()."entrepot as e";
  460. $sql .= " WHERE e.rowid = ".((int) $id);
  461. dol_syslog(get_class($this)."::info", LOG_DEBUG);
  462. $result = $this->db->query($sql);
  463. if ($result) {
  464. if ($this->db->num_rows($result)) {
  465. $obj = $this->db->fetch_object($result);
  466. $this->id = $obj->rowid;
  467. $this->user_creation_id = $obj->fk_user_author;
  468. $this->date_creation = $this->db->jdate($obj->datec);
  469. $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem);
  470. }
  471. $this->db->free($result);
  472. } else {
  473. dol_print_error($this->db);
  474. }
  475. }
  476. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  477. /**
  478. * Return list of all warehouses
  479. *
  480. * @param int $status Status
  481. * @return array Array list of warehouses
  482. */
  483. public function list_array($status = 1)
  484. {
  485. // phpcs:enable
  486. $liste = array();
  487. $sql = "SELECT rowid, ref as label";
  488. $sql .= " FROM ".$this->db->prefix()."entrepot";
  489. $sql .= " WHERE entity IN (".getEntity('stock').")";
  490. $sql .= " AND statut = ".((int) $status);
  491. $result = $this->db->query($sql);
  492. $i = 0;
  493. $num = $this->db->num_rows($result);
  494. if ($result) {
  495. while ($i < $num) {
  496. $row = $this->db->fetch_row($result);
  497. $liste[$row[0]] = $row[1];
  498. $i++;
  499. }
  500. $this->db->free($result);
  501. }
  502. return $liste;
  503. }
  504. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  505. /**
  506. * Return number of unique different product into a warehouse
  507. *
  508. * @return array|int Array('nb'=>Nb, 'value'=>Value)
  509. */
  510. public function nb_different_products()
  511. {
  512. // phpcs:enable
  513. $ret = array();
  514. $sql = "SELECT count(distinct p.rowid) as nb";
  515. $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
  516. $sql .= ", ".$this->db->prefix()."product as p";
  517. $sql .= " WHERE ps.fk_entrepot = ".((int) $this->id);
  518. $sql .= " AND ps.fk_product = p.rowid";
  519. //print $sql;
  520. $result = $this->db->query($sql);
  521. if ($result) {
  522. $obj = $this->db->fetch_object($result);
  523. $ret['nb'] = $obj->nb;
  524. $this->db->free($result);
  525. } else {
  526. $this->error = $this->db->lasterror();
  527. return -1;
  528. }
  529. return $ret;
  530. }
  531. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  532. /**
  533. * Return stock and value of warehosue
  534. *
  535. * @return array|int Array('nb'=>Nb, 'value'=>Value)
  536. */
  537. public function nb_products()
  538. {
  539. global $conf;
  540. // phpcs:enable
  541. $ret = array();
  542. //For MultiCompany PMP per entity
  543. $separatedPMP = false;
  544. if (getDolGlobalString('MULTICOMPANY_PRODUCT_SHARING_ENABLED') && getDolGlobalString('MULTICOMPANY_PMP_PER_ENTITY_ENABLED')) {
  545. $separatedPMP = true;
  546. }
  547. if ($separatedPMP) {
  548. $sql = "SELECT sum(ps.reel) as nb, sum(ps.reel * pa.pmp) as value";
  549. } else {
  550. $sql = "SELECT sum(ps.reel) as nb, sum(ps.reel * p.pmp) as value";
  551. }
  552. $sql .= " FROM ".$this->db->prefix()."product_stock as ps";
  553. $sql .= ", ".$this->db->prefix()."product as p";
  554. if ($separatedPMP) {
  555. $sql .= ", ".$this->db->prefix()."product_perentity as pa";
  556. }
  557. $sql .= " WHERE ps.fk_entrepot = ".((int) $this->id);
  558. if ($separatedPMP) {
  559. $sql .= " AND pa.fk_product = p.rowid AND pa.entity = ". (int) $conf->entity;
  560. }
  561. $sql .= " AND ps.fk_product = p.rowid";
  562. //print $sql;
  563. $result = $this->db->query($sql);
  564. if ($result) {
  565. $obj = $this->db->fetch_object($result);
  566. $ret['nb'] = $obj->nb;
  567. $ret['value'] = $obj->value;
  568. $this->db->free($result);
  569. } else {
  570. $this->error = $this->db->lasterror();
  571. return -1;
  572. }
  573. return $ret;
  574. }
  575. /**
  576. * Return label of status of object
  577. *
  578. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  579. * @return string Label of status
  580. */
  581. public function getLibStatut($mode = 0)
  582. {
  583. return $this->LibStatut($this->statut, $mode);
  584. }
  585. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  586. /**
  587. * Return label of a given status
  588. *
  589. * @param int $status Id status
  590. * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto
  591. * @return string Label of status
  592. */
  593. public function LibStatut($status, $mode = 0)
  594. {
  595. // phpcs:enable
  596. global $langs;
  597. $statusType = 'status5';
  598. if ($status > 0) {
  599. $statusType = 'status4';
  600. }
  601. $langs->load('stocks');
  602. $label = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
  603. $labelshort = $langs->transnoentitiesnoconv($this->labelStatus[$status]);
  604. return dolGetStatus($label, $labelshort, '', $statusType, $mode);
  605. }
  606. /**
  607. * getTooltipContentArray
  608. *
  609. * @param array $params Params to construct tooltip data
  610. * @since v18
  611. * @return array
  612. */
  613. public function getTooltipContentArray($params)
  614. {
  615. global $conf, $langs, $user;
  616. $langs->load('stocks');
  617. $datas = [];
  618. $option = $params['option'] ?? '';
  619. $nofetch = !empty($params['nofetch']);
  620. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  621. return ['optimize' => $langs->trans("Warehouse")];
  622. }
  623. $datas['picto'] = img_picto('', $this->picto).' <u class="paddingrightonly">'.$langs->trans("Warehouse").'</u>';
  624. if (isset($this->statut)) {
  625. $datas['picto'] .= ' '.$this->getLibStatut(5);
  626. }
  627. $datas['ref'] = '<br><b>'.$langs->trans('Ref').':</b> '.(empty($this->ref) ? $this->label : $this->ref);
  628. if (!empty($this->lieu)) {
  629. $datas['locationsummary'] = '<br><b>'.$langs->trans('LocationSummary').':</b> '.$this->lieu;
  630. }
  631. // show categories for this record only in ajax to not overload lists
  632. if (!$nofetch && isModEnabled('categorie')) {
  633. require_once DOL_DOCUMENT_ROOT . '/categories/class/categorie.class.php';
  634. $form = new Form($this->db);
  635. $datas['categories_warehouse'] = '<br>' . $form->showCategories($this->id, Categorie::TYPE_WAREHOUSE, 1, 1);
  636. }
  637. return $datas;
  638. }
  639. /**
  640. * Return clickable name (possibility with the pictogram)
  641. *
  642. * @param int $withpicto with pictogram
  643. * @param string $option Where the link point to
  644. * @param int $showfullpath 0=Show ref only. 1=Show full path instead of Ref (this->fk_parent must be defined)
  645. * @param int $notooltip 1=Disable tooltip
  646. * @param string $morecss Add more css on link
  647. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  648. * @return string String with URL
  649. */
  650. public function getNomUrl($withpicto = 0, $option = '', $showfullpath = 0, $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  651. {
  652. global $conf, $langs, $hookmanager;
  653. $langs->load("stocks");
  654. if (!empty($conf->dol_no_mouse_hover)) {
  655. $notooltip = 1; // Force disable tooltips
  656. }
  657. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER') && $withpicto) {
  658. $withpicto = 0;
  659. }
  660. $result = '';
  661. $params = [
  662. 'id' => $this->id,
  663. 'objecttype' => $this->element,
  664. 'option' => $option,
  665. 'nofetch' => 1,
  666. ];
  667. $classfortooltip = 'classfortooltip';
  668. $dataparams = '';
  669. if (getDolGlobalInt('MAIN_ENABLE_AJAX_TOOLTIP')) {
  670. $classfortooltip = 'classforajaxtooltip';
  671. $dataparams = ' data-params="'.dol_escape_htmltag(json_encode($params)).'"';
  672. $label = 'ToComplete';
  673. } else {
  674. $label = implode($this->getTooltipContentArray($params));
  675. }
  676. $url = DOL_URL_ROOT.'/product/stock/card.php?id='.$this->id;
  677. if ($option != 'nolink') {
  678. // Add param to save lastsearch_values or not
  679. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  680. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  681. $add_save_lastsearch_values = 1;
  682. }
  683. if ($add_save_lastsearch_values) {
  684. $url .= '&save_lastsearch_values=1';
  685. }
  686. }
  687. $linkclose = '';
  688. if (empty($notooltip)) {
  689. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  690. $label = $langs->trans("Warehouse");
  691. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  692. }
  693. $linkclose .= ($label ? ' title="'.dol_escape_htmltag($label, 1).'"' : ' title="tocomplete"');
  694. $linkclose .= $dataparams.' class="'.$classfortooltip.'"';
  695. }
  696. $linkstart = '<a href="'.$url.'"';
  697. $linkstart .= $linkclose.'>';
  698. $linkend = '</a>';
  699. $result .= $linkstart;
  700. if ($withpicto) {
  701. $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 0, 0, $notooltip ? 0 : 1);
  702. }
  703. if ($withpicto != 2) {
  704. $result .= (($showfullpath || getDolGlobalString('STOCK_ALWAYS_SHOW_FULL_ARBO')) ? $this->get_full_arbo() : $this->label);
  705. }
  706. $result .= $linkend;
  707. global $action;
  708. $hookmanager->initHooks(array('warehousedao'));
  709. $parameters = array('id'=>$this->id, 'getnomurl' => &$result, 'withpicto' => $withpicto, 'option' => $option, 'showfullpath' => $showfullpath, 'notooltip'=> $notooltip);
  710. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  711. if ($reshook > 0) {
  712. $result = $hookmanager->resPrint;
  713. } else {
  714. $result .= $hookmanager->resPrint;
  715. }
  716. return $result;
  717. }
  718. /**
  719. * Initialise an instance with random values.
  720. * Used to build previews or test instances.
  721. * id must be 0 if object instance is a specimen.
  722. *
  723. * @return void
  724. */
  725. public function initAsSpecimen()
  726. {
  727. global $user, $langs, $conf, $mysoc;
  728. $now = dol_now();
  729. // Initialize parameters
  730. $this->id = 0;
  731. $this->label = 'WAREHOUSE SPECIMEN';
  732. $this->description = 'WAREHOUSE SPECIMEN '.dol_print_date($now, 'dayhourlog');
  733. $this->statut = 1;
  734. $this->specimen = 1;
  735. $this->lieu = 'Location test';
  736. $this->address = '21 jump street';
  737. $this->zip = '99999';
  738. $this->town = 'MyTown';
  739. $this->country_id = 1;
  740. $this->country_code = 'FR';
  741. }
  742. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  743. /**
  744. * Return full path to current warehouse
  745. *
  746. * @return string String full path to current warehouse separated by " >> "
  747. */
  748. public function get_full_arbo()
  749. {
  750. // phpcs:enable
  751. global $user, $langs, $conf;
  752. $TArbo = array($this->label);
  753. $protection = 100; // We limit depth of warehouses to 100
  754. $warehousetmp = new Entrepot($this->db);
  755. $parentid = $this->fk_parent; // If parent_id not defined on current object, we do not start consecutive searches of parents
  756. $i = 0;
  757. while ($parentid > 0 && $i < $protection) {
  758. $sql = "SELECT fk_parent FROM ".$this->db->prefix()."entrepot WHERE rowid = ".((int) $parentid);
  759. $resql = $this->db->query($sql);
  760. if ($resql) {
  761. $objarbo = $this->db->fetch_object($resql);
  762. if ($objarbo) {
  763. $warehousetmp->fetch($parentid);
  764. $TArbo[] = $warehousetmp->label;
  765. $parentid = $objarbo->fk_parent;
  766. } else {
  767. break;
  768. }
  769. } else {
  770. dol_print_error($this->db);
  771. }
  772. $i++;
  773. }
  774. return implode(' >> ', array_reverse($TArbo));
  775. }
  776. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  777. /**
  778. * Return array of children warehouses ids from $id warehouse (recursive function)
  779. *
  780. * @param int $id id parent warehouse
  781. * @param integer[] $TChildWarehouses array which will contain all children (param by reference)
  782. * @return integer[] $TChildWarehouses array which will contain all children
  783. */
  784. public function get_children_warehouses($id, &$TChildWarehouses)
  785. {
  786. // phpcs:enable
  787. $sql = "SELECT rowid
  788. FROM ".$this->db->prefix()."entrepot
  789. WHERE fk_parent = ".((int) $id);
  790. $resql = $this->db->query($sql);
  791. if ($resql) {
  792. while ($res = $this->db->fetch_object($resql)) {
  793. $TChildWarehouses[] = $res->rowid;
  794. $this->get_children_warehouses($res->rowid, $TChildWarehouses);
  795. }
  796. }
  797. return $TChildWarehouses;
  798. }
  799. /**
  800. * Create object on disk
  801. *
  802. * @param string $modele force le modele a utiliser ('' to not force)
  803. * @param Translate $outputlangs Object langs to use for output
  804. * @param int $hidedetails Hide details of lines
  805. * @param int $hidedesc Hide description
  806. * @param int $hideref Hide ref
  807. * @return int 0 if KO, 1 if OK
  808. */
  809. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0)
  810. {
  811. global $conf, $user, $langs;
  812. $langs->load("stocks");
  813. $outputlangs->load("products");
  814. if (!dol_strlen($modele)) {
  815. $modele = 'standard';
  816. if ($this->model_pdf) {
  817. $modele = $this->model_pdf;
  818. } elseif (getDolGlobalString('STOCK_ADDON_PDF')) {
  819. $modele = $conf->global->STOCK_ADDON_PDF;
  820. }
  821. }
  822. $modelpath = "core/modules/stock/doc/";
  823. return $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref);
  824. }
  825. /**
  826. * Sets object to supplied categories.
  827. *
  828. * Deletes object from existing categories not supplied.
  829. * Adds it to non existing supplied categories.
  830. * Existing categories are left untouch.
  831. *
  832. * @param int[]|int $categories Category or categories IDs
  833. * @return int Return integer <0 if KO, >0 if OK
  834. */
  835. public function setCategories($categories)
  836. {
  837. require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
  838. return parent::setCategoriesCommon($categories, Categorie::TYPE_WAREHOUSE);
  839. }
  840. /**
  841. * Return clicable link of object (with eventually picto)
  842. *
  843. * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
  844. * @param array $arraydata Array of data
  845. * @return string HTML Code for Kanban thumb.
  846. */
  847. public function getKanbanView($option = '', $arraydata = null)
  848. {
  849. $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
  850. $return = '<div class="box-flex-item box-flex-grow-zero">';
  851. $return .= '<div class="info-box info-box-sm">';
  852. $return .= '<div class="info-box-icon bg-infobox-action" >';
  853. $return .= img_picto('', $this->picto);
  854. $return .= '</div>';
  855. $return .= '<div class="info-box-content" >';
  856. $return .= '<span class="info-box-ref inline-block tdoverflowmax150 valignmiddle">'.(method_exists($this, 'getNomUrl') ? $this->getNomUrl() : $this->ref).'</span>';
  857. if ($selected >= 0) {
  858. $return .= '<input id="cb'.$this->id.'" class="flat checkforselect fright" type="checkbox" name="toselect[]" value="'.$this->id.'"'.($selected ? ' checked="checked"' : '').'>';
  859. }
  860. if (property_exists($this, 'lieu') && (!empty($this->lieu))) {
  861. $return .= '<br><span class="info-box-label opacitymedium">'.$this->lieu.'</span>';
  862. }
  863. if (property_exists($this, 'sellvalue') && $this->sellvalue != 0) {
  864. $return .= '<br><span class="info-box-label amount">'.price($this->sellvalue).'</span>';
  865. }
  866. if (method_exists($this, 'getLibStatut')) {
  867. $return .= '<br><div class="info-box-status">'.$this->getLibStatut(3).'</div>';
  868. }
  869. $return .= '</div>';
  870. $return .= '</div>';
  871. $return .= '</div>';
  872. return $return;
  873. }
  874. }