productfournisseurprice.class.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844
  1. <?php
  2. /* Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
  3. * Copyright (C) 2021 Alexis LAURIER <contact@alexislaurier.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. /**
  19. * \file class/productfournisseurprice.class.php
  20. * \ingroup product
  21. * \brief This file is a CRUD class file for ProductFournisseurPrice (Create/Read/Update/Delete)
  22. */
  23. // Put here all includes required by your class file
  24. require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
  25. /**
  26. * Class for ProductFournisseurPrice
  27. */
  28. class ProductFournisseurPrice extends CommonObject
  29. {
  30. /**
  31. * @var string ID to identify managed object.
  32. */
  33. public $element = 'productfournisseurprice';
  34. /**
  35. * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
  36. */
  37. public $table_element = 'product_fournisseur_price';
  38. /**
  39. * @var int Does this object support multicompany module ?
  40. * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
  41. */
  42. public $ismultientitymanaged = 1;
  43. /**
  44. * @var int Does object support extrafields ? 0=No, 1=Yes
  45. */
  46. public $isextrafieldmanaged = 1;
  47. /**
  48. * @var string String with name of icon for productfournisseurprice. Must be the part after the 'object_' into object_productfournisseurprice.png
  49. */
  50. public $picto = 'productfournisseurprice@buypricehistory';
  51. const STATUS_DRAFT = 0;
  52. const STATUS_VALIDATED = 1;
  53. const STATUS_CANCELED = 9;
  54. /**
  55. * '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')
  56. * Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
  57. * 'label' the translation key.
  58. * 'picto' is code of a picto to show before value in forms
  59. * 'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
  60. * 'position' is the sort order of field.
  61. * 'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
  62. * '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)
  63. * 'noteditable' says if field is not editable (1 or 0)
  64. * '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.
  65. * 'index' if we want an index in database.
  66. * 'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
  67. * 'searchall' is 1 if we want to search in this field when making a search from the quick search button.
  68. * '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).
  69. * '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'
  70. * 'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
  71. * 'showoncombobox' if value of the field must be visible into the label of the combobox that list record
  72. * '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.
  73. * 'arrayofkeyval' to set list of value if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel")
  74. * 'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
  75. * 'comment' is not used. You can store here any text of your choice. It is not used by application.
  76. *
  77. * Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
  78. */
  79. // BEGIN MODULEBUILDER PROPERTIES
  80. /**
  81. * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
  82. */
  83. public $fields=array(
  84. 'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>10, 'notnull'=>1, 'visible'=>0,),
  85. 'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>'1', 'position'=>15, 'notnull'=>1, 'visible'=>-2, 'default'=>'1', 'index'=>1,),
  86. 'datec' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>20, 'notnull'=>0, 'visible'=>-1,),
  87. 'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>25, 'notnull'=>1, 'visible'=>-1,),
  88. 'fk_product' => array('type'=>'integer:Product:product/class/product.class.php:1', 'label'=>'Fkproduct', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>-1,),
  89. 'fk_soc' => array('type'=>'integer:Societe:societe/class/societe.class.php', 'label'=>'ThirdParty', 'enabled'=>'1', 'position'=>35, 'notnull'=>0, 'visible'=>-1,),
  90. 'ref_fourn' => array('type'=>'varchar(255)', 'label'=>'Reffourn', 'enabled'=>'1', 'position'=>40, 'notnull'=>0, 'visible'=>-1,),
  91. 'desc_fourn' => array('type'=>'text', 'label'=>'Descfourn', 'enabled'=>'1', 'position'=>45, 'notnull'=>0, 'visible'=>-1,),
  92. 'fk_availability' => array('type'=>'integer', 'label'=>'Fkavailability', 'enabled'=>'1', 'position'=>50, 'notnull'=>0, 'visible'=>-1,),
  93. 'price' => array('type'=>'double(24,8)', 'label'=>'Price', 'enabled'=>'1', 'position'=>55, 'notnull'=>0, 'visible'=>-1,),
  94. 'quantity' => array('type'=>'double', 'label'=>'Quantity', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>-1,),
  95. 'remise_percent' => array('type'=>'double', 'label'=>'Remisepercent', 'enabled'=>'1', 'position'=>65, 'notnull'=>1, 'visible'=>-1,),
  96. 'remise' => array('type'=>'double', 'label'=>'Remise', 'enabled'=>'1', 'position'=>70, 'notnull'=>1, 'visible'=>-1,),
  97. 'unitprice' => array('type'=>'double(24,8)', 'label'=>'Unitprice', 'enabled'=>'1', 'position'=>75, 'notnull'=>0, 'visible'=>-1,),
  98. 'charges' => array('type'=>'double(24,8)', 'label'=>'Charges', 'enabled'=>'1', 'position'=>80, 'notnull'=>0, 'visible'=>-1,),
  99. 'default_vat_code' => array('type'=>'varchar(10)', 'label'=>'Defaultvatcode', 'enabled'=>'1', 'position'=>85, 'notnull'=>0, 'visible'=>-1,),
  100. 'tva_tx' => array('type'=>'double(6,3)', 'label'=>'Tvatx', 'enabled'=>'1', 'position'=>90, 'notnull'=>1, 'visible'=>-1,),
  101. 'info_bits' => array('type'=>'integer', 'label'=>'Infobits', 'enabled'=>'1', 'position'=>95, 'notnull'=>1, 'visible'=>-1,),
  102. 'fk_user' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'Fkuser', 'enabled'=>'1', 'position'=>100, 'notnull'=>0, 'visible'=>-1,),
  103. 'fk_supplier_price_expression' => array('type'=>'integer', 'label'=>'Fksupplierpriceexpression', 'enabled'=>'1', 'position'=>105, 'notnull'=>0, 'visible'=>-1,),
  104. 'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>900, 'notnull'=>0, 'visible'=>-2,),
  105. 'delivery_time_days' => array('type'=>'integer', 'label'=>'Deliverytimedays', 'enabled'=>'1', 'position'=>115, 'notnull'=>0, 'visible'=>-1,),
  106. 'supplier_reputation' => array('type'=>'varchar(10)', 'label'=>'Supplierreputation', 'enabled'=>'1', 'position'=>120, 'notnull'=>0, 'visible'=>-1,),
  107. 'fk_multicurrency' => array('type'=>'integer', 'label'=>'Fkmulticurrency', 'enabled'=>'1', 'position'=>125, 'notnull'=>0, 'visible'=>-1,),
  108. 'multicurrency_code' => array('type'=>'varchar(255)', 'label'=>'Multicurrencycode', 'enabled'=>'1', 'position'=>130, 'notnull'=>0, 'visible'=>-1,),
  109. 'multicurrency_tx' => array('type'=>'double(24,8)', 'label'=>'Multicurrencytx', 'enabled'=>'1', 'position'=>135, 'notnull'=>0, 'visible'=>-1,),
  110. 'multicurrency_price' => array('type'=>'double(24,8)', 'label'=>'Multicurrencyprice', 'enabled'=>'1', 'position'=>140, 'notnull'=>0, 'visible'=>-1,),
  111. 'multicurrency_unitprice' => array('type'=>'double(24,8)', 'label'=>'Multicurrencyunitprice', 'enabled'=>'1', 'position'=>145, 'notnull'=>0, 'visible'=>-1,),
  112. 'localtax1_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax1tx', 'enabled'=>'1', 'position'=>150, 'notnull'=>0, 'visible'=>-1,),
  113. 'localtax1_type' => array('type'=>'varchar(10)', 'label'=>'Localtax1type', 'enabled'=>'1', 'position'=>155, 'notnull'=>1, 'visible'=>-1,),
  114. 'localtax2_tx' => array('type'=>'double(6,3)', 'label'=>'Localtax2tx', 'enabled'=>'1', 'position'=>160, 'notnull'=>0, 'visible'=>-1,),
  115. 'localtax2_type' => array('type'=>'varchar(10)', 'label'=>'Localtax2type', 'enabled'=>'1', 'position'=>165, 'notnull'=>1, 'visible'=>-1,),
  116. 'barcode' => array('type'=>'varchar(180)', 'label'=>'Barcode', 'enabled'=>'1', 'position'=>170, 'notnull'=>0, 'visible'=>-1,),
  117. 'fk_barcode_type' => array('type'=>'integer', 'label'=>'Fkbarcodetype', 'enabled'=>'1', 'position'=>175, 'notnull'=>0, 'visible'=>-1,),
  118. 'packaging' => array('type'=>'varchar(64)', 'label'=>'Packaging', 'enabled'=>'1', 'position'=>180, 'notnull'=>0, 'visible'=>-1,),
  119. );
  120. public $rowid;
  121. public $entity;
  122. public $datec;
  123. public $tms;
  124. public $fk_product;
  125. public $fk_soc;
  126. public $ref_fourn;
  127. public $desc_fourn;
  128. public $fk_availability;
  129. public $price;
  130. public $quantity;
  131. public $remise_percent;
  132. public $remise;
  133. public $unitprice;
  134. public $charges;
  135. public $default_vat_code;
  136. public $tva_tx;
  137. public $info_bits;
  138. public $fk_user;
  139. public $fk_supplier_price_expression;
  140. public $import_key;
  141. public $delivery_time_days;
  142. public $supplier_reputation;
  143. public $fk_multicurrency;
  144. public $multicurrency_code;
  145. public $multicurrency_tx;
  146. public $multicurrency_price;
  147. public $multicurrency_unitprice;
  148. public $localtax1_tx;
  149. public $localtax1_type;
  150. public $localtax2_tx;
  151. public $localtax2_type;
  152. public $barcode;
  153. public $fk_barcode_type;
  154. public $packaging;
  155. // END MODULEBUILDER PROPERTIES
  156. /**
  157. * Constructor
  158. *
  159. * @param DoliDb $db Database handler
  160. */
  161. public function __construct(DoliDB $db)
  162. {
  163. global $conf, $langs;
  164. $this->db = $db;
  165. if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) $this->fields['rowid']['visible'] = 0;
  166. if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) $this->fields['entity']['enabled'] = 0;
  167. // Unset fields that are disabled
  168. foreach ($this->fields as $key => $val) {
  169. if (isset($val['enabled']) && empty($val['enabled'])) {
  170. unset($this->fields[$key]);
  171. }
  172. }
  173. }
  174. /**
  175. * Create object into database
  176. *
  177. * @param User $user User that creates
  178. * @param bool $notrigger false=launch triggers after, true=disable triggers
  179. * @return int <0 if KO, Id of created object if OK
  180. */
  181. public function create(User $user, $notrigger = false)
  182. {
  183. return $this->createCommon($user, $notrigger);
  184. }
  185. /**
  186. * Clone an object into another one
  187. *
  188. * @param User $user User that creates
  189. * @param int $fromid Id of object to clone
  190. * @return mixed New object created, <0 if KO
  191. */
  192. public function createFromClone(User $user, $fromid)
  193. {
  194. global $langs, $extrafields;
  195. $error = 0;
  196. dol_syslog(__METHOD__, LOG_DEBUG);
  197. $object = new self($this->db);
  198. $this->db->begin();
  199. // Load source object
  200. $result = $object->fetchCommon($fromid);
  201. if ($result > 0 && !empty($object->table_element_line)) $object->fetchLines();
  202. // get lines so they will be clone
  203. //foreach($this->lines as $line)
  204. // $line->fetch_optionals();
  205. // Reset some properties
  206. unset($object->id);
  207. unset($object->fk_user_creat);
  208. unset($object->import_key);
  209. // Clear fields
  210. if (property_exists($object, 'ref')) $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  211. if (property_exists($object, 'label')) $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  212. if (property_exists($object, 'status')) { $object->status = self::STATUS_DRAFT; }
  213. if (property_exists($object, 'date_creation')) { $object->date_creation = dol_now(); }
  214. if (property_exists($object, 'date_modification')) { $object->date_modification = null; }
  215. // ...
  216. // Clear extrafields that are unique
  217. if (is_array($object->array_options) && count($object->array_options) > 0) {
  218. $extrafields->fetch_name_optionals_label($this->table_element);
  219. foreach ($object->array_options as $key => $option) {
  220. $shortkey = preg_replace('/options_/', '', $key);
  221. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  222. //var_dump($key);
  223. //var_dump($clonedObj->array_options[$key]); exit;
  224. unset($object->array_options[$key]);
  225. }
  226. }
  227. }
  228. // Create clone
  229. $object->context['createfromclone'] = 'createfromclone';
  230. $result = $object->createCommon($user);
  231. if ($result < 0) {
  232. $error++;
  233. $this->error = $object->error;
  234. $this->errors = $object->errors;
  235. }
  236. if (!$error) {
  237. // copy internal contacts
  238. if ($this->copy_linked_contact($object, 'internal') < 0) {
  239. $error++;
  240. }
  241. }
  242. if (!$error) {
  243. // copy external contacts if same company
  244. if (property_exists($this, 'socid') && $this->socid == $object->socid) {
  245. if ($this->copy_linked_contact($object, 'external') < 0)
  246. $error++;
  247. }
  248. }
  249. unset($object->context['createfromclone']);
  250. // End
  251. if (!$error) {
  252. $this->db->commit();
  253. return $object;
  254. } else {
  255. $this->db->rollback();
  256. return -1;
  257. }
  258. }
  259. /**
  260. * Load object in memory from the database
  261. *
  262. * @param int $id Id object
  263. * @return int <0 if KO, 0 if not found, >0 if OK
  264. */
  265. public function fetch($id)
  266. {
  267. return $this->fetchCommon($id);
  268. }
  269. /**
  270. * Load list of objects in memory from the database.
  271. *
  272. * @param string $sortorder Sort Order
  273. * @param string $sortfield Sort field
  274. * @param int $limit limit
  275. * @param int $offset Offset
  276. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  277. * @param string $filtermode Filter mode (AND or OR)
  278. * @return array|int int <0 if KO, array of pages if OK
  279. */
  280. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  281. {
  282. global $conf;
  283. dol_syslog(__METHOD__, LOG_DEBUG);
  284. $records = array();
  285. $sql = "SELECT ";
  286. $sql .= $this->getFieldList();
  287. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  288. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
  289. else $sql .= " WHERE 1 = 1";
  290. // Manage filter
  291. $sqlwhere = array();
  292. if (count($filter) > 0) {
  293. foreach ($filter as $key => $value) {
  294. if ($key == 't.rowid') {
  295. $sqlwhere[] = $key." = ".((int) $value);
  296. } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  297. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  298. } elseif ($key == 'customsql') {
  299. $sqlwhere[] = $value;
  300. } elseif (strpos($value, '%') === false) {
  301. $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
  302. } else {
  303. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  304. }
  305. }
  306. }
  307. if (count($sqlwhere) > 0) {
  308. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  309. }
  310. if (!empty($sortfield)) {
  311. $sql .= $this->db->order($sortfield, $sortorder);
  312. }
  313. if (!empty($limit)) {
  314. $sql .= $this->db->plimit($limit, $offset);
  315. }
  316. $resql = $this->db->query($sql);
  317. if ($resql) {
  318. $num = $this->db->num_rows($resql);
  319. $i = 0;
  320. while ($i < ($limit ? min($limit, $num) : $num)) {
  321. $obj = $this->db->fetch_object($resql);
  322. $record = new self($this->db);
  323. $record->setVarsFromFetchObj($obj);
  324. $records[$record->id] = $record;
  325. $i++;
  326. }
  327. $this->db->free($resql);
  328. return $records;
  329. } else {
  330. $this->errors[] = 'Error '.$this->db->lasterror();
  331. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  332. return -1;
  333. }
  334. }
  335. /**
  336. * Update object into database
  337. *
  338. * @param User $user User that modifies
  339. * @param bool $notrigger false=launch triggers after, true=disable triggers
  340. * @return int <0 if KO, >0 if OK
  341. */
  342. public function update(User $user, $notrigger = false)
  343. {
  344. return $this->updateCommon($user, $notrigger);
  345. }
  346. /**
  347. * Delete object in database
  348. *
  349. * @param User $user User that deletes
  350. * @param bool $notrigger false=launch triggers after, true=disable triggers
  351. * @return int <0 if KO, >0 if OK
  352. */
  353. public function delete(User $user, $notrigger = false)
  354. {
  355. return $this->deleteCommon($user, $notrigger);
  356. }
  357. /**
  358. * Validate object
  359. *
  360. * @param User $user User making status change
  361. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  362. * @return int <=0 if OK, 0=Nothing done, >0 if KO
  363. */
  364. public function validate($user, $notrigger = 0)
  365. {
  366. global $conf, $langs;
  367. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  368. $error = 0;
  369. // Protection
  370. if ($this->status == self::STATUS_VALIDATED) {
  371. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  372. return 0;
  373. }
  374. $now = dol_now();
  375. $this->db->begin();
  376. // Define new ref
  377. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  378. $num = $this->getNextNumRef();
  379. } else {
  380. $num = $this->ref;
  381. }
  382. $this->newref = $num;
  383. if (!empty($num)) {
  384. // Validate
  385. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  386. $sql .= " SET ref = '".$this->db->escape($num)."',";
  387. $sql .= " status = ".self::STATUS_VALIDATED;
  388. if (!empty($this->fields['date_validation'])) $sql .= ", date_validation = '".$this->db->idate($now)."'";
  389. if (!empty($this->fields['fk_user_valid'])) $sql .= ", fk_user_valid = ".$user->id;
  390. $sql .= " WHERE rowid = ".((int) $this->id);
  391. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  392. $resql = $this->db->query($sql);
  393. if (!$resql) {
  394. dol_print_error($this->db);
  395. $this->error = $this->db->lasterror();
  396. $error++;
  397. }
  398. if (!$error && !$notrigger) {
  399. // Call trigger
  400. $result = $this->call_trigger('PRODUCTFOURNISSEURPRICE_VALIDATE', $user);
  401. if ($result < 0) $error++;
  402. // End call triggers
  403. }
  404. }
  405. if (!$error) {
  406. $this->oldref = $this->ref;
  407. // Rename directory if dir was a temporary ref
  408. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  409. // Now we rename also files into index
  410. $sql = 'UPDATE '.$this->db->prefix()."ecm_files set filename = CONCAT('".$this->db->escape($this->newref)."', SUBSTR(filename, ".(strlen($this->ref) + 1).")), filepath = 'productfournisseurprice/".$this->db->escape($this->newref)."'";
  411. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'productfournisseurprice/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  412. $resql = $this->db->query($sql);
  413. if (!$resql) { $error++; $this->error = $this->db->lasterror(); }
  414. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  415. $oldref = dol_sanitizeFileName($this->ref);
  416. $newref = dol_sanitizeFileName($num);
  417. $dirsource = $conf->buypricehistory->dir_output.'/productfournisseurprice/'.$oldref;
  418. $dirdest = $conf->buypricehistory->dir_output.'/productfournisseurprice/'.$newref;
  419. if (!$error && file_exists($dirsource)) {
  420. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  421. if (@rename($dirsource, $dirdest)) {
  422. dol_syslog("Rename ok");
  423. // Rename docs starting with $oldref with $newref
  424. $listoffiles = dol_dir_list($conf->buypricehistory->dir_output.'/productfournisseurprice/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  425. foreach ($listoffiles as $fileentry) {
  426. $dirsource = $fileentry['name'];
  427. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  428. $dirsource = $fileentry['path'].'/'.$dirsource;
  429. $dirdest = $fileentry['path'].'/'.$dirdest;
  430. @rename($dirsource, $dirdest);
  431. }
  432. }
  433. }
  434. }
  435. }
  436. // Set new ref and current status
  437. if (!$error) {
  438. $this->ref = $num;
  439. $this->status = self::STATUS_VALIDATED;
  440. }
  441. if (!$error) {
  442. $this->db->commit();
  443. return 1;
  444. } else {
  445. $this->db->rollback();
  446. return -1;
  447. }
  448. }
  449. /**
  450. * Set draft status
  451. *
  452. * @param User $user Object user that modify
  453. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  454. * @return int <0 if KO, >0 if OK
  455. */
  456. public function setDraft($user, $notrigger = 0)
  457. {
  458. // Protection
  459. if ($this->status <= self::STATUS_DRAFT) {
  460. return 0;
  461. }
  462. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'PRODUCTFOURNISSEURPRICE_UNVALIDATE');
  463. }
  464. /**
  465. * Set cancel status
  466. *
  467. * @param User $user Object user that modify
  468. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  469. * @return int <0 if KO, 0=Nothing done, >0 if OK
  470. */
  471. public function cancel($user, $notrigger = 0)
  472. {
  473. // Protection
  474. if ($this->status != self::STATUS_VALIDATED) {
  475. return 0;
  476. }
  477. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'PRODUCTFOURNISSEURPRICE_CANCEL');
  478. }
  479. /**
  480. * Set back to validated status
  481. *
  482. * @param User $user Object user that modify
  483. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  484. * @return int <0 if KO, 0=Nothing done, >0 if OK
  485. */
  486. public function reopen($user, $notrigger = 0)
  487. {
  488. // Protection
  489. if ($this->status != self::STATUS_CANCELED) {
  490. return 0;
  491. }
  492. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'PRODUCTFOURNISSEURPRICE_REOPEN');
  493. }
  494. /**
  495. * Return a link to the object card (with optionaly the picto)
  496. *
  497. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  498. * @param string $option On what the link point to ('nolink', ...)
  499. * @param int $notooltip 1=Disable tooltip
  500. * @param string $morecss Add more css on link
  501. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  502. * @return string String with URL
  503. */
  504. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  505. {
  506. global $conf, $langs, $hookmanager;
  507. if (!empty($conf->dol_no_mouse_hover)) $notooltip = 1; // Force disable tooltips
  508. $result = '';
  509. $label = img_picto('', $this->picto).' <u>'.$langs->trans("ProductFournisseurPrice").'</u>';
  510. if (isset($this->status)) {
  511. $label .= ' '.$this->getLibStatut(5);
  512. }
  513. $label .= '<br>';
  514. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  515. $url = dol_buildpath('/buypricehistory/productfournisseurprice_card.php', 1).'?id='.$this->id;
  516. if ($option != 'nolink') {
  517. // Add param to save lastsearch_values or not
  518. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  519. if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) $add_save_lastsearch_values = 1;
  520. if ($add_save_lastsearch_values) $url .= '&save_lastsearch_values=1';
  521. }
  522. $linkclose = '';
  523. if (empty($notooltip)) {
  524. if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
  525. $label = $langs->trans("ShowProductFournisseurPrice");
  526. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  527. }
  528. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  529. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  530. } else $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  531. $linkstart = '<a href="'.$url.'"';
  532. $linkstart .= $linkclose.'>';
  533. $linkend = '</a>';
  534. $result .= $linkstart;
  535. if (empty($this->showphoto_on_popup)) {
  536. if ($withpicto) $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);
  537. } else {
  538. if ($withpicto) {
  539. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  540. list($class, $module) = explode('@', $this->picto);
  541. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  542. $filearray = dol_dir_list($upload_dir, "files");
  543. $filename = $filearray[0]['name'];
  544. if (!empty($filename)) {
  545. $pospoint = strpos($filearray[0]['name'], '.');
  546. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  547. if (empty($conf->global->{strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS'})) {
  548. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo'.$module.'" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div></div>';
  549. } else {
  550. $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="'.DOL_URL_ROOT.'/viewimage.php?modulepart='.$module.'&entity='.$conf->entity.'&file='.urlencode($pathtophoto).'"></div>';
  551. }
  552. $result .= '</div>';
  553. } else {
  554. $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);
  555. }
  556. }
  557. }
  558. if ($withpicto != 2) $result .= $this->ref;
  559. $result .= $linkend;
  560. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  561. global $action, $hookmanager;
  562. $hookmanager->initHooks(array('productfournisseurpricedao'));
  563. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  564. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  565. if ($reshook > 0) $result = $hookmanager->resPrint;
  566. else $result .= $hookmanager->resPrint;
  567. return $result;
  568. }
  569. /**
  570. * Return the label of the status
  571. *
  572. * @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
  573. * @return string Label of status
  574. */
  575. public function getLibStatut($mode = 0)
  576. {
  577. return $this->LibStatut($this->status, $mode);
  578. }
  579. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  580. /**
  581. * Return the status
  582. *
  583. * @param int $status Id status
  584. * @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
  585. * @return string Label of status
  586. */
  587. public function LibStatut($status, $mode = 0)
  588. {
  589. // phpcs:enable
  590. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  591. global $langs;
  592. //$langs->load("buypricehistory@buypricehistory");
  593. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  594. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  595. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  596. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  597. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  598. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  599. }
  600. $statusType = 'status'.$status;
  601. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  602. if ($status == self::STATUS_CANCELED) $statusType = 'status6';
  603. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  604. }
  605. /**
  606. * Load the info information in the object
  607. *
  608. * @param int $id Id of object
  609. * @return void
  610. */
  611. public function info($id)
  612. {
  613. $sql = "SELECT rowid, date_creation as datec, tms as datem,";
  614. $sql .= " fk_user_creat, fk_user_modif";
  615. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  616. $sql .= " WHERE t.rowid = ".((int) $id);
  617. $result = $this->db->query($sql);
  618. if ($result) {
  619. if ($this->db->num_rows($result)) {
  620. $obj = $this->db->fetch_object($result);
  621. $this->id = $obj->rowid;
  622. if ($obj->fk_user_author) {
  623. $cuser = new User($this->db);
  624. $cuser->fetch($obj->fk_user_author);
  625. $this->user_creation = $cuser;
  626. }
  627. if ($obj->fk_user_valid) {
  628. $vuser = new User($this->db);
  629. $vuser->fetch($obj->fk_user_valid);
  630. $this->user_validation = $vuser;
  631. }
  632. if ($obj->fk_user_cloture) {
  633. $cluser = new User($this->db);
  634. $cluser->fetch($obj->fk_user_cloture);
  635. $this->user_cloture = $cluser;
  636. }
  637. $this->date_creation = $this->db->jdate($obj->datec);
  638. $this->date_modification = $this->db->jdate($obj->datem);
  639. $this->date_validation = $this->db->jdate($obj->datev);
  640. }
  641. $this->db->free($result);
  642. } else {
  643. dol_print_error($this->db);
  644. }
  645. }
  646. /**
  647. * Initialise object with example values
  648. * Id must be 0 if object instance is a specimen
  649. *
  650. * @return void
  651. */
  652. public function initAsSpecimen()
  653. {
  654. $this->initAsSpecimenCommon();
  655. }
  656. /**
  657. * Returns the reference to the following non used object depending on the active numbering module.
  658. *
  659. * @return string Object free reference
  660. */
  661. public function getNextNumRef()
  662. {
  663. global $langs, $conf;
  664. $langs->load("buypricehistory@buypricehistory");
  665. if (empty($conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON)) {
  666. $conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON = 'mod_productfournisseurprice_standard';
  667. }
  668. if (!empty($conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON)) {
  669. $mybool = false;
  670. $file = $conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON.".php";
  671. $classname = $conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON;
  672. // Include file with class
  673. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  674. foreach ($dirmodels as $reldir) {
  675. $dir = dol_buildpath($reldir."core/modules/buypricehistory/");
  676. // Load file with numbering class (if found)
  677. $mybool |= @include_once $dir.$file;
  678. }
  679. if ($mybool === false) {
  680. dol_print_error('', "Failed to include file ".$file);
  681. return '';
  682. }
  683. if (class_exists($classname)) {
  684. $obj = new $classname();
  685. $numref = $obj->getNextValue($this);
  686. if ($numref != '' && $numref != '-1') {
  687. return $numref;
  688. } else {
  689. $this->error = $obj->error;
  690. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  691. return "";
  692. }
  693. } else {
  694. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  695. return "";
  696. }
  697. } else {
  698. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  699. return "";
  700. }
  701. }
  702. /**
  703. * Create a document onto disk according to template module.
  704. *
  705. * @param string $modele Force template to use ('' to not force)
  706. * @param Translate $outputlangs objet lang a utiliser pour traduction
  707. * @param int $hidedetails Hide details of lines
  708. * @param int $hidedesc Hide description
  709. * @param int $hideref Hide ref
  710. * @param null|array $moreparams Array to provide more information
  711. * @return int 0 if KO, 1 if OK
  712. */
  713. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  714. {
  715. global $conf, $langs;
  716. $result = 0;
  717. $includedocgeneration = 0;
  718. $langs->load("buypricehistory@buypricehistory");
  719. if (!dol_strlen($modele)) {
  720. $modele = 'standard_productfournisseurprice';
  721. if (!empty($this->model_pdf)) {
  722. $modele = $this->model_pdf;
  723. } elseif (!empty($conf->global->PRODUCTFOURNISSEURPRICE_ADDON_PDF)) {
  724. $modele = $conf->global->PRODUCTFOURNISSEURPRICE_ADDON_PDF;
  725. }
  726. }
  727. $modelpath = "core/modules/buypricehistory/doc/";
  728. if ($includedocgeneration && !empty($modele)) {
  729. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  730. }
  731. return $result;
  732. }
  733. }