dolibarr  16.0.5
price_parser.class.php
Go to the documentation of this file.
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 
23 require_once DOL_DOCUMENT_ROOT.'/core/class/evalmath.class.php';
24 require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
25 require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_expression.class.php';
26 require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_global_variable.class.php';
27 require_once DOL_DOCUMENT_ROOT.'/product/dynamic_price/class/price_global_variable_updater.class.php';
28 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
29 
34 {
35  protected $db;
36  // Limit of expressions per price
37  public $limit = 100;
38  // The error that occurred when parsing price
39  public $error_parser;
40  // The expression that caused the error
41  public $error_expr;
42  //The special char
43  public $special_chr = "#";
44  //The separator char
45  public $separator_chr = ";";
46 
52  public function __construct($db)
53  {
54  $this->db = $db;
55  }
56 
62  public function translatedError()
63  {
64  global $langs;
65  $langs->load("errors");
66  /*
67  -No arg
68  9, an unexpected error occured
69  14, division by zero
70  19, expression not found
71  20, empty expression
72 
73  -1 Arg
74  1, cannot assign to constant '%s'
75  2, cannot redefine built-in function '%s'
76  3, undefined variable '%s' in function definition
77  4, illegal character '%s'
78  5, unexpected '%s'
79  8, unexpected operator '%s'
80  10, operator '%s' lacks operand
81  11, expecting '%s'
82  17, undefined variable '%s'
83  21, empty result '%s'
84  22, negative result '%s'
85  24, variable '%s' exists but has no value
86 
87  -2 Args
88  6, wrong number of arguments (%s given, %s expected)
89  23, unknown or non set variable '%s' after %s
90 
91  -internal errors
92  7, internal error
93  12, internal error
94  13, internal error
95  15, internal error
96  16, internal error
97  18, internal error
98  */
99  if (empty($this->error_parser)) {
100  return $langs->trans("ErrorPriceExpressionUnknown", 0); //this is not supposed to happen
101  }
102  list($code, $info) = $this->error_parser;
103  if (in_array($code, array(9, 14, 19, 20))) { //Errors which have 0 arg
104  return $langs->trans("ErrorPriceExpression".$code);
105  } elseif (in_array($code, array(1, 2, 3, 4, 5, 8, 10, 11, 17, 21, 22))) { //Errors which have 1 arg
106  return $langs->trans("ErrorPriceExpression".$code, $info);
107  } elseif (in_array($code, array(6, 23))) { //Errors which have 2 args
108  return $langs->trans("ErrorPriceExpression".$code, $info[0], $info[1]);
109  } elseif (in_array($code, array(7, 12, 13, 15, 16, 18))) { //Internal errors
110  return $langs->trans("ErrorPriceExpressionInternal", $code);
111  } else //Unknown errors
112  {
113  return $langs->trans("ErrorPriceExpressionUnknown", $code);
114  }
115  }
116 
125  public function parseExpression($product, $expression, $values)
126  {
127  global $user;
128  global $hookmanager;
129  $action = 'PARSEEXPRESSION';
130  if ($result = $hookmanager->executeHooks('doDynamiPrice', array(
131  'expression' =>$expression,
132  'product' => $product,
133  'values' => $values
134  ), $this, $action)) {
135  return $result;
136  }
137  //Check if empty
138  $expression = trim($expression);
139  if (empty($expression)) {
140  $this->error_parser = array(20, null);
141  return -2;
142  }
143 
144  //Accessible product values by expressions
145  $values = array_merge($values, array(
146  "tva_tx" => $product->tva_tx,
147  "localtax1_tx" => $product->localtax1_tx,
148  "localtax2_tx" => $product->localtax2_tx,
149  "weight" => $product->weight,
150  "length" => $product->length,
151  "surface" => $product->surface,
152  "price_min" => $product->price_min,
153  ));
154 
155  //Retrieve all extrafield for product and add it to values
156  $extrafields = new ExtraFields($this->db);
157  $product->fetch_optionals();
158  if (is_array($extrafields->attributes[$product->table_element]['label'])) {
159  foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
160  $values["extrafield_".$key] = $product->array_options['options_'.$key];
161  }
162  }
163 
164  //Process any pending updaters
165  $price_updaters = new PriceGlobalVariableUpdater($this->db);
166  foreach ($price_updaters->listPendingUpdaters() as $entry) {
167  //Schedule the next update by adding current timestamp (secs) + interval (mins)
168  $entry->update_next_update(dol_now() + ($entry->update_interval * 60), $user);
169  //Do processing
170  $res = $entry->process();
171  //Store any error or clear status if OK
172  $entry->update_status($res < 1 ? $entry->error : '', $user);
173  }
174 
175  //Get all global values
176  $price_globals = new PriceGlobalVariable($this->db);
177  foreach ($price_globals->listGlobalVariables() as $entry) {
178  $values["global_".$entry->code] = $entry->value;
179  }
180 
181  //Remove internal variables
182  unset($values["supplier_id"]);
183 
184  //Prepare the lib, parameters and values
185  $em = new EvalMath();
186  $em->suppress_errors = true; //Don't print errors on page
187  $this->error_expr = null;
188  $last_result = null;
189 
190  //Fill each variable in expression from values
191  $expression = str_replace("\n", $this->separator_chr, $expression);
192  foreach ($values as $key => $value) {
193  if ($value === null && strpos($expression, $key) !== false) {
194  $this->error_parser = array(24, $key);
195  return -7;
196  }
197  $expression = str_replace($this->special_chr.$key.$this->special_chr, strval($value), $expression);
198  }
199 
200  //Check if there is unfilled variable
201  if (strpos($expression, $this->special_chr) !== false) {
202  $data = explode($this->special_chr, $expression);
203  $variable = $this->special_chr.$data[1];
204  if (isset($data[2])) {
205  $variable .= $this->special_chr;
206  }
207  $this->error_parser = array(23, array($variable, $expression));
208  return -6;
209  }
210 
211  //Iterate over each expression splitted by $separator_chr
212  $expressions = explode($this->separator_chr, $expression);
213  $expressions = array_slice($expressions, 0, $this->limit);
214  foreach ($expressions as $expr) {
215  $expr = trim($expr);
216  if (!empty($expr)) {
217  $last_result = $em->evaluate($expr);
218  $this->error_parser = $em->last_error_code;
219  if ($this->error_parser !== null) { //$em->last_error_code is null if no error happened, so just check if error_parser is not null
220  $this->error_expr = $expr;
221  return -3;
222  }
223  }
224  }
225  $vars = $em->vars();
226  if (empty($vars["price"])) {
227  $vars["price"] = $last_result;
228  }
229  if (!isset($vars["price"])) {
230  $this->error_parser = array(21, $expression);
231  return -4;
232  }
233  if ($vars["price"] < 0) {
234  $this->error_parser = array(22, $expression);
235  return -5;
236  }
237  return $vars["price"];
238  }
239 
247  public function parseProduct($product, $extra_values = array())
248  {
249  //Get the expression from db
250  $price_expression = new PriceExpression($this->db);
251  $res = $price_expression->fetch($product->fk_price_expression);
252  if ($res < 1) {
253  $this->error_parser = array(19, null);
254  return -1;
255  }
256 
257  //Get the supplier min price
258  $productFournisseur = new ProductFournisseur($this->db);
259  $res = $productFournisseur->find_min_price_product_fournisseur($product->id, 0, 0);
260  if ($res < 0) {
261  $this->error_parser = array(25, null);
262  return -1;
263  } elseif ($res == 0) {
264  $supplier_min_price = 0;
265  $supplier_min_price_with_discount = 0;
266  } else {
267  $supplier_min_price = $productFournisseur->fourn_unitprice;
268  $supplier_min_price_with_discount = $productFournisseur->fourn_unitprice_with_discount;
269  }
270 
271  //Accessible values by expressions
272  $extra_values = array_merge($extra_values, array(
273  "supplier_min_price" => $supplier_min_price,
274  "supplier_min_price_with_discount" => $supplier_min_price_with_discount,
275  ));
276 
277  //Parse the expression and return the price, if not error occurred check if price is higher than min
278  $result = $this->parseExpression($product, $price_expression->expression, $extra_values);
279  if (empty($this->error_parser)) {
280  if ($result < $product->price_min) {
281  $result = $product->price_min;
282  }
283  }
284  return $result;
285  }
286 
294  public function parseProductSupplier($product_supplier, $extra_values = array())
295  {
296  //Get the expression from db
297  $price_expression = new PriceExpression($this->db);
298  $res = $price_expression->fetch($product_supplier->fk_supplier_price_expression);
299  if ($res < 1) {
300  $this->error_parser = array(19, null);
301  return -1;
302  }
303 
304  //Get the product data (use ignore_expression to avoid possible recursion)
305  $product_supplier->fetch($product_supplier->id, '', '', '', 1);
306 
307  //Accessible values by expressions
308  $extra_values = array_merge($extra_values, array(
309  "supplier_quantity" => $product_supplier->fourn_qty,
310  "supplier_tva_tx" => $product_supplier->fourn_tva_tx,
311  ));
312 
313  //Parse the expression and return the price
314  return $this->parseExpression($product_supplier, $price_expression->expression, $extra_values);
315  }
316 
325  public function testExpression($product_id, $expression, $extra_values = array())
326  {
327  //Get the product data
328  $product = new Product($this->db);
329  $product->fetch($product_id, '', '', 1);
330 
331  //Values for product expressions
332  $extra_values = array_merge($extra_values, array(
333  "supplier_min_price" => 1,
334  "supplier_min_price_with_discount" => 2,
335  ));
336 
337  //Values for supplier product expressions
338  $extra_values = array_merge($extra_values, array(
339  "supplier_quantity" => 3,
340  "supplier_tva_tx" => 4,
341  ));
342  return $this->parseExpression($product, $expression, $extra_values);
343  }
344 }
PriceParser\__construct
__construct($db)
Constructor.
Definition: price_parser.class.php:52
PriceParser\translatedError
translatedError()
Returns translated error.
Definition: price_parser.class.php:62
db
$conf db
API class for accounts.
Definition: inc.php:41
PriceExpression
Class for accesing price expression table.
Definition: price_expression.class.php:30
ProductFournisseur
Class to manage predefined suppliers products.
Definition: fournisseur.product.class.php:41
PriceGlobalVariableUpdater
Class for price global variable updaters table.
Definition: price_global_variable_updater.class.php:30
PriceParser
Class to parse product price expressions.
Definition: price_parser.class.php:33
PriceParser\parseProduct
parseProduct($product, $extra_values=array())
Calculates product price based on product id and associated expression.
Definition: price_parser.class.php:247
EvalMath
Class EvalMath.
Definition: evalmath.class.php:97
PriceParser\parseProductSupplier
parseProductSupplier($product_supplier, $extra_values=array())
Calculates supplier product price based on product supplier price and associated expression.
Definition: price_parser.class.php:294
PriceParser\parseExpression
parseExpression($product, $expression, $values)
Calculates price based on expression.
Definition: price_parser.class.php:125
ExtraFields
Class to manage standard extra fields.
Definition: extrafields.class.php:39
Product
Class to manage products or services.
Definition: product.class.php:46
PriceParser\testExpression
testExpression($product_id, $expression, $extra_values=array())
Tests string expression for validity.
Definition: price_parser.class.php:325
dol_now
dol_now($mode='auto')
Return date for now.
Definition: functions.lib.php:2845
PriceGlobalVariable
Class for accesing price global variables table.
Definition: price_global_variable.class.php:30