productfournisseurprice.class.php 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883
  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 (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid'])) {
  166. $this->fields['rowid']['visible'] = 0;
  167. }
  168. if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
  169. $this->fields['entity']['enabled'] = 0;
  170. }
  171. // Unset fields that are disabled
  172. foreach ($this->fields as $key => $val) {
  173. if (isset($val['enabled']) && empty($val['enabled'])) {
  174. unset($this->fields[$key]);
  175. }
  176. }
  177. }
  178. /**
  179. * Create object into database
  180. *
  181. * @param User $user User that creates
  182. * @param bool $notrigger false=launch triggers after, true=disable triggers
  183. * @return int Return integer <0 if KO, Id of created object if OK
  184. */
  185. public function create(User $user, $notrigger = false)
  186. {
  187. return $this->createCommon($user, $notrigger);
  188. }
  189. /**
  190. * Clone an object into another one
  191. *
  192. * @param User $user User that creates
  193. * @param int $fromid Id of object to clone
  194. * @return mixed New object created, <0 if KO
  195. */
  196. public function createFromClone(User $user, $fromid)
  197. {
  198. global $langs, $extrafields;
  199. $error = 0;
  200. dol_syslog(__METHOD__, LOG_DEBUG);
  201. $object = new self($this->db);
  202. $this->db->begin();
  203. // Load source object
  204. $result = $object->fetchCommon($fromid);
  205. if ($result > 0 && !empty($object->table_element_line)) {
  206. $object->fetchLines();
  207. }
  208. // get lines so they will be clone
  209. //foreach($this->lines as $line)
  210. // $line->fetch_optionals();
  211. // Reset some properties
  212. unset($object->id);
  213. unset($object->fk_user_creat);
  214. unset($object->import_key);
  215. // Clear fields
  216. if (property_exists($object, 'ref')) {
  217. $object->ref = empty($this->fields['ref']['default']) ? "Copy_Of_".$object->ref : $this->fields['ref']['default'];
  218. }
  219. if (property_exists($object, 'label')) {
  220. $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf")." ".$object->label : $this->fields['label']['default'];
  221. }
  222. if (property_exists($object, 'status')) {
  223. $object->status = self::STATUS_DRAFT;
  224. }
  225. if (property_exists($object, 'date_creation')) {
  226. $object->date_creation = dol_now();
  227. }
  228. if (property_exists($object, 'date_modification')) {
  229. $object->date_modification = null;
  230. }
  231. // ...
  232. // Clear extrafields that are unique
  233. if (is_array($object->array_options) && count($object->array_options) > 0) {
  234. $extrafields->fetch_name_optionals_label($this->table_element);
  235. foreach ($object->array_options as $key => $option) {
  236. $shortkey = preg_replace('/options_/', '', $key);
  237. if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
  238. //var_dump($key);
  239. //var_dump($clonedObj->array_options[$key]); exit;
  240. unset($object->array_options[$key]);
  241. }
  242. }
  243. }
  244. // Create clone
  245. $object->context['createfromclone'] = 'createfromclone';
  246. $result = $object->createCommon($user);
  247. if ($result < 0) {
  248. $error++;
  249. $this->error = $object->error;
  250. $this->errors = $object->errors;
  251. }
  252. if (!$error) {
  253. // copy internal contacts
  254. if ($this->copy_linked_contact($object, 'internal') < 0) {
  255. $error++;
  256. }
  257. }
  258. if (!$error) {
  259. // copy external contacts if same company
  260. if (property_exists($this, 'socid') && $this->socid == $object->socid) {
  261. if ($this->copy_linked_contact($object, 'external') < 0) {
  262. $error++;
  263. }
  264. }
  265. }
  266. unset($object->context['createfromclone']);
  267. // End
  268. if (!$error) {
  269. $this->db->commit();
  270. return $object;
  271. } else {
  272. $this->db->rollback();
  273. return -1;
  274. }
  275. }
  276. /**
  277. * Load object in memory from the database
  278. *
  279. * @param int $id Id object
  280. * @return int Return integer <0 if KO, 0 if not found, >0 if OK
  281. */
  282. public function fetch($id)
  283. {
  284. return $this->fetchCommon($id);
  285. }
  286. /**
  287. * Load list of objects in memory from the database.
  288. *
  289. * @param string $sortorder Sort Order
  290. * @param string $sortfield Sort field
  291. * @param int $limit limit
  292. * @param int $offset Offset
  293. * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
  294. * @param string $filtermode Filter mode (AND or OR)
  295. * @return array|int int <0 if KO, array of pages if OK
  296. */
  297. public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
  298. {
  299. global $conf;
  300. dol_syslog(__METHOD__, LOG_DEBUG);
  301. $records = array();
  302. $sql = "SELECT ";
  303. $sql .= $this->getFieldList();
  304. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  305. if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
  306. $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
  307. } else {
  308. $sql .= " WHERE 1 = 1";
  309. }
  310. // Manage filter
  311. $sqlwhere = array();
  312. if (count($filter) > 0) {
  313. foreach ($filter as $key => $value) {
  314. if ($key == 't.rowid') {
  315. $sqlwhere[] = $key." = ".((int) $value);
  316. } elseif (array_key_exists($key, $this->fields) && in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
  317. $sqlwhere[] = $key." = '".$this->db->idate($value)."'";
  318. } elseif ($key == 'customsql') {
  319. $sqlwhere[] = $value;
  320. } elseif (strpos($value, '%') === false) {
  321. $sqlwhere[] = $key.' IN ('.$this->db->sanitize($this->db->escape($value)).')';
  322. } else {
  323. $sqlwhere[] = $key." LIKE '%".$this->db->escape($value)."%'";
  324. }
  325. }
  326. }
  327. if (count($sqlwhere) > 0) {
  328. $sql .= ' AND ('.implode(' '.$this->db->escape($filtermode).' ', $sqlwhere).')';
  329. }
  330. if (!empty($sortfield)) {
  331. $sql .= $this->db->order($sortfield, $sortorder);
  332. }
  333. if (!empty($limit)) {
  334. $sql .= $this->db->plimit($limit, $offset);
  335. }
  336. $resql = $this->db->query($sql);
  337. if ($resql) {
  338. $num = $this->db->num_rows($resql);
  339. $i = 0;
  340. while ($i < ($limit ? min($limit, $num) : $num)) {
  341. $obj = $this->db->fetch_object($resql);
  342. $record = new self($this->db);
  343. $record->setVarsFromFetchObj($obj);
  344. $records[$record->id] = $record;
  345. $i++;
  346. }
  347. $this->db->free($resql);
  348. return $records;
  349. } else {
  350. $this->errors[] = 'Error '.$this->db->lasterror();
  351. dol_syslog(__METHOD__.' '.join(',', $this->errors), LOG_ERR);
  352. return -1;
  353. }
  354. }
  355. /**
  356. * Update object into database
  357. *
  358. * @param User $user User that modifies
  359. * @param bool $notrigger false=launch triggers after, true=disable triggers
  360. * @return int Return integer <0 if KO, >0 if OK
  361. */
  362. public function update(User $user, $notrigger = false)
  363. {
  364. return $this->updateCommon($user, $notrigger);
  365. }
  366. /**
  367. * Delete object in database
  368. *
  369. * @param User $user User that deletes
  370. * @param bool $notrigger false=launch triggers after, true=disable triggers
  371. * @return int Return integer <0 if KO, >0 if OK
  372. */
  373. public function delete(User $user, $notrigger = false)
  374. {
  375. return $this->deleteCommon($user, $notrigger);
  376. }
  377. /**
  378. * Validate object
  379. *
  380. * @param User $user User making status change
  381. * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
  382. * @return int Return integer <=0 if OK, 0=Nothing done, >0 if KO
  383. */
  384. public function validate($user, $notrigger = 0)
  385. {
  386. global $conf, $langs;
  387. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  388. $error = 0;
  389. // Protection
  390. if ($this->status == self::STATUS_VALIDATED) {
  391. dol_syslog(get_class($this)."::validate action abandonned: already validated", LOG_WARNING);
  392. return 0;
  393. }
  394. $now = dol_now();
  395. $this->db->begin();
  396. // Define new ref
  397. if (!$error && (preg_match('/^[\(]?PROV/i', $this->ref) || empty($this->ref))) { // empty should not happened, but when it occurs, the test save life
  398. $num = $this->getNextNumRef();
  399. } else {
  400. $num = $this->ref;
  401. }
  402. $this->newref = $num;
  403. if (!empty($num)) {
  404. // Validate
  405. $sql = "UPDATE ".$this->db->prefix().$this->table_element;
  406. $sql .= " SET ref = '".$this->db->escape($num)."',";
  407. $sql .= " status = ".self::STATUS_VALIDATED;
  408. if (!empty($this->fields['date_validation'])) {
  409. $sql .= ", date_validation = '".$this->db->idate($now)."'";
  410. }
  411. if (!empty($this->fields['fk_user_valid'])) {
  412. $sql .= ", fk_user_valid = ".$user->id;
  413. }
  414. $sql .= " WHERE rowid = ".((int) $this->id);
  415. dol_syslog(get_class($this)."::validate()", LOG_DEBUG);
  416. $resql = $this->db->query($sql);
  417. if (!$resql) {
  418. dol_print_error($this->db);
  419. $this->error = $this->db->lasterror();
  420. $error++;
  421. }
  422. if (!$error && !$notrigger) {
  423. // Call trigger
  424. $result = $this->call_trigger('PRODUCTFOURNISSEURPRICE_VALIDATE', $user);
  425. if ($result < 0) {
  426. $error++;
  427. }
  428. // End call triggers
  429. }
  430. }
  431. if (!$error) {
  432. $this->oldref = $this->ref;
  433. // Rename directory if dir was a temporary ref
  434. if (preg_match('/^[\(]?PROV/i', $this->ref)) {
  435. // Now we rename also files into index
  436. $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)."'";
  437. $sql .= " WHERE filename LIKE '".$this->db->escape($this->ref)."%' AND filepath = 'productfournisseurprice/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  438. $resql = $this->db->query($sql);
  439. if (!$resql) {
  440. $error++;
  441. $this->error = $this->db->lasterror();
  442. }
  443. $sql = 'UPDATE '.MAIN_DB_PREFIX."ecm_files set filepath = 'productfournisseurprice/".$this->db->escape($this->newref)."'";
  444. $sql .= " WHERE filepath = 'productfournisseurprice/".$this->db->escape($this->ref)."' and entity = ".$conf->entity;
  445. $resql = $this->db->query($sql);
  446. if (!$resql) {
  447. $error++;
  448. $this->error = $this->db->lasterror();
  449. }
  450. // We rename directory ($this->ref = old ref, $num = new ref) in order not to lose the attachments
  451. $oldref = dol_sanitizeFileName($this->ref);
  452. $newref = dol_sanitizeFileName($num);
  453. $dirsource = $conf->buypricehistory->dir_output.'/productfournisseurprice/'.$oldref;
  454. $dirdest = $conf->buypricehistory->dir_output.'/productfournisseurprice/'.$newref;
  455. if (!$error && file_exists($dirsource)) {
  456. dol_syslog(get_class($this)."::validate() rename dir ".$dirsource." into ".$dirdest);
  457. if (@rename($dirsource, $dirdest)) {
  458. dol_syslog("Rename ok");
  459. // Rename docs starting with $oldref with $newref
  460. $listoffiles = dol_dir_list($conf->buypricehistory->dir_output.'/productfournisseurprice/'.$newref, 'files', 1, '^'.preg_quote($oldref, '/'));
  461. foreach ($listoffiles as $fileentry) {
  462. $dirsource = $fileentry['name'];
  463. $dirdest = preg_replace('/^'.preg_quote($oldref, '/').'/', $newref, $dirsource);
  464. $dirsource = $fileentry['path'].'/'.$dirsource;
  465. $dirdest = $fileentry['path'].'/'.$dirdest;
  466. @rename($dirsource, $dirdest);
  467. }
  468. }
  469. }
  470. }
  471. }
  472. // Set new ref and current status
  473. if (!$error) {
  474. $this->ref = $num;
  475. $this->status = self::STATUS_VALIDATED;
  476. }
  477. if (!$error) {
  478. $this->db->commit();
  479. return 1;
  480. } else {
  481. $this->db->rollback();
  482. return -1;
  483. }
  484. }
  485. /**
  486. * Set draft status
  487. *
  488. * @param User $user Object user that modify
  489. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  490. * @return int Return integer <0 if KO, >0 if OK
  491. */
  492. public function setDraft($user, $notrigger = 0)
  493. {
  494. // Protection
  495. if ($this->status <= self::STATUS_DRAFT) {
  496. return 0;
  497. }
  498. return $this->setStatusCommon($user, self::STATUS_DRAFT, $notrigger, 'PRODUCTFOURNISSEURPRICE_UNVALIDATE');
  499. }
  500. /**
  501. * Set cancel status
  502. *
  503. * @param User $user Object user that modify
  504. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  505. * @return int Return integer <0 if KO, 0=Nothing done, >0 if OK
  506. */
  507. public function cancel($user, $notrigger = 0)
  508. {
  509. // Protection
  510. if ($this->status != self::STATUS_VALIDATED) {
  511. return 0;
  512. }
  513. return $this->setStatusCommon($user, self::STATUS_CANCELED, $notrigger, 'PRODUCTFOURNISSEURPRICE_CANCEL');
  514. }
  515. /**
  516. * Set back to validated status
  517. *
  518. * @param User $user Object user that modify
  519. * @param int $notrigger 1=Does not execute triggers, 0=Execute triggers
  520. * @return int Return integer <0 if KO, 0=Nothing done, >0 if OK
  521. */
  522. public function reopen($user, $notrigger = 0)
  523. {
  524. // Protection
  525. if ($this->status != self::STATUS_CANCELED) {
  526. return 0;
  527. }
  528. return $this->setStatusCommon($user, self::STATUS_VALIDATED, $notrigger, 'PRODUCTFOURNISSEURPRICE_REOPEN');
  529. }
  530. /**
  531. * Return a link to the object card (with optionaly the picto)
  532. *
  533. * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
  534. * @param string $option On what the link point to ('nolink', ...)
  535. * @param int $notooltip 1=Disable tooltip
  536. * @param string $morecss Add more css on link
  537. * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
  538. * @return string String with URL
  539. */
  540. public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
  541. {
  542. global $conf, $langs, $hookmanager;
  543. if (!empty($conf->dol_no_mouse_hover)) {
  544. $notooltip = 1;
  545. } // Force disable tooltips
  546. $result = '';
  547. $label = img_picto('', $this->picto).' <u>'.$langs->trans("ProductFournisseurPrice").'</u>';
  548. if (isset($this->status)) {
  549. $label .= ' '.$this->getLibStatut(5);
  550. }
  551. $label .= '<br>';
  552. $label .= '<b>'.$langs->trans('Ref').':</b> '.$this->ref;
  553. $url = dol_buildpath('/buypricehistory/productfournisseurprice_card.php', 1).'?id='.$this->id;
  554. if ($option != 'nolink') {
  555. // Add param to save lastsearch_values or not
  556. $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
  557. if ($save_lastsearch_value == -1 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
  558. $add_save_lastsearch_values = 1;
  559. }
  560. if ($add_save_lastsearch_values) {
  561. $url .= '&save_lastsearch_values=1';
  562. }
  563. }
  564. $linkclose = '';
  565. if (empty($notooltip)) {
  566. if (getDolGlobalString('MAIN_OPTIMIZEFORTEXTBROWSER')) {
  567. $label = $langs->trans("ShowProductFournisseurPrice");
  568. $linkclose .= ' alt="'.dol_escape_htmltag($label, 1).'"';
  569. }
  570. $linkclose .= ' title="'.dol_escape_htmltag($label, 1).'"';
  571. $linkclose .= ' class="classfortooltip'.($morecss ? ' '.$morecss : '').'"';
  572. } else {
  573. $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
  574. }
  575. $linkstart = '<a href="'.$url.'"';
  576. $linkstart .= $linkclose.'>';
  577. $linkend = '</a>';
  578. $result .= $linkstart;
  579. if (empty($this->showphoto_on_popup)) {
  580. if ($withpicto) {
  581. $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);
  582. }
  583. } else {
  584. if ($withpicto) {
  585. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  586. list($class, $module) = explode('@', $this->picto);
  587. $upload_dir = $conf->$module->multidir_output[$conf->entity]."/$class/".dol_sanitizeFileName($this->ref);
  588. $filearray = dol_dir_list($upload_dir, "files");
  589. $filename = $filearray[0]['name'];
  590. if (!empty($filename)) {
  591. $pospoint = strpos($filearray[0]['name'], '.');
  592. $pathtophoto = $class.'/'.$this->ref.'/thumbs/'.substr($filename, 0, $pospoint).'_mini'.substr($filename, $pospoint);
  593. if (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
  594. $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>';
  595. } else {
  596. $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>';
  597. }
  598. $result .= '</div>';
  599. } else {
  600. $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);
  601. }
  602. }
  603. }
  604. if ($withpicto != 2) {
  605. $result .= $this->ref;
  606. }
  607. $result .= $linkend;
  608. //if ($withpicto != 2) $result.=(($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');
  609. global $action, $hookmanager;
  610. $hookmanager->initHooks(array('productfournisseurpricedao'));
  611. $parameters = array('id'=>$this->id, 'getnomurl' => &$result);
  612. $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  613. if ($reshook > 0) {
  614. $result = $hookmanager->resPrint;
  615. } else {
  616. $result .= $hookmanager->resPrint;
  617. }
  618. return $result;
  619. }
  620. /**
  621. * Return the label of the status
  622. *
  623. * @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
  624. * @return string Label of status
  625. */
  626. public function getLibStatut($mode = 0)
  627. {
  628. return $this->LibStatut($this->status, $mode);
  629. }
  630. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  631. /**
  632. * Return the status
  633. *
  634. * @param int $status Id status
  635. * @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
  636. * @return string Label of status
  637. */
  638. public function LibStatut($status, $mode = 0)
  639. {
  640. // phpcs:enable
  641. if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
  642. global $langs;
  643. //$langs->load("buypricehistory@buypricehistory");
  644. $this->labelStatus[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  645. $this->labelStatus[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  646. $this->labelStatus[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  647. $this->labelStatusShort[self::STATUS_DRAFT] = $langs->transnoentitiesnoconv('Draft');
  648. $this->labelStatusShort[self::STATUS_VALIDATED] = $langs->transnoentitiesnoconv('Enabled');
  649. $this->labelStatusShort[self::STATUS_CANCELED] = $langs->transnoentitiesnoconv('Disabled');
  650. }
  651. $statusType = 'status'.$status;
  652. //if ($status == self::STATUS_VALIDATED) $statusType = 'status1';
  653. if ($status == self::STATUS_CANCELED) {
  654. $statusType = 'status6';
  655. }
  656. return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
  657. }
  658. /**
  659. * Load the info information in the object
  660. *
  661. * @param int $id Id of object
  662. * @return void
  663. */
  664. public function info($id)
  665. {
  666. $sql = "SELECT rowid, date_creation as datec, tms as datem,";
  667. $sql .= " fk_user_creat, fk_user_modif";
  668. $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
  669. $sql .= " WHERE t.rowid = ".((int) $id);
  670. $result = $this->db->query($sql);
  671. if ($result) {
  672. if ($this->db->num_rows($result)) {
  673. $obj = $this->db->fetch_object($result);
  674. $this->id = $obj->rowid;
  675. $this->user_creation_id = $obj->fk_user_author;
  676. $this->user_validation_id = $obj->fk_user_valid;
  677. $this->date_creation = $this->db->jdate($obj->datec);
  678. $this->date_modification = $this->db->jdate($obj->datem);
  679. }
  680. $this->db->free($result);
  681. } else {
  682. dol_print_error($this->db);
  683. }
  684. }
  685. /**
  686. * Initialise object with example values
  687. * Id must be 0 if object instance is a specimen
  688. *
  689. * @return void
  690. */
  691. public function initAsSpecimen()
  692. {
  693. $this->initAsSpecimenCommon();
  694. }
  695. /**
  696. * Returns the reference to the following non used object depending on the active numbering module.
  697. *
  698. * @return string Object free reference
  699. */
  700. public function getNextNumRef()
  701. {
  702. global $langs, $conf;
  703. $langs->load("buypricehistory@buypricehistory");
  704. if (!getDolGlobalString('BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON')) {
  705. $conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON = 'mod_productfournisseurprice_standard';
  706. }
  707. if (getDolGlobalString('BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON')) {
  708. $mybool = false;
  709. $file = getDolGlobalString('BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON') . ".php";
  710. $classname = $conf->global->BUYPRICEHISTORY_PRODUCTFOURNISSEURPRICE_ADDON;
  711. // Include file with class
  712. $dirmodels = array_merge(array('/'), (array) $conf->modules_parts['models']);
  713. foreach ($dirmodels as $reldir) {
  714. $dir = dol_buildpath($reldir."core/modules/buypricehistory/");
  715. // Load file with numbering class (if found)
  716. $mybool |= @include_once $dir.$file;
  717. }
  718. if ($mybool === false) {
  719. dol_print_error('', "Failed to include file ".$file);
  720. return '';
  721. }
  722. if (class_exists($classname)) {
  723. $obj = new $classname();
  724. $numref = $obj->getNextValue($this);
  725. if ($numref != '' && $numref != '-1') {
  726. return $numref;
  727. } else {
  728. $this->error = $obj->error;
  729. //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
  730. return "";
  731. }
  732. } else {
  733. print $langs->trans("Error")." ".$langs->trans("ClassNotFound").' '.$classname;
  734. return "";
  735. }
  736. } else {
  737. print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
  738. return "";
  739. }
  740. }
  741. /**
  742. * Create a document onto disk according to template module.
  743. *
  744. * @param string $modele Force template to use ('' to not force)
  745. * @param Translate $outputlangs objet lang a utiliser pour traduction
  746. * @param int $hidedetails Hide details of lines
  747. * @param int $hidedesc Hide description
  748. * @param int $hideref Hide ref
  749. * @param null|array $moreparams Array to provide more information
  750. * @return int 0 if KO, 1 if OK
  751. */
  752. public function generateDocument($modele, $outputlangs, $hidedetails = 0, $hidedesc = 0, $hideref = 0, $moreparams = null)
  753. {
  754. global $conf, $langs;
  755. $result = 0;
  756. $includedocgeneration = 0;
  757. $langs->load("buypricehistory@buypricehistory");
  758. if (!dol_strlen($modele)) {
  759. $modele = 'standard_productfournisseurprice';
  760. if (!empty($this->model_pdf)) {
  761. $modele = $this->model_pdf;
  762. } elseif (getDolGlobalString('PRODUCTFOURNISSEURPRICE_ADDON_PDF')) {
  763. $modele = $conf->global->PRODUCTFOURNISSEURPRICE_ADDON_PDF;
  764. }
  765. }
  766. $modelpath = "core/modules/buypricehistory/doc/";
  767. if ($includedocgeneration && !empty($modele)) {
  768. $result = $this->commonGenerateDocument($modelpath, $modele, $outputlangs, $hidedetails, $hidedesc, $hideref, $moreparams);
  769. }
  770. return $result;
  771. }
  772. }