dolibarr  19.0.0-dev
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  $tosell = GETPOSTISSET('tosell') ? GETPOST('tosell', 'int') : '';
66  $limit = GETPOSTISSET('limit') ? GETPOST('limit', 'int') : 0;
67  $offset = GETPOSTISSET('offset') ? GETPOST('offset', 'int') : 0;
68 
69  top_httphead('application/json');
70 
71  $object = new Categorie($db);
72  if ($category == "supplements") {
73  $category = getDolGlobalInt('TAKEPOS_SUPPLEMENTS_CATEGORY');
74  if (empty($category)) {
75  echo 'Error, the category to use for supplements is not defined. Go into setup of module TakePOS.';
76  exit;
77  }
78  }
79 
80  $result = $object->fetch($category);
81  if ($result > 0) {
82  $filter = array();
83  if ($tosell != '') {
84  $filter = array('customsql' => 'o.tosell = '.((int) $tosell));
85  }
86  $prods = $object->getObjectsInCateg("product", 0, $limit, $offset, getDolGlobalString('TAKEPOS_SORTPRODUCTFIELD'), 'ASC', $filter);
87  // Removed properties we don't need
88  $res = array();
89  if (is_array($prods) && count($prods) > 0) {
90  foreach ($prods as $prod) {
91  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
92  // remove products without stock
93  $prod->load_stock('nobatch,novirtual');
94  if ($prod->stock_warehouse[getDolGlobalString('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])]->real <= 0) {
95  continue;
96  }
97  }
98  unset($prod->fields);
99  unset($prod->db);
100 
101  $prod->price_formated = price(price2num($prod->price, 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
102  $prod->price_ttc_formated = price(price2num($prod->price_ttc, 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
103 
104  $res[] = $prod;
105  }
106  }
107  echo json_encode($res);
108  } else {
109  echo 'Failed to load category with id='.dol_escape_htmltag($category);
110  }
111 } elseif ($action == 'search' && $term != '') {
112  top_httphead('application/json');
113 
114  // Change thirdparty with barcode
115  require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
116 
117  $thirdparty = new Societe($db);
118  $result = $thirdparty->fetch('', '', '', $term);
119 
120  if ($result && $thirdparty->id > 0) {
121  $rows = array();
122  $rows[] = array(
123  'rowid' => $thirdparty->id,
124  'name' => $thirdparty->name,
125  'barcode' => $thirdparty->barcode,
126  'object' => 'thirdparty'
127  );
128  echo json_encode($rows);
129  exit;
130  }
131 
132  // Define $filteroncategids, the filter on category ID if there is a Root category defined.
133  $filteroncategids = '';
134  if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { // A root category is defined, we must filter on products inside this category tree
135  $object = new Categorie($db);
136  //$result = $object->fetch($conf->global->TAKEPOS_ROOT_CATEGORY_ID);
137  $arrayofcateg = $object->get_full_arbo('product', $conf->global->TAKEPOS_ROOT_CATEGORY_ID, 1);
138  if (is_array($arrayofcateg) && count($arrayofcateg) > 0) {
139  foreach ($arrayofcateg as $val) {
140  $filteroncategids .= ($filteroncategids ? ', ' : '').$val['id'];
141  }
142  }
143  }
144 
145  $barcode_rules = getDolGlobalString('TAKEPOS_BARCODE_RULE_TO_INSERT_PRODUCT');
146  if (isModEnabled('barcode') && !empty($barcode_rules)) {
147  $barcode_rules_list = array();
148 
149  // get barcode rules
150  $barcode_char_nb = 0;
151  $barcode_rules_arr = explode('+', $barcode_rules);
152  foreach ($barcode_rules_arr as $barcode_rules_values) {
153  $barcode_rules_values_arr = explode(':', $barcode_rules_values);
154  if (count($barcode_rules_values_arr) == 2) {
155  $char_nb = intval($barcode_rules_values_arr[1]);
156  $barcode_rules_list[] = array('code' => $barcode_rules_values_arr[0], 'char_nb' => $char_nb);
157  $barcode_char_nb += $char_nb;
158  }
159  }
160 
161  $barcode_value_list = array();
162  $barcode_offset = 0;
163  $barcode_length = dol_strlen($term);
164  if ($barcode_length == $barcode_char_nb) {
165  $rows = array();
166 
167  // split term with barcode rules
168  foreach ($barcode_rules_list as $barcode_rule_arr) {
169  $code = $barcode_rule_arr['code'];
170  $char_nb = $barcode_rule_arr['char_nb'];
171  $barcode_value_list[$code] = substr($term, $barcode_offset, $char_nb);
172  $barcode_offset += $char_nb;
173  }
174 
175  if (isset($barcode_value_list['ref'])) {
176  // search product from reference
177  $sql = "SELECT rowid, ref, label, tosell, tobuy, barcode, price, price_ttc";
178  $sql .= " FROM " . $db->prefix() . "product as p";
179  $sql .= " WHERE entity IN (" . getEntity('product') . ")";
180  $sql .= " AND ref = '" . $db->escape($barcode_value_list['ref']) . "'";
181  if ($filteroncategids) {
182  $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)."))";
183  }
184  $sql .= " AND tosell = 1";
185  $sql .= " AND (barcode IS NULL OR barcode <> '" . $db->escape($term) . "')";
186 
187  $resql = $db->query($sql);
188  if ($resql && $db->num_rows($resql) == 1) {
189  if ($obj = $db->fetch_object($resql)) {
190  $qty = 1;
191  if (isset($barcode_value_list['qu'])) {
192  $qty_str = $barcode_value_list['qu'];
193  if (isset($barcode_value_list['qd'])) {
194  $qty_str .= '.' . $barcode_value_list['qd'];
195  }
196  $qty = floatval($qty_str);
197  }
198 
199  $ig = '../public/theme/common/nophoto.png';
200  if (empty($conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES)) {
201  $objProd = new Product($db);
202  $objProd->fetch($obj->rowid);
203  $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
204 
205  $match = array();
206  preg_match('@src="([^"]+)"@', $image, $match);
207  $file = array_pop($match);
208 
209  if ($file != '') {
210  if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
211  $ig = $file.'&cache=1';
212  } else {
213  $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
214  }
215  }
216  }
217 
218  $rows[] = array(
219  'rowid' => $obj->rowid,
220  'ref' => $obj->ref,
221  'label' => $obj->label,
222  'tosell' => $obj->tosell,
223  'tobuy' => $obj->tobuy,
224  'barcode' => $obj->barcode,
225  'price' => $obj->price,
226  'price_ttc' => $obj->price_ttc,
227  'object' => 'product',
228  'img' => $ig,
229  'qty' => $qty,
230  );
231  }
232  $db->free($resql);
233  }
234  }
235 
236  if (count($rows) == 1) {
237  echo json_encode($rows);
238  exit();
239  }
240  }
241  }
242 
243  $sql = 'SELECT p.rowid, p.ref, p.label, p.tosell, p.tobuy, p.barcode, p.price, p.price_ttc' ;
244  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
245  $sql .= ', ps.reel';
246  }
247 
248  // Add fields from hooks
249  $parameters = array();
250  $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters);
251  if ($reshook >= 0) {
252  $sql .= $hookmanager->resPrint;
253  }
254 
255  $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
256  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
257  $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_stock as ps';
258  $sql .= ' ON (p.rowid = ps.fk_product';
259  $sql .= " AND ps.fk_entrepot = ".((int) getDolGlobalInt("CASHDESK_ID_WAREHOUSE".$_SESSION['takeposterminal']));
260  $sql .= ')';
261  }
262 
263  // Add tables from hooks
264  $parameters = array();
265  $reshook = $hookmanager->executeHooks('printFieldListTables', $parameters);
266  if ($reshook >= 0) {
267  $sql .= $hookmanager->resPrint;
268  }
269 
270  $sql .= ' WHERE entity IN ('.getEntity('product').')';
271  if ($filteroncategids) {
272  $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).'))';
273  }
274  $sql .= ' AND p.tosell = 1';
275  if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
276  $sql .= ' AND ps.reel > 0';
277  }
278  $sql .= natural_search(array('ref', 'label', 'barcode'), $term);
279  // Add where from hooks
280  $parameters = array();
281  $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters);
282  if ($reshook >= 0) {
283  $sql .= $hookmanager->resPrint;
284  }
285 
286  // load only one page of products
287  $sql.= $db->plimit($search_limit, $search_start);
288 
289  $resql = $db->query($sql);
290  if ($resql) {
291  $rows = array();
292 
293  while ($obj = $db->fetch_object($resql)) {
294  $objProd = new Product($db);
295  $objProd->fetch($obj->rowid);
296  $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
297 
298  $match = array();
299  preg_match('@src="([^"]+)"@', $image, $match);
300  $file = array_pop($match);
301 
302  if ($file == "") {
303  $ig = '../public/theme/common/nophoto.png';
304  } else {
305  if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
306  $ig = $file.'&cache=1';
307  } else {
308  $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
309  }
310  }
311 
312  $row = array(
313  'rowid' => $obj->rowid,
314  'ref' => $obj->ref,
315  'label' => $obj->label,
316  'tosell' => $obj->tosell,
317  'tobuy' => $obj->tobuy,
318  'barcode' => $obj->barcode,
319  'price' => $obj->price,
320  'price_ttc' => $obj->price_ttc,
321  'object' => 'product',
322  'img' => $ig,
323  'qty' => 1,
324  'price_formated' => price(price2num($obj->price, 'MT'), 1, $langs, 1, -1, -1, $conf->currency),
325  'price_ttc_formated' => price(price2num($obj->price_ttc, 'MT'), 1, $langs, 1, -1, -1, $conf->currency)
326  );
327  // Add entries to row from hooks
328  $parameters=array();
329  $parameters['row'] = $row;
330  $parameters['obj'] = $obj;
331  $reshook = $hookmanager->executeHooks('completeAjaxReturnArray', $parameters);
332  if ($reshook > 0) {
333  // replace
334  if (count($hookmanager->resArray)) {
335  $row = $hookmanager->resArray;
336  } else {
337  $row = array();
338  }
339  } else {
340  // add
341  if (count($hookmanager->resArray)) {
342  $rows[] = $hookmanager->resArray;
343  }
344  $rows[] = $row;
345  }
346  }
347 
348  echo json_encode($rows);
349  } else {
350  echo 'Failed to search product : '.$db->lasterror();
351  }
352 } elseif ($action == "opendrawer" && $term != '') {
353  require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
354  $printer = new dolReceiptPrinter($db);
355  // check printer for terminal
356  if (getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) {
357  $printer->initPrinter(getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term));
358  // open cashdrawer
359  $printer->pulse();
360  $printer->close();
361  }
362 } elseif ($action == "printinvoiceticket" && $term != '' && $id > 0 && $user->hasRight('facture', 'lire')) {
363  require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
364  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
365  $printer = new dolReceiptPrinter($db);
366  // check printer for terminal
367  if ((getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0 || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term) > 0) {
368  $object = new Facture($db);
369  $object->fetch($id);
370  $ret = $printer->sendToPrinter($object, getDolGlobalString('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalString('TAKEPOS_PRINTER_TO_USE'.$term));
371  }
372 } elseif ($action == 'getInvoice') {
373  top_httphead('application/json');
374 
375  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
376 
377  $object = new Facture($db);
378  if ($id > 0) {
379  $object->fetch($id);
380  }
381 
382  echo json_encode($object);
383 } elseif ($action == 'thecheck') {
384  $place = GETPOST('place', 'alpha');
385  require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
386  require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
387 
388  $object = new Facture($db);
389 
390  $printer = new dolReceiptPrinter($db);
391  $printer->sendToPrinter($object, getDolGlobalString('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalString('TAKEPOS_PRINTER_TO_USE'.$term));
392 }
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') && $user->hasRight('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') && $user->hasRight('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)) $sql
Social contributions to pay.
Definition: index.php:746
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.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
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(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
Definition: main.inc.php:1494
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.