ProductAttributeValue.class.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485
  1. <?php
  2. /* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
  3. * Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
  4. *
  5. * This program is free software; you can redistribute it and/or modify
  6. * it under the terms of the GNU General Public License as published by
  7. * the Free Software Foundation; either version 3 of the License, or
  8. * (at your option) any later version.
  9. *
  10. * This program is distributed in the hope that it will be useful,
  11. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  13. * GNU General Public License for more details.
  14. *
  15. * You should have received a copy of the GNU General Public License
  16. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  17. */
  18. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php';
  19. /**
  20. * Class ProductAttributeValue
  21. * Used to represent a product attribute value
  22. */
  23. class ProductAttributeValue extends CommonObjectLine
  24. {
  25. /**
  26. * @var string ID of module.
  27. */
  28. public $module = 'variants';
  29. /**
  30. * @var string ID to identify managed object.
  31. */
  32. public $element = 'productattributevalue';
  33. /**
  34. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  35. */
  36. public $table_element = 'product_attribute_value';
  37. /**
  38. * @var int Does this object support multicompany module ?
  39. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  40. */
  41. public $ismultientitymanaged = 1;
  42. /**
  43. * @var int Does object support extrafields ? 0=No, 1=Yes
  44. */
  45. public $isextrafieldmanaged = 0;
  46. /**
  47. * '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')
  48. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  49. * 'label' the translation key.
  50. * 'picto' is code of a picto to show before value in forms
  51. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  52. * 'position' is the sort order of field.
  53. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  54. * '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)
  55. * 'noteditable' says if field is not editable (1 or 0)
  56. * '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.
  57. * 'index' if we want an index in database.
  58. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  59. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  60. * '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).
  61. * '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'
  62. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  63. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  64. * '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.
  65. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  66. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  67. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  68. *
  69. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  70. */
  71. /**
  72. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  73. */
  74. public $fields=array(
  75. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
  76. 'fk_product_attribute' => array('type'=>'integer:ProductAttribute:variants/class/ProductAttribute.class.php', 'label'=>'ProductAttribute', 'enabled'=>1, 'visible'=>0, 'position'=>10, 'notnull'=>1, 'index'=>1,),
  77. 'ref' => array('type'=>'varchar(255)', 'label'=>'Ref', 'visible'=>1, 'enabled'=>1, 'position'=>20, 'notnull'=>1, 'index'=>1, 'searchall'=>1, 'comment'=>"Reference of object", 'css'=>''),
  78. 'value' => array('type'=>'varchar(255)', 'label'=>'Value', 'enabled'=>'1', 'position'=>30, 'notnull'=>1, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'help'=>"", 'showoncombobox'=>'1',),
  79. 'position' => array('type'=>'integer', 'label'=>'Rank', 'enabled'=>1, 'visible'=>0, 'default'=>0, 'position'=>200, 'notnull'=>1,),
  80. );
  81. public $id;
  82. public $fk_product_attribute;
  83. public $ref;
  84. public $value;
  85. public $position;
  86. /**
  87. * Constructor
  88. *
  89. * @param DoliDB $db Database handler
  90. */
  91. public function __construct(DoliDB $db)
  92. {
  93. global $conf, $langs;
  94. $this->db = $db;
  95. $this->entity = $conf->entity;
  96. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
  97. $this->fields['rowid']['visible'] = 0;
  98. }
  99. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  100. $this->fields['entity']['enabled'] = 0;
  101. }
  102. // Unset fields that are disabled
  103. foreach ($this->fields as $key => $val) {
  104. if (isset($val['enabled']) && empty($val['enabled'])) {
  105. unset($this->fields[$key]);
  106. }
  107. }
  108. // Translate some data of arrayofkeyval
  109. if (is_object($langs)) {
  110. foreach ($this->fields as $key => $val) {
  111. if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
  112. foreach ($val['arrayofkeyval'] as $key2 => $val2) {
  113. $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
  114. }
  115. }
  116. }
  117. }
  118. }
  119. /**
  120. * Creates a value for a product attribute
  121. *
  122. * @param User $user Object user
  123. * @param int $notrigger Do not execute trigger
  124. * @return int <0 KO >0 OK
  125. */
  126. public function create(User $user, $notrigger = 0)
  127. {
  128. global $langs;
  129. $error = 0;
  130. // Clean parameters
  131. $this->fk_product_attribute = $this->fk_product_attribute > 0 ? $this->fk_product_attribute : 0;
  132. $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
  133. $this->value = trim($this->value);
  134. // Check parameters
  135. if (empty($this->fk_product_attribute)) {
  136. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductAttribute"));
  137. $error++;
  138. }
  139. if (empty($this->ref)) {
  140. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
  141. $error++;
  142. }
  143. if (empty($this->value)) {
  144. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Value"));
  145. $error++;
  146. }
  147. if ($error) {
  148. dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
  149. return -1;
  150. }
  151. $this->db->begin();
  152. $sql = "INSERT INTO " . MAIN_DB_PREFIX . $this->table_element . " (";
  153. $sql .= " fk_product_attribute, ref, value, entity, position";
  154. $sql .= ")";
  155. $sql .= " VALUES (";
  156. $sql .= " " . ((int) $this->fk_product_attribute);
  157. $sql .= ", '" . $this->db->escape($this->ref) . "'";
  158. $sql .= ", '" . $this->db->escape($this->value) . "'";
  159. $sql .= ", " . ((int) $this->entity);
  160. $sql .= ", " . ((int) $this->position);
  161. $sql .= ")";
  162. dol_syslog(__METHOD__, LOG_DEBUG);
  163. $resql = $this->db->query($sql);
  164. if (!$resql) {
  165. $this->errors[] = "Error " . $this->db->lasterror();
  166. $error++;
  167. }
  168. if (!$error) {
  169. $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX . $this->table_element);
  170. }
  171. if (!$error && !$notrigger) {
  172. // Call trigger
  173. $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_CREATE', $user);
  174. if ($result < 0) {
  175. $error++;
  176. }
  177. // End call triggers
  178. }
  179. if ($error) {
  180. $this->db->rollback();
  181. return -1 * $error;
  182. } else {
  183. $this->db->commit();
  184. return $this->id;
  185. }
  186. }
  187. /**
  188. * Gets a product attribute value
  189. *
  190. * @param int $id Product attribute value id
  191. * @return int <0 KO, >0 OK
  192. */
  193. public function fetch($id)
  194. {
  195. global $langs;
  196. $error = 0;
  197. // Clean parameters
  198. $id = $id > 0 ? $id : 0;
  199. // Check parameters
  200. if (empty($id)) {
  201. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
  202. $error++;
  203. }
  204. if ($error) {
  205. dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
  206. return -1;
  207. }
  208. $sql = "SELECT rowid, fk_product_attribute, ref, value";
  209. $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element;
  210. $sql .= " WHERE rowid = " . ((int) $id);
  211. $sql .= " AND entity IN (" . getEntity('product') . ")";
  212. dol_syslog(__METHOD__, LOG_DEBUG);
  213. $resql = $this->db->query($sql);
  214. if (!$resql) {
  215. $this->errors[] = "Error " . $this->db->lasterror();
  216. dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
  217. return -1;
  218. }
  219. $numrows = $this->db->num_rows($resql);
  220. if ($numrows) {
  221. $obj = $this->db->fetch_object($resql);
  222. $this->id = $obj->rowid;
  223. $this->fk_product_attribute = $obj->fk_product_attribute;
  224. $this->ref = $obj->ref;
  225. $this->value = $obj->value;
  226. }
  227. $this->db->free($resql);
  228. return $numrows;
  229. }
  230. /**
  231. * Returns all product attribute values of a product attribute
  232. *
  233. * @param int $prodattr_id Product attribute id
  234. * @param bool $only_used Fetch only used attribute values
  235. * @param int $returnonlydata 0: return object, 1: return only data
  236. * @return ProductAttributeValue[] Array of object
  237. */
  238. public function fetchAllByProductAttribute($prodattr_id, $only_used = false, $returnonlydata = 0)
  239. {
  240. $return = array();
  241. $sql = "SELECT ";
  242. if ($only_used) {
  243. $sql .= "DISTINCT ";
  244. }
  245. $sql .= "v.fk_product_attribute, v.rowid, v.ref, v.value FROM " . MAIN_DB_PREFIX . "product_attribute_value v ";
  246. if ($only_used) {
  247. $sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination2val c2v ON c2v.fk_prod_attr_val = v.rowid ";
  248. $sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product_attribute_combination c ON c.rowid = c2v.fk_prod_combination ";
  249. $sql .= "LEFT JOIN " . MAIN_DB_PREFIX . "product p ON p.rowid = c.fk_product_child ";
  250. }
  251. $sql .= "WHERE v.fk_product_attribute = " . ((int) $prodattr_id);
  252. if ($only_used) {
  253. $sql .= " AND c2v.rowid IS NOT NULL AND p.tosell = 1";
  254. }
  255. $query = $this->db->query($sql);
  256. while ($result = $this->db->fetch_object($query)) {
  257. if (empty($returnonlydata)) {
  258. $tmp = new ProductAttributeValue($this->db);
  259. } else {
  260. $tmp = new stdClass();
  261. }
  262. $tmp->fk_product_attribute = $result->fk_product_attribute;
  263. $tmp->id = $result->rowid;
  264. $tmp->ref = $result->ref;
  265. $tmp->value = $result->value;
  266. $return[] = $tmp;
  267. }
  268. return $return;
  269. }
  270. /**
  271. * Updates a product attribute value
  272. *
  273. * @param User $user Object user
  274. * @param int $notrigger Do not execute trigger
  275. * @return int <0 if KO, >0 if OK
  276. */
  277. public function update(User $user, $notrigger = 0)
  278. {
  279. global $langs;
  280. $error = 0;
  281. // Clean parameters
  282. $this->fk_product_attribute = $this->fk_product_attribute > 0 ? $this->fk_product_attribute : 0;
  283. $this->ref = strtoupper(dol_sanitizeFileName(dol_string_nospecial(trim($this->ref)))); // Ref must be uppercase
  284. $this->value = trim($this->value);
  285. // Check parameters
  286. if (empty($this->fk_product_attribute)) {
  287. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("ProductAttribute"));
  288. $error++;
  289. }
  290. if (empty($this->ref)) {
  291. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Ref"));
  292. $error++;
  293. }
  294. if (empty($this->value)) {
  295. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("Value"));
  296. $error++;
  297. }
  298. if ($error) {
  299. dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
  300. return -1;
  301. }
  302. $this->db->begin();
  303. $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element . " SET";
  304. $sql .= " fk_product_attribute = " . ((int) $this->fk_product_attribute);
  305. $sql .= ", ref = '" . $this->db->escape($this->ref) . "'";
  306. $sql .= ", value = '" . $this->db->escape($this->value) . "'";
  307. $sql .= ", position = " . ((int) $this->position);
  308. $sql .= " WHERE rowid = " . ((int) $this->id);
  309. dol_syslog(__METHOD__, LOG_DEBUG);
  310. $resql = $this->db->query($sql);
  311. if (!$resql) {
  312. $this->errors[] = "Error " . $this->db->lasterror();
  313. $error++;
  314. }
  315. if (!$error && !$notrigger) {
  316. // Call trigger
  317. $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_MODIFY', $user);
  318. if ($result < 0) {
  319. $error++;
  320. }
  321. // End call triggers
  322. }
  323. if (!$error) {
  324. $this->db->commit();
  325. return 1;
  326. } else {
  327. $this->db->rollback();
  328. return -1 * $error;
  329. }
  330. }
  331. /**
  332. * Deletes a product attribute value
  333. *
  334. * @param User $user Object user
  335. * @param int $notrigger Do not execute trigger
  336. * @return int <0 KO, >0 OK
  337. */
  338. public function delete(User $user, $notrigger = 0)
  339. {
  340. global $langs;
  341. $error = 0;
  342. // Clean parameters
  343. $this->id = $this->id > 0 ? $this->id : 0;
  344. // Check parameters
  345. if (empty($this->id)) {
  346. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
  347. $error++;
  348. }
  349. if ($error) {
  350. dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
  351. return -1;
  352. }
  353. $result = $this->isUsed();
  354. if ($result < 0) {
  355. return -1;
  356. } elseif ($result > 0) {
  357. $this->errors[] = $langs->trans('ErrorAttributeValueIsUsedIntoProduct');
  358. return -1;
  359. }
  360. $this->db->begin();
  361. if (!$error && !$notrigger) {
  362. // Call trigger
  363. $result = $this->call_trigger('PRODUCT_ATTRIBUTE_VALUE_DELETE', $user);
  364. if ($result < 0) {
  365. $error++;
  366. }
  367. // End call triggers
  368. }
  369. if (!$error) {
  370. $sql = "DELETE FROM " . MAIN_DB_PREFIX . $this->table_element . " WHERE rowid = " . ((int) $this->id);
  371. dol_syslog(__METHOD__, LOG_DEBUG);
  372. $resql = $this->db->query($sql);
  373. if (!$resql) {
  374. $this->errors[] = "Error " . $this->db->lasterror();
  375. $error++;
  376. }
  377. }
  378. if (!$error) {
  379. $this->db->commit();
  380. return 1;
  381. } else {
  382. $this->db->rollback();
  383. return -1 * $error;
  384. }
  385. }
  386. /**
  387. * Test if used by a product
  388. *
  389. * @return int <0 KO, =0 if No, =1 if Yes
  390. */
  391. public function isUsed()
  392. {
  393. global $langs;
  394. $error = 0;
  395. // Clean parameters
  396. $this->id = $this->id > 0 ? $this->id : 0;
  397. // Check parameters
  398. if (empty($this->id)) {
  399. $this->errors[] = $langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("TechnicalID"));
  400. $error++;
  401. }
  402. if ($error) {
  403. dol_syslog(__METHOD__ . ' ' . $this->errorsToString(), LOG_ERR);
  404. return -1;
  405. }
  406. $sql = "SELECT COUNT(*) AS nb FROM " . MAIN_DB_PREFIX . "product_attribute_combination2val WHERE fk_prod_attr_val = " . ((int) $this->id);
  407. dol_syslog(__METHOD__, LOG_DEBUG);
  408. $resql = $this->db->query($sql);
  409. if (!$resql) {
  410. $this->errors[] = "Error " . $this->db->lasterror();
  411. return -1;
  412. }
  413. $used = 0;
  414. if ($obj = $this->db->fetch_object($resql)) {
  415. $used = $obj->nb;
  416. }
  417. return $used ? 1 : 0;
  418. }
  419. }