price_parser.class.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349
  1. <?php
  2. /* Copyright (C) 2015 Ion Agorria <ion@agorria.com>
  3. *
  4. * This program is free software; you can redistribute it and/or modify
  5. * it under the terms of the GNU General Public License as published by
  6. * the Free Software Foundation; either version 3 of the License, or
  7. * (at your option) any later version.
  8. *
  9. * This program is distributed in the hope that it will be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  16. */
  17. /**
  18. * \file htdocs/product/dynamic_price/class/price_parser.class.php
  19. * \ingroup product
  20. * \brief File of class to calculate prices using expression
  21. */
  22. require_once DOL_DOCUMENT_ROOT.'/core/class/evalmath.class.php';
  23. require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
  24. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php';
  25. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_global_variable.class.php';
  26. require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_global_variable_updater.class.php';
  27. require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
  28. /**
  29. * Class to parse product price expressions
  30. */
  31. class PriceParser
  32. {
  33. protected $db;
  34. // Limit of expressions per price
  35. public $limit = 100;
  36. // The error that occurred when parsing price
  37. public $error_parser;
  38. // The expression that caused the error
  39. public $error_expr;
  40. //The special char
  41. public $special_chr = "#";
  42. //The separator char
  43. public $separator_chr = ";";
  44. /**
  45. * Constructor
  46. *
  47. * @param DoliDB $db Database handler
  48. */
  49. public function __construct($db)
  50. {
  51. $this->db = $db;
  52. }
  53. /**
  54. * Returns translated error
  55. *
  56. * @return string Translated error
  57. */
  58. public function translatedError()
  59. {
  60. global $langs;
  61. $langs->load("errors");
  62. /*
  63. -No arg
  64. 9, an unexpected error occured
  65. 14, division by zero
  66. 19, expression not found
  67. 20, empty expression
  68. -1 Arg
  69. 1, cannot assign to constant '%s'
  70. 2, cannot redefine built-in function '%s'
  71. 3, undefined variable '%s' in function definition
  72. 4, illegal character '%s'
  73. 5, unexpected '%s'
  74. 8, unexpected operator '%s'
  75. 10, operator '%s' lacks operand
  76. 11, expecting '%s'
  77. 17, undefined variable '%s'
  78. 21, empty result '%s'
  79. 22, negative result '%s'
  80. 24, variable '%s' exists but has no value
  81. -2 Args
  82. 6, wrong number of arguments (%s given, %s expected)
  83. 23, unknown or non set variable '%s' after %s
  84. -internal errors
  85. 7, internal error
  86. 12, internal error
  87. 13, internal error
  88. 15, internal error
  89. 16, internal error
  90. 18, internal error
  91. */
  92. if (empty($this->error_parser)) {
  93. return $langs->trans("ErrorPriceExpressionUnknown", 0); //this is not supposed to happen
  94. }
  95. list($code, $info) = $this->error_parser;
  96. if (in_array($code, array(9, 14, 19, 20))) { //Errors which have 0 arg
  97. return $langs->trans("ErrorPriceExpression".$code);
  98. } elseif (in_array($code, array(1, 2, 3, 4, 5, 8, 10, 11, 17, 21, 22))) { //Errors which have 1 arg
  99. return $langs->trans("ErrorPriceExpression".$code, $info);
  100. } elseif (in_array($code, array(6, 23))) { //Errors which have 2 args
  101. return $langs->trans("ErrorPriceExpression".$code, $info[0], $info[1]);
  102. } elseif (in_array($code, array(7, 12, 13, 15, 16, 18))) { //Internal errors
  103. return $langs->trans("ErrorPriceExpressionInternal", $code);
  104. } else { //Unknown errors
  105. return $langs->trans("ErrorPriceExpressionUnknown", $code);
  106. }
  107. }
  108. /**
  109. * Calculates price based on expression
  110. *
  111. * @param Product $product The Product object to get information
  112. * @param String $expression The expression to parse
  113. * @param array $values Strings to replaces
  114. * @return int > 0 if OK, < 1 if KO
  115. */
  116. public function parseExpression($product, $expression, $values)
  117. {
  118. global $user, $hookmanager, $extrafields;
  119. $action = 'PARSEEXPRESSION';
  120. if ($reshook = $hookmanager->executeHooks('doDynamiPrice', array(
  121. 'expression' => &$expression,
  122. 'product' => &$product,
  123. 'values' => &$values
  124. ), $this, $action)) {
  125. return $hookmanager->resArray['return'];
  126. }
  127. //Check if empty
  128. $expression = trim($expression);
  129. if (empty($expression)) {
  130. $this->error_parser = array(20, null);
  131. return -2;
  132. }
  133. //Accessible product values by expressions
  134. $values = array_merge($values, array(
  135. "tva_tx" => $product->tva_tx,
  136. "localtax1_tx" => $product->localtax1_tx,
  137. "localtax2_tx" => $product->localtax2_tx,
  138. "weight" => $product->weight,
  139. "length" => $product->length,
  140. "surface" => $product->surface,
  141. "price_min" => $product->price_min,
  142. "cost_price" => $product->cost_price,
  143. "pmp" => $product->pmp,
  144. ));
  145. // Retrieve all extrafields if not already not know (should not happen)
  146. if (! is_object($extrafields)) {
  147. $extrafields = new ExtraFields($this->db);
  148. $extrafields->fetch_name_optionals_label($product->table_element);
  149. }
  150. $product->fetch_optionals();
  151. if (is_array($extrafields->attributes[$product->table_element]['label'])) {
  152. foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
  153. $values["extrafield_".$key] = $product->array_options['options_'.$key];
  154. }
  155. }
  156. //Process any pending updaters
  157. $price_updaters = new PriceGlobalVariableUpdater($this->db);
  158. foreach ($price_updaters->listPendingUpdaters() as $entry) {
  159. //Schedule the next update by adding current timestamp (secs) + interval (mins)
  160. $entry->update_next_update(dol_now() + ($entry->update_interval * 60), $user);
  161. //Do processing
  162. $res = $entry->process();
  163. //Store any error or clear status if OK
  164. $entry->update_status($res < 1 ? $entry->error : '', $user);
  165. }
  166. //Get all global values
  167. $price_globals = new PriceGlobalVariable($this->db);
  168. foreach ($price_globals->listGlobalVariables() as $entry) {
  169. $values["global_".$entry->code] = $entry->value;
  170. }
  171. //Remove internal variables
  172. unset($values["supplier_id"]);
  173. //Prepare the lib, parameters and values
  174. $em = new EvalMath();
  175. $em->suppress_errors = true; //Don't print errors on page
  176. $this->error_expr = null;
  177. $last_result = null;
  178. //Fill each variable in expression from values
  179. $expression = str_replace("\n", $this->separator_chr, $expression);
  180. foreach ($values as $key => $value) {
  181. if ($value === null && strpos($expression, $key) !== false) {
  182. $this->error_parser = array(24, $key);
  183. return -7;
  184. }
  185. $expression = str_replace($this->special_chr.$key.$this->special_chr, strval($value), $expression);
  186. }
  187. //Check if there is unfilled variable
  188. if (strpos($expression, $this->special_chr) !== false) {
  189. $data = explode($this->special_chr, $expression);
  190. $variable = $this->special_chr.$data[1];
  191. if (isset($data[2])) {
  192. $variable .= $this->special_chr;
  193. }
  194. $this->error_parser = array(23, array($variable, $expression));
  195. return -6;
  196. }
  197. //Iterate over each expression splitted by $separator_chr
  198. $expressions = explode($this->separator_chr, $expression);
  199. $expressions = array_slice($expressions, 0, $this->limit);
  200. foreach ($expressions as $expr) {
  201. $expr = trim($expr);
  202. if (!empty($expr)) {
  203. $last_result = $em->evaluate($expr);
  204. $this->error_parser = $em->last_error_code;
  205. if ($this->error_parser !== null) { //$em->last_error_code is null if no error happened, so just check if error_parser is not null
  206. $this->error_expr = $expr;
  207. return -3;
  208. }
  209. }
  210. }
  211. $vars = $em->vars();
  212. if (empty($vars["price"])) {
  213. $vars["price"] = $last_result;
  214. }
  215. if (!isset($vars["price"])) {
  216. $this->error_parser = array(21, $expression);
  217. return -4;
  218. }
  219. if ($vars["price"] < 0) {
  220. $this->error_parser = array(22, $expression);
  221. return -5;
  222. }
  223. return $vars["price"];
  224. }
  225. /**
  226. * Calculates product price based on product id and associated expression
  227. *
  228. * @param Product $product The Product object to get information
  229. * @param array $extra_values Any aditional values for expression
  230. * @return int > 0 if OK, < 1 if KO
  231. */
  232. public function parseProduct($product, $extra_values = array())
  233. {
  234. //Get the expression from db
  235. $price_expression = new PriceExpression($this->db);
  236. $res = $price_expression->fetch($product->fk_price_expression);
  237. if ($res < 1) {
  238. $this->error_parser = array(19, null);
  239. return -1;
  240. }
  241. //Get the supplier min price
  242. $productFournisseur = new ProductFournisseur($this->db);
  243. $res = $productFournisseur->find_min_price_product_fournisseur($product->id, 0, 0);
  244. if ($res < 0) {
  245. $this->error_parser = array(25, null);
  246. return -1;
  247. } elseif ($res == 0) {
  248. $supplier_min_price = 0;
  249. $supplier_min_price_with_discount = 0;
  250. } else {
  251. $supplier_min_price = $productFournisseur->fourn_unitprice;
  252. $supplier_min_price_with_discount = $productFournisseur->fourn_unitprice_with_discount;
  253. }
  254. //Accessible values by expressions
  255. $extra_values = array_merge($extra_values, array(
  256. "supplier_min_price" => $supplier_min_price,
  257. "supplier_min_price_with_discount" => $supplier_min_price_with_discount,
  258. ));
  259. //Parse the expression and return the price, if not error occurred check if price is higher than min
  260. $result = $this->parseExpression($product, $price_expression->expression, $extra_values);
  261. if (empty($this->error_parser)) {
  262. if ($result < $product->price_min) {
  263. $result = $product->price_min;
  264. }
  265. }
  266. return $result;
  267. }
  268. /**
  269. * Calculates supplier product price based on product supplier price and associated expression
  270. *
  271. * @param ProductFournisseur $product_supplier The Product supplier object to get information
  272. * @param array $extra_values Any aditional values for expression
  273. * @return int > 0 if OK, < 1 if KO
  274. */
  275. public function parseProductSupplier($product_supplier, $extra_values = array())
  276. {
  277. //Get the expression from db
  278. $price_expression = new PriceExpression($this->db);
  279. $res = $price_expression->fetch($product_supplier->fk_supplier_price_expression);
  280. if ($res < 1) {
  281. $this->error_parser = array(19, null);
  282. return -1;
  283. }
  284. //Get the product data (use ignore_expression to avoid possible recursion)
  285. $product_supplier->fetch($product_supplier->id, '', '', '', 1);
  286. //Accessible values by expressions
  287. $extra_values = array_merge($extra_values, array(
  288. "supplier_quantity" => $product_supplier->fourn_qty,
  289. "supplier_tva_tx" => $product_supplier->fourn_tva_tx,
  290. ));
  291. //Parse the expression and return the price
  292. return $this->parseExpression($product_supplier, $price_expression->expression, $extra_values);
  293. }
  294. /**
  295. * Tests string expression for validity
  296. *
  297. * @param int $product_id The Product id to get information
  298. * @param string $expression The expression to parse
  299. * @param array $extra_values Any aditional values for expression
  300. * @return int > 0 if OK, < 1 if KO
  301. */
  302. public function testExpression($product_id, $expression, $extra_values = array())
  303. {
  304. //Get the product data
  305. $product = new Product($this->db);
  306. $product->fetch($product_id, '', '', 1);
  307. //Values for product expressions
  308. $extra_values = array_merge($extra_values, array(
  309. "supplier_min_price" => 1,
  310. "supplier_min_price_with_discount" => 2,
  311. ));
  312. //Values for supplier product expressions
  313. $extra_values = array_merge($extra_values, array(
  314. "supplier_quantity" => 3,
  315. "supplier_tva_tx" => 4,
  316. ));
  317. return $this->parseExpression($product, $expression, $extra_values);
  318. }
  319. }