dolibarr  x.y.z
ajax.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2001-2004 Andreu Bisquerra <jove@bisquerra.com>
3  * Copyright (C) 2020 Thibault FOUCART <support@ptibogxiv.net>
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 
24 if (!defined('NOTOKENRENEWAL')) {
25  define('NOTOKENRENEWAL', '1');
26 }
27 if (!defined('NOREQUIREMENU')) {
28  define('NOREQUIREMENU', '1');
29 }
30 if (!defined('NOREQUIREHTML')) {
31  define('NOREQUIREHTML', '1');
32 }
33 if (!defined('NOREQUIREAJAX')) {
34  define('NOREQUIREAJAX', '1');
35 }
36 if (!defined('NOBROWSERNOTIF')) {
37  define('NOBROWSERNOTIF', '1');
38 }
39 
40 // Load Dolibarr environment
41 require '../../main.inc.php'; // Load $user and permissions
42 require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
43 require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php";
44 
45 $category = GETPOST('category', 'alphanohtml'); // Can be id of category or 'supplements'
46 $action = GETPOST('action', 'aZ09');
47 $term = GETPOST('term', 'alpha');
48 $id = GETPOST('id', 'int');
49 $search_start = GETPOST('search_start', 'int');
50 $search_limit = GETPOST('search_limit', 'int');
51 
52 if (empty($user->rights->takepos->run)) {
54 }
55 
56 // Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
57 $hookmanager->initHooks(array('takeposproductsearch')); // new context for product search hooks
58 
59 
60 /*
61  * View
62  */
63 
64 if ($action == 'getProducts') {
65  top_httphead('application/json');
66 
67  $object = new Categorie($db);
68  if ($category == "supplements") {
69  $category = getDolGlobalInt('TAKEPOS_SUPPLEMENTS_CATEGORY');
70  }
71  $result = $object->fetch($category);
72  if ($result > 0) {
73  $prods = $object->getObjectsInCateg("product", 0, 0, 0, getDolGlobalString('TAKEPOS_SORTPRODUCTFIELD'), 'ASC');
74  // Removed properties we don't need
75  $res = array();
76  if (is_array($prods) && count($prods) > 0) {
77  foreach ($prods as $prod) {
78  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
79  // remove products without stock
80  $prod->load_stock('nobatch,novirtual');
81  if ($prod->stock_warehouse[getDolGlobalString('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])]->real <= 0) {
82  continue;
83  }
84  }
85  unset($prod->fields);
86  unset($prod->db);
87 
88  $prod->price_formated = price(price2num($prod->price, 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
89  $prod->price_ttc_formated = price(price2num($prod->price_ttc, 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
90 
91  $res[] = $prod;
92  }
93  }
94  echo json_encode($res);
95  } else {
96  echo 'Failed to load category with id='.dol_escape_htmltag($category);
97  }
98 } elseif ($action == 'search' && $term != '') {
99  top_httphead('application/json');
100 
101  // Change thirdparty with barcode
102  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
103 
104  $thirdparty = new Societe($db);
105  $result = $thirdparty->fetch('', '', '', $term);
106 
107  if ($result && $thirdparty->id > 0) {
108  $rows = array();
109  $rows[] = array(
110  'rowid' => $thirdparty->id,
111  'name' => $thirdparty->name,
112  'barcode' => $thirdparty->barcode,
113  'object' => 'thirdparty'
114  );
115  echo json_encode($rows);
116  exit;
117  }
118 
119  // Define $filteroncategids, the filter on category ID if there is a Root category defined.
120  $filteroncategids = '';
121  if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { // A root category is defined, we must filter on products inside this category tree
122  $object = new Categorie($db);
123  //$result = $object->fetch($conf->global->TAKEPOS_ROOT_CATEGORY_ID);
124  $arrayofcateg = $object->get_full_arbo('product', $conf->global->TAKEPOS_ROOT_CATEGORY_ID, 1);
125  if (is_array($arrayofcateg) && count($arrayofcateg) > 0) {
126  foreach ($arrayofcateg as $val) {
127  $filteroncategids .= ($filteroncategids ? ', ' : '').$val['id'];
128  }
129  }
130  }
131 
132  $barcode_rules = getDolGlobalString('TAKEPOS_BARCODE_RULE_TO_INSERT_PRODUCT');
133  if (isModEnabled('barcode') && !empty($barcode_rules)) {
134  $barcode_rules_list = array();
135 
136  // get barcode rules
137  $barcode_char_nb = 0;
138  $barcode_rules_arr = explode('+', $barcode_rules);
139  foreach ($barcode_rules_arr as $barcode_rules_values) {
140  $barcode_rules_values_arr = explode(':', $barcode_rules_values);
141  if (count($barcode_rules_values_arr) == 2) {
142  $char_nb = intval($barcode_rules_values_arr[1]);
143  $barcode_rules_list[] = array('code' => $barcode_rules_values_arr[0], 'char_nb' => $char_nb);
144  $barcode_char_nb += $char_nb;
145  }
146  }
147 
148  $barcode_value_list = array();
149  $barcode_offset = 0;
150  $barcode_length = dol_strlen($term);
151  if ($barcode_length == $barcode_char_nb) {
152  $rows = array();
153 
154  // split term with barcode rules
155  foreach ($barcode_rules_list as $barcode_rule_arr) {
156  $code = $barcode_rule_arr['code'];
157  $char_nb = $barcode_rule_arr['char_nb'];
158  $barcode_value_list[$code] = substr($term, $barcode_offset, $char_nb);
159  $barcode_offset += $char_nb;
160  }
161 
162  if (isset($barcode_value_list['ref'])) {
163  // search product from reference
164  $sql = "SELECT rowid, ref, label, tosell, tobuy, barcode, price, price_ttc";
165  $sql .= " FROM " . $db->prefix() . "product as p";
166  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
167  $sql .= " AND ref = '" . $db->escape($barcode_value_list['ref']) . "'";
168  if ($filteroncategids) {
169  $sql .= " AND EXISTS (SELECT cp.fk_product FROM " . $db->prefix() . "categorie_product as cp WHERE cp.fk_product = p.rowid AND cp.fk_categorie IN (".$db->sanitize($filteroncategids)."))";
170  }
171  $sql .= " AND tosell = 1";
172  $sql .= " AND (barcode IS NULL OR barcode != '" . $db->escape($term) . "')";
173 
174  $resql = $db->query($sql);
175  if ($resql && $db->num_rows($resql) == 1) {
176  if ($obj = $db->fetch_object($resql)) {
177  $qty = 1;
178  if (isset($barcode_value_list['qu'])) {
179  $qty_str = $barcode_value_list['qu'];
180  if (isset($barcode_value_list['qd'])) {
181  $qty_str .= '.' . $barcode_value_list['qd'];
182  }
183  $qty = floatval($qty_str);
184  }
185 
186  $ig = '../public/theme/common/nophoto.png';
187  if (empty($conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES)) {
188  $objProd = new Product($db);
189  $objProd->fetch($obj->rowid);
190  $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
191 
192  $match = array();
193  preg_match('@src="([^"]+)"@', $image, $match);
194  $file = array_pop($match);
195 
196  if ($file != '') {
197  if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
198  $ig = $file.'&cache=1';
199  } else {
200  $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
201  }
202  }
203  }
204 
205  $rows[] = array(
206  'rowid' => $obj->rowid,
207  'ref' => $obj->ref,
208  'label' => $obj->label,
209  'tosell' => $obj->tosell,
210  'tobuy' => $obj->tobuy,
211  'barcode' => $obj->barcode,
212  'price' => $obj->price,
213  'price_ttc' => $obj->price_ttc,
214  'object' => 'product',
215  'img' => $ig,
216  'qty' => $qty,
217  );
218  }
219  $db->free($resql);
220  }
221  }
222 
223  if (count($rows) == 1) {
224  echo json_encode($rows);
225  exit();
226  }
227  }
228  }
229 
230  $sql = 'SELECT p.rowid, p.ref, p.label, p.tosell, p.tobuy, p.barcode, p.price, p.price_ttc' ;
231  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
232  $sql .= ', ps.reel';
233  }
234 
235  // Add fields from hooks
236  $parameters = array();
237  $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters);
238  if ($reshook >= 0) {
239  $sql .= $hookmanager->resPrint;
240  }
241 
242  $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
243  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
244  $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps';
245  $sql .= ' ON (p.rowid = ps.fk_product';
246  $sql .= " AND ps.fk_entrepot = ".((int) getDolGlobalInt("CASHDESK_ID_WAREHOUSE".$_SESSION['takeposterminal']));
247  }
248 
249  // Add tables from hooks
250  $parameters = array();
251  $reshook = $hookmanager->executeHooks('printFieldListTables', $parameters);
252  if ($reshook >= 0) {
253  $sql .= $hookmanager->resPrint;
254  }
255 
256  $sql .= ' WHERE entity IN ('.getEntity('product').')';
257  if ($filteroncategids) {
258  $sql .= ' AND EXISTS (SELECT cp.fk_product FROM '.MAIN_DB_PREFIX.'categorie_product as cp WHERE cp.fk_product = p.rowid AND cp.fk_categorie IN ('.$db->sanitize($filteroncategids).'))';
259  }
260  $sql .= ' AND tosell = 1';
261  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
262  $sql .= ' AND ps.reel > 0';
263  }
264  $sql .= natural_search(array('ref', 'label', 'barcode'), $term);
265  // Add where from hooks
266  $parameters = array();
267  $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters);
268  if ($reshook >= 0) {
269  $sql .= $hookmanager->resPrint;
270  }
271 
272  // load only one page of products
273  $sql.= $db->plimit($search_limit, $search_start);
274 
275  $resql = $db->query($sql);
276  if ($resql) {
277  $rows = array();
278 
279  while ($obj = $db->fetch_object($resql)) {
280  $objProd = new Product($db);
281  $objProd->fetch($obj->rowid);
282  $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
283 
284  $match = array();
285  preg_match('@src="([^"]+)"@', $image, $match);
286  $file = array_pop($match);
287 
288  if ($file == "") {
289  $ig = '../public/theme/common/nophoto.png';
290  } else {
291  if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
292  $ig = $file.'&cache=1';
293  } else {
294  $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
295  }
296  }
297 
298  $row = array(
299  'rowid' => $obj->rowid,
300  'ref' => $obj->ref,
301  'label' => $obj->label,
302  'tosell' => $obj->tosell,
303  'tobuy' => $obj->tobuy,
304  'barcode' => $obj->barcode,
305  'price' => $obj->price,
306  'price_ttc' => $obj->price_ttc,
307  'object' => 'product',
308  'img' => $ig,
309  'qty' => 1,
310  'price_formated' => price(price2num($obj->price, 'MT'), 1, $langs, 1, -1, -1, $conf->currency),
311  'price_ttc_formated' => price(price2num($obj->price_ttc, 'MT'), 1, $langs, 1, -1, -1, $conf->currency)
312  );
313  // Add entries to row from hooks
314  $parameters=array();
315  $parameters['row'] = $row;
316  $parameters['obj'] = $obj;
317  $reshook = $hookmanager->executeHooks('completeAjaxReturnArray', $parameters);
318  if ($reshook > 0) {
319  // replace
320  if (count($hookmanager->resArray)) {
321  $row = $hookmanager->resArray;
322  } else {
323  $row = array();
324  }
325  } else {
326  // add
327  if (count($hookmanager->resArray)) {
328  $rows[] = $hookmanager->resArray;
329  }
330  $rows[] = $row;
331  }
332  }
333 
334  echo json_encode($rows);
335  } else {
336  echo 'Failed to search product : '.$db->lasterror();
337  }
338 } elseif ($action == "opendrawer" && $term != '') {
339  require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
340  $printer = new dolReceiptPrinter($db);
341  // check printer for terminal
342  if (getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) {
343  $printer->initPrinter(getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term));
344  // open cashdrawer
345  $printer->pulse();
346  $printer->close();
347  }
348 } elseif ($action == "printinvoiceticket" && $term != '' && $id > 0 && !empty($user->rights->facture->lire)) {
349  require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
350  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
351  $printer = new dolReceiptPrinter($db);
352  // check printer for terminal
353  if ((getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0 || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term) > 0) {
354  $object = new Facture($db);
355  $object->fetch($id);
356  $ret = $printer->sendToPrinter($object, getDolGlobalString('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalString('TAKEPOS_PRINTER_TO_USE'.$term));
357  }
358 } elseif ($action == 'getInvoice') {
359  top_httphead('application/json');
360 
361  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
362 
363  $object = new Facture($db);
364  if ($id > 0) {
365  $object->fetch($id);
366  }
367 
368  echo json_encode($object);
369 } elseif ($action == 'thecheck') {
370  $place = GETPOST('place', 'alpha');
371  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
372  require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
373  $printer = new dolReceiptPrinter($db);
374  $printer->sendToPrinter($object, getDolGlobalString('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalString('TAKEPOS_PRINTER_TO_USE'.$term));
375 }
Class to manage categories.
Class to manage invoices.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Receipt Printers.
if(isModEnabled('facture') &&!empty($user->rights->facture->lire)) if((isModEnabled('fournisseur') &&empty($conf->global->MAIN_USE_NEW_SUPPLIERMOD) && $user->hasRight("fournisseur", "facture", "lire"))||(isModEnabled('supplier_invoice') && $user->hasRight("supplier_invoice", "lire"))) if(isModEnabled('don') &&!empty($user->rights->don->lire)) if(isModEnabled('tax') &&!empty($user->rights->tax->charges->lire)) if(isModEnabled('facture') &&isModEnabled('commande') && $user->hasRight("commande", "lire") &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) $resql
Social contributions to pay.
Definition: index.php:745
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
natural_search($fields, $value, $mode=0, $nofirstand=0)
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
dol_strlen($string, $stringencoding='UTF-8')
Make a strlen call.
price($amount, $form=0, $outlangs='', $trunc=1, $rounding=-1, $forcerounding=-1, $currency_code='')
Function to format a value into an amount for visual output Function used into PDF and HTML pages.
getDolGlobalInt($key, $default=0)
Return dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
if(!function_exists('utf8_encode')) if(!function_exists('utf8_decode')) getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
if(!defined('NOREQUIREMENU')) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1436
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.