dolibarr 18.0.6
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
24if (!defined('NOTOKENRENEWAL')) {
25 define('NOTOKENRENEWAL', '1');
26}
27if (!defined('NOREQUIREMENU')) {
28 define('NOREQUIREMENU', '1');
29}
30if (!defined('NOREQUIREHTML')) {
31 define('NOREQUIREHTML', '1');
32}
33if (!defined('NOREQUIREAJAX')) {
34 define('NOREQUIREAJAX', '1');
35}
36if (!defined('NOBROWSERNOTIF')) {
37 define('NOBROWSERNOTIF', '1');
38}
39
40// Load Dolibarr environment
41require '../../main.inc.php'; // Load $user and permissions
42require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
43require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php";
44require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
45
46$category = GETPOST('category', 'alphanohtml'); // Can be id of category or 'supplements'
47$action = GETPOST('action', 'aZ09');
48$term = GETPOST('term', 'alpha');
49$id = GETPOST('id', 'int');
50$search_start = GETPOST('search_start', 'int');
51$search_limit = GETPOST('search_limit', 'int');
52
53if (empty($user->rights->takepos->run)) {
55}
56
57// Initialize technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
58$hookmanager->initHooks(array('takeposproductsearch')); // new context for product search hooks
59
60$pricelevel = 1; // default price level if PRODUIT_MULTIPRICES. TODO Get price level from thirdparty.
61
62
63
64/*
65 * View
66 */
67
68$thirdparty = new Societe($db);
69
70if ($action == 'getProducts') {
71 $tosell = GETPOSTISSET('tosell') ? GETPOST('tosell', 'int') : '';
72 $limit = GETPOSTISSET('limit') ? GETPOST('limit', 'int') : 0;
73 $offset = GETPOSTISSET('offset') ? GETPOST('offset', 'int') : 0;
74
75 top_httphead('application/json');
76
77 // Search
78 if (GETPOSTINT('thirdpartyid') > 0) {
79 $result = $thirdparty->fetch(GETPOSTINT('thirdpartyid'));
80 if ($result > 0) {
81 $pricelevel = $thirdparty->price_level;
82 }
83 }
84
85 $object = new Categorie($db);
86 if ($category == "supplements") {
87 $category = getDolGlobalInt('TAKEPOS_SUPPLEMENTS_CATEGORY');
88 if (empty($category)) {
89 echo 'Error, the category to use for supplements is not defined. Go into setup of module TakePOS.';
90 exit;
91 }
92 }
93
94 $result = $object->fetch($category);
95 if ($result > 0) {
96 $filter = array();
97 if ($tosell != '') {
98 $filter = array('customsql' => 'o.tosell = '.((int) $tosell));
99 }
100 $prods = $object->getObjectsInCateg("product", 0, $limit, $offset, getDolGlobalString('TAKEPOS_SORTPRODUCTFIELD'), 'ASC', $filter);
101 // Removed properties we don't need
102 $res = array();
103 if (is_array($prods) && count($prods) > 0) {
104 foreach ($prods as $prod) {
105 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
106 // remove products without stock
107 $prod->load_stock('nobatch,novirtual');
108 if ($prod->stock_warehouse[getDolGlobalString('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])]->real <= 0) {
109 continue;
110 }
111 }
112 unset($prod->fields);
113 unset($prod->db);
114
115 $prod->price_formated = price(price2num(empty($prod->multiprices[$pricelevel]) ? $prod->price : $prod->multiprices[$pricelevel], 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
116 $prod->price_ttc_formated = price(price2num(empty($prod->multiprices_ttc[$pricelevel]) ? $prod->price_ttc : $prod->multiprices_ttc[$pricelevel], 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
117
118 $res[] = $prod;
119 }
120 }
121 echo json_encode($res);
122 } else {
123 echo 'Failed to load category with id='.dol_escape_htmltag($category);
124 }
125} elseif ($action == 'search' && $term != '') {
126 top_httphead('application/json');
127
128 // Search barcode into thirdparties. If found, it means we want to change thirdparties.
129 $result = $thirdparty->fetch('', '', '', $term);
130
131 if ($result && $thirdparty->id > 0) {
132 $rows = array();
133 $rows[] = array(
134 'rowid' => $thirdparty->id,
135 'name' => $thirdparty->name,
136 'barcode' => $thirdparty->barcode,
137 'object' => 'thirdparty'
138 );
139 echo json_encode($rows);
140 exit;
141 }
142
143 // Search
144 if (GETPOSTINT('thirdpartyid') > 0) {
145 $result = $thirdparty->fetch(GETPOSTINT('thirdpartyid'));
146 if ($result > 0) {
147 $pricelevel = $thirdparty->price_level;
148 }
149 }
150
151 // Define $filteroncategids, the filter on category ID if there is a Root category defined.
152 $filteroncategids = '';
153 if ($conf->global->TAKEPOS_ROOT_CATEGORY_ID > 0) { // A root category is defined, we must filter on products inside this category tree
154 $object = new Categorie($db);
155 //$result = $object->fetch($conf->global->TAKEPOS_ROOT_CATEGORY_ID);
156 $arrayofcateg = $object->get_full_arbo('product', $conf->global->TAKEPOS_ROOT_CATEGORY_ID, 1);
157 if (is_array($arrayofcateg) && count($arrayofcateg) > 0) {
158 foreach ($arrayofcateg as $val) {
159 $filteroncategids .= ($filteroncategids ? ', ' : '').$val['id'];
160 }
161 }
162 }
163
164 $barcode_rules = getDolGlobalString('TAKEPOS_BARCODE_RULE_TO_INSERT_PRODUCT');
165 if (isModEnabled('barcode') && !empty($barcode_rules)) {
166 $barcode_rules_list = array();
167
168 // get barcode rules
169 $barcode_char_nb = 0;
170 $barcode_rules_arr = explode('+', $barcode_rules);
171 foreach ($barcode_rules_arr as $barcode_rules_values) {
172 $barcode_rules_values_arr = explode(':', $barcode_rules_values);
173 if (count($barcode_rules_values_arr) == 2) {
174 $char_nb = intval($barcode_rules_values_arr[1]);
175 $barcode_rules_list[] = array('code' => $barcode_rules_values_arr[0], 'char_nb' => $char_nb);
176 $barcode_char_nb += $char_nb;
177 }
178 }
179
180 $barcode_value_list = array();
181 $barcode_offset = 0;
182 $barcode_length = dol_strlen($term);
183 if ($barcode_length == $barcode_char_nb) {
184 $rows = array();
185
186 // split term with barcode rules
187 foreach ($barcode_rules_list as $barcode_rule_arr) {
188 $code = $barcode_rule_arr['code'];
189 $char_nb = $barcode_rule_arr['char_nb'];
190 $barcode_value_list[$code] = substr($term, $barcode_offset, $char_nb);
191 $barcode_offset += $char_nb;
192 }
193
194 if (isset($barcode_value_list['ref'])) {
195 // search product from reference
196 $sql = "SELECT rowid, ref, label, tosell, tobuy, barcode, price, price_ttc";
197 $sql .= " FROM " . $db->prefix() . "product as p";
198 $sql .= " WHERE entity IN (" . getEntity('product') . ")";
199 $sql .= " AND ref = '" . $db->escape($barcode_value_list['ref']) . "'";
200 if ($filteroncategids) {
201 $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)."))";
202 }
203 $sql .= " AND tosell = 1";
204 $sql .= " AND (barcode IS NULL OR barcode <> '" . $db->escape($term) . "')";
205
206 $resql = $db->query($sql);
207 if ($resql && $db->num_rows($resql) == 1) {
208 if ($obj = $db->fetch_object($resql)) {
209 $qty = 1;
210 if (isset($barcode_value_list['qu'])) {
211 $qty_str = $barcode_value_list['qu'];
212 if (isset($barcode_value_list['qd'])) {
213 $qty_str .= '.' . $barcode_value_list['qd'];
214 }
215 $qty = floatval($qty_str);
216 }
217
218 $objProd = new Product($db);
219 $objProd->fetch($obj->rowid);
220
221 $ig = '../public/theme/common/nophoto.png';
222 if (empty($conf->global->TAKEPOS_HIDE_PRODUCT_IMAGES)) {
223 $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
224
225 $match = array();
226 preg_match('@src="([^"]+)"@', $image, $match);
227 $file = array_pop($match);
228
229 if ($file != '') {
230 if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
231 $ig = $file.'&cache=1';
232 } else {
233 $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
234 }
235 }
236 }
237
238 $rows[] = array(
239 'rowid' => $obj->rowid,
240 'ref' => $obj->ref,
241 'label' => $obj->label,
242 'tosell' => $obj->tosell,
243 'tobuy' => $obj->tobuy,
244 'barcode' => $obj->barcode,
245 'price' => empty($objProd->multiprices[$pricelevel]) ? $obj->price : $objProd->multiprices[$pricelevel],
246 'price_ttc' => empty($objProd->multiprices_ttc[$pricelevel]) ? $obj->price_ttc : $objProd->multiprices_ttc[$pricelevel],
247 'object' => 'product',
248 'img' => $ig,
249 'qty' => $qty,
250 );
251 }
252 $db->free($resql);
253 }
254 }
255
256 if (count($rows) == 1) {
257 echo json_encode($rows);
258 exit();
259 }
260 }
261 }
262
263 $sql = 'SELECT p.rowid, p.ref, p.label, p.tosell, p.tobuy, p.barcode, p.price, p.price_ttc' ;
264 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
265 $sql .= ', ps.reel';
266 }
267 /* this will be possible when field archive will be supported into llx_product_price
268 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
269 $sql .= ', pp.price_level, pp.price as multiprice_ht, pp.price_ttc as multiprice_ttc';
270 }*/
271 // Add fields from hooks
272 $parameters = array();
273 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters);
274 if ($reshook >= 0) {
275 $sql .= $hookmanager->resPrint;
276 }
277
278 $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
279 /* this will be possible when field archive will be supported into llx_product_price
280 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
281 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_price as pp ON pp.fk_product = p.rowid AND pp.entity = ".((int) $conf->entity)." AND pp.price_level = ".((int) $pricelevel);
282 $sql .= " AND archive = 0";
283 }*/
284 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
285 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_stock as ps';
286 $sql .= ' ON (p.rowid = ps.fk_product';
287 $sql .= " AND ps.fk_entrepot = ".((int) getDolGlobalInt("CASHDESK_ID_WAREHOUSE".$_SESSION['takeposterminal']));
288 $sql .= ')';
289 }
290
291 // Add tables from hooks
292 $parameters = array();
293 $reshook = $hookmanager->executeHooks('printFieldListTables', $parameters);
294 if ($reshook >= 0) {
295 $sql .= $hookmanager->resPrint;
296 }
297
298 $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
299 if ($filteroncategids) {
300 $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).'))';
301 }
302 $sql .= ' AND p.tosell = 1';
303 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
304 $sql .= ' AND ps.reel > 0';
305 }
306 $sql .= natural_search(array('ref', 'label', 'barcode'), $term);
307 // Add where from hooks
308 $parameters = array();
309 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters);
310 if ($reshook >= 0) {
311 $sql .= $hookmanager->resPrint;
312 }
313
314 // load only one page of products
315 $sql.= $db->plimit($search_limit, $search_start);
316
317 $resql = $db->query($sql);
318 if ($resql) {
319 $rows = array();
320
321 while ($obj = $db->fetch_object($resql)) {
322 $objProd = new Product($db);
323 $objProd->fetch($obj->rowid);
324 $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
325
326 $match = array();
327 preg_match('@src="([^"]+)"@', $image, $match);
328 $file = array_pop($match);
329
330 if ($file == "") {
331 $ig = '../public/theme/common/nophoto.png';
332 } else {
333 if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
334 $ig = $file.'&cache=1';
335 } else {
336 $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
337 }
338 }
339
340 $row = array(
341 'rowid' => $obj->rowid,
342 'ref' => $obj->ref,
343 'label' => $obj->label,
344 'tosell' => $obj->tosell,
345 'tobuy' => $obj->tobuy,
346 'barcode' => $obj->barcode,
347 'price' => empty($objProd->multiprices[$pricelevel]) ? $obj->price : $objProd->multiprices[$pricelevel],
348 'price_ttc' => empty($objProd->multiprices_ttc[$pricelevel]) ? $obj->price_ttc : $objProd->multiprices_ttc[$pricelevel],
349 'object' => 'product',
350 'img' => $ig,
351 'qty' => 1,
352 'price_formated' => price(price2num(empty($objProd->multiprices[$pricelevel]) ? $obj->price : $objProd->multiprices[$pricelevel], 'MT'), 1, $langs, 1, -1, -1, $conf->currency),
353 'price_ttc_formated' => price(price2num(empty($objProd->multiprices_ttc[$pricelevel]) ? $obj->price_ttc : $objProd->multiprices_ttc[$pricelevel], 'MT'), 1, $langs, 1, -1, -1, $conf->currency)
354 );
355 // Add entries to row from hooks
356 $parameters=array();
357 $parameters['row'] = $row;
358 $parameters['obj'] = $obj;
359 $reshook = $hookmanager->executeHooks('completeAjaxReturnArray', $parameters);
360 if ($reshook > 0) {
361 // replace
362 if (count($hookmanager->resArray)) {
363 $row = $hookmanager->resArray;
364 } else {
365 $row = array();
366 }
367 } else {
368 // add
369 if (count($hookmanager->resArray)) {
370 $rows[] = $hookmanager->resArray;
371 }
372 $rows[] = $row;
373 }
374 }
375
376 echo json_encode($rows);
377 } else {
378 echo 'Failed to search product : '.$db->lasterror();
379 }
380} elseif ($action == "opendrawer" && $term != '') {
381 require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
382 $printer = new dolReceiptPrinter($db);
383 // check printer for terminal
384 if (getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) {
385 $printer->initPrinter(getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term));
386 // open cashdrawer
387 $printer->pulse();
388 $printer->close();
389 }
390} elseif ($action == "printinvoiceticket" && $term != '' && $id > 0 && $user->hasRight('facture', 'lire')) {
391 require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
392 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
393 $printer = new dolReceiptPrinter($db);
394 // check printer for terminal
395 if ((getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0 || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term) > 0) {
396 $object = new Facture($db);
397 $object->fetch($id);
398 $ret = $printer->sendToPrinter($object, getDolGlobalString('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalString('TAKEPOS_PRINTER_TO_USE'.$term));
399 }
400} elseif ($action == 'getInvoice') {
401 top_httphead('application/json');
402
403 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
404
405 $object = new Facture($db);
406 if ($id > 0) {
407 $object->fetch($id);
408 }
409
410 echo json_encode($object);
411} elseif ($action == 'thecheck') {
412 $place = GETPOST('place', 'alpha');
413 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
414 require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
415
416 $object = new Facture($db);
417
418 $printer = new dolReceiptPrinter($db);
419 $printer->sendToPrinter($object, getDolGlobalString('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalString('TAKEPOS_PRINTER_TO_USE'.$term));
420}
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.
GETPOSTINT($paramname, $method=0)
Return value of a param into GET or POST supervariable.
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.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.