dolibarr 23.0.3
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 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
6 *
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
26if (!defined('NOTOKENRENEWAL')) {
27 define('NOTOKENRENEWAL', '1');
28}
29if (!defined('NOREQUIREMENU')) {
30 define('NOREQUIREMENU', '1');
31}
32if (!defined('NOREQUIREHTML')) {
33 define('NOREQUIREHTML', '1');
34}
35if (!defined('NOREQUIREAJAX')) {
36 define('NOREQUIREAJAX', '1');
37}
38if (!defined('NOBROWSERNOTIF')) {
39 define('NOBROWSERNOTIF', '1');
40}
41
42// Load Dolibarr environment
43require '../../main.inc.php'; // Load $user and permissions
51require_once DOL_DOCUMENT_ROOT.'/categories/class/categorie.class.php';
52require_once DOL_DOCUMENT_ROOT."/product/class/product.class.php";
53require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
54
55$category = GETPOST('category', 'alphanohtml'); // Can be id of category or 'supplements'
56$action = GETPOST('action', 'aZ09');
57$term = GETPOST('term', 'alpha');
58$search_term = GETPOST('search_term', 'alpha');
59$id = GETPOSTINT('id');
60$search_start = GETPOSTINT('search_start');
61$search_limit = GETPOSTINT('search_limit');
62
63if (!$user->hasRight('takepos', 'run')) {
65}
66
67// Initialize a technical object to manage hooks. Note that conf->hooks_modules contains array of hooks
68$hookmanager->initHooks(array('takeposproductsearch')); // new context for product search hooks
69
70$pricelevel = 1; // default price level if PRODUIT_MULTIPRICES. TODO Get price level from thirdparty.
71
72
73
74/*
75 * View
76 */
77
78$thirdparty = new Societe($db);
79
80if ($action == 'getProducts' && $user->hasRight('takepos', 'run')) {
81 $tosell = GETPOSTISSET('tosell') ? GETPOSTINT('tosell') : '';
82 $limit = GETPOSTISSET('limit') ? GETPOSTINT('limit') : 0;
83 $offset = GETPOSTISSET('offset') ? GETPOSTINT('offset') : 0;
84
85 top_httphead('application/json');
86
87 // Search
88 if (GETPOSTINT('thirdpartyid') > 0) {
89 $result = $thirdparty->fetch(GETPOSTINT('thirdpartyid'));
90 if ($result > 0) {
91 $pricelevel = $thirdparty->price_level;
92 }
93 }
94
95 $object = new Categorie($db);
96 if ($category == "supplements") {
97 $category = getDolGlobalInt('TAKEPOS_SUPPLEMENTS_CATEGORY');
98 if (empty($category)) {
99 echo 'Error, the category to use for supplements is not defined. Go into setup of module TakePOS.';
100 exit;
101 }
102 }
103
104 $result = $object->fetch($category);
105 if ($result > 0) {
106 $filter = '';
107 if ($tosell != '') {
108 $filter = '(o.tosell:=:'.((int) $tosell).')';
109 }
110 $prods = $object->getObjectsInCateg("product", 0, $limit, $offset, getDolGlobalString('TAKEPOS_SORTPRODUCTFIELD'), 'ASC', $filter);
111 // Removed properties we don't need
112 $res = array();
113 if (is_array($prods) && count($prods) > 0) {
114 $productChildrenNb = 0;
115 foreach ($prods as $prod) {
116 '@phan-var-force Product $prod';
117 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
118 if (getDolGlobalInt('PRODUIT_SOUSPRODUITS')) {
119 $productChildrenNb = $prod->hasFatherOrChild(1);
120 }
121 // always show virtual products (don't manage stock)
122 if ($productChildrenNb == 0) {
123 // remove products without stock
124 $prod->load_stock('nobatch,novirtual');
125 if ($prod->stock_warehouse[getDolGlobalString('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])]->real <= 0) {
126 continue;
127 }
128 }
129 }
130 unset($prod->fields);
131 unset($prod->db);
132
133 $prod->price_formated = price(price2num(empty($prod->multiprices[$pricelevel]) ? $prod->price : $prod->multiprices[$pricelevel], 'MT'), 1, $langs, 1, -1, -1, $conf->currency);
134 $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);
135
136 $res[] = $prod;
137 }
138 }
139 echo json_encode($res);
140 } else {
141 echo 'Failed to load category with id='.dol_escape_htmltag($category);
142 }
143} elseif ($action == 'search' && $search_term != '' && $user->hasRight('takepos', 'run')) {
144 top_httphead('application/json');
145
146 // Search barcode into third parties. If found, it means we want to change third parties.
147 $result = $thirdparty->fetch(0, '', '', $search_term);
148
149 if ($result && $thirdparty->id > 0) {
150 $rows = array();
151 $rows[] = array(
152 'rowid' => $thirdparty->id,
153 'name' => $thirdparty->name,
154 'barcode' => $thirdparty->barcode,
155 'object' => 'thirdparty'
156 );
157 echo json_encode($rows);
158 exit;
159 }
160
161 // Search
162 if (GETPOSTINT('thirdpartyid') > 0) {
163 $result = $thirdparty->fetch(GETPOSTINT('thirdpartyid'));
164 if ($result > 0) {
165 $pricelevel = $thirdparty->price_level;
166 }
167 }
168
169 // Define $filteroncategids, the filter on category ID if there is a Root category defined.
170 $filteroncategids = '';
171 if (getDolGlobalInt('TAKEPOS_ROOT_CATEGORY_ID') > 0) { // A root category is defined, we must filter on products inside this category tree
172 $object = new Categorie($db);
173 //$result = $object->fetch($conf->global->TAKEPOS_ROOT_CATEGORY_ID);
174 $arrayofcateg = $object->get_full_arbo('product', getDolGlobalInt('TAKEPOS_ROOT_CATEGORY_ID'), 1);
175 if (is_array($arrayofcateg) && count($arrayofcateg) > 0) {
176 foreach ($arrayofcateg as $val) {
177 $filteroncategids .= ($filteroncategids ? ', ' : '').$val['id'];
178 }
179 }
180 }
181
182 $barcode_rules = getDolGlobalString('TAKEPOS_BARCODE_RULE_TO_INSERT_PRODUCT');
183 if (isModEnabled('barcode') && !empty($barcode_rules)) {
184 $barcode_rules_list = array();
185
186 // get barcode rules
187 $barcode_char_nb = 0;
188 $barcode_rules_arr = explode('+', $barcode_rules);
189 foreach ($barcode_rules_arr as $barcode_rules_values) {
190 $barcode_rules_values_arr = explode(':', $barcode_rules_values);
191 if (count($barcode_rules_values_arr) == 2) {
192 $char_nb = intval($barcode_rules_values_arr[1]);
193 $barcode_rules_list[] = array('code' => $barcode_rules_values_arr[0], 'char_nb' => $char_nb);
194 $barcode_char_nb += $char_nb;
195 }
196 }
197
198 $barcode_value_list = array();
199 $barcode_offset = 0;
200 $barcode_length = dol_strlen($search_term);
201 if ($barcode_length == $barcode_char_nb) {
202 $rows = array();
203
204 // split term with barcode rules
205 foreach ($barcode_rules_list as $barcode_rule_arr) {
206 $code = $barcode_rule_arr['code'];
207 $char_nb = $barcode_rule_arr['char_nb'];
208 $barcode_value_list[$code] = substr($search_term, $barcode_offset, $char_nb);
209 $barcode_offset += $char_nb;
210 }
211
212 if (isset($barcode_value_list['ref'])) {
213 // search product from reference
214 $sql = "SELECT rowid, ref, label, tosell, tobuy, barcode, price, price_ttc";
215 $sql .= " FROM " . $db->prefix() . "product as p";
216 $sql .= " WHERE entity IN (" . getEntity('product') . ")";
217 $sql .= " AND ref = '" . $db->escape($barcode_value_list['ref']) . "'";
218 if ($filteroncategids) {
219 $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)."))";
220 }
221 $sql .= " AND tosell = 1";
222 $sql .= " AND (barcode IS NULL OR barcode <> '" . $db->escape($search_term) . "')";
223
224 $resql = $db->query($sql);
225 if ($resql && $db->num_rows($resql) == 1) {
226 if ($obj = $db->fetch_object($resql)) {
227 $qty = 1;
228 if (isset($barcode_value_list['qu'])) {
229 $qty_str = $barcode_value_list['qu'];
230 if (isset($barcode_value_list['qd'])) {
231 $qty_str .= '.' . $barcode_value_list['qd'];
232 }
233 $qty = (float) $qty_str;
234 }
235
236 $objProd = new Product($db);
237 $objProd->fetch($obj->rowid);
238
239 $ig = '../public/theme/common/nophoto.png';
240 if (!getDolGlobalString('TAKEPOS_HIDE_PRODUCT_IMAGES')) {
241 $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
242
243 $match = array();
244 preg_match('@src="([^"]+)"@', $image, $match);
245 $file = array_pop($match);
246
247 if ($file != '') {
248 if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
249 $ig = $file.'&cache=1';
250 } else {
251 $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
252 }
253 }
254 }
255
256 $rows[] = array(
257 'rowid' => $obj->rowid,
258 'ref' => $obj->ref,
259 'label' => $obj->label,
260 'tosell' => $obj->tosell,
261 'tobuy' => $obj->tobuy,
262 'barcode' => $search_term, // there is only one product matches the barcode rule and so the term is considered as the barcode of this product
263 'price' => empty($objProd->multiprices[$pricelevel]) ? $obj->price : $objProd->multiprices[$pricelevel],
264 'price_ttc' => empty($objProd->multiprices_ttc[$pricelevel]) ? $obj->price_ttc : $objProd->multiprices_ttc[$pricelevel],
265 'object' => 'product',
266 'img' => $ig,
267 'qty' => $qty,
268 );
269 }
270 $db->free($resql);
271 }
272 }
273
274 if (count($rows) == 1) {
275 echo json_encode($rows);
276 exit();
277 }
278 }
279 }
280
281 $sql = 'SELECT p.rowid, p.ref, p.label, p.tosell, p.tobuy, p.barcode, p.price, p.price_ttc' ;
282 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
283 if (getDolGlobalInt('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])) {
284 $sql .= ', ps.reel';
285 } else {
286 $sql .= ', SUM(ps.reel) as reel';
287 }
288 }
289 /* this will be possible when field archive will be supported into llx_product_price
290 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
291 $sql .= ', pp.price_level, pp.price as multiprice_ht, pp.price_ttc as multiprice_ttc';
292 }*/
293 // Add fields from hooks
294 $parameters = array();
295 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters);
296 if ($reshook >= 0) {
297 $sql .= $hookmanager->resPrint;
298 }
299
300 $sql .= ' FROM '.MAIN_DB_PREFIX.'product as p';
301 /* this will be possible when field archive will be supported into llx_product_price
302 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
303 $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);
304 $sql .= " AND archive = 0";
305 }*/
306 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1) {
307 $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'product_stock as ps';
308 $sql .= ' ON (p.rowid = ps.fk_product';
309 if (getDolGlobalString('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])) {
310 $sql .= " AND ps.fk_entrepot = ".((int) getDolGlobalInt("CASHDESK_ID_WAREHOUSE".$_SESSION['takeposterminal']));
311 }
312 $sql .= ')';
313 }
314
315 // Add tables from hooks
316 $parameters = array();
317 $reshook = $hookmanager->executeHooks('printFieldListTables', $parameters);
318 if ($reshook >= 0) {
319 $sql .= $hookmanager->resPrint;
320 }
321
322 $sql .= ' WHERE p.entity IN ('.getEntity('product').')';
323 if ($filteroncategids) {
324 $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).'))';
325 }
326 $sql .= ' AND p.tosell = 1';
327 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1 && getDolGlobalInt('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])) {
328 $sql .= ' AND ps.reel > 0';
329 }
330 $sql .= natural_search(array('ref', 'label', 'barcode'), $search_term);
331 // Add where from hooks
332 $parameters = array();
333 $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters);
334 if ($reshook >= 0) {
335 $sql .= $hookmanager->resPrint;
336 }
337
338 if (getDolGlobalInt('TAKEPOS_PRODUCT_IN_STOCK') == 1 && !getDolGlobalInt('CASHDESK_ID_WAREHOUSE'.$_SESSION['takeposterminal'])) {
339 $sql .= ' GROUP BY p.rowid, p.ref, p.label, p.tosell, p.tobuy, p.barcode, p.price, p.price_ttc';
340 // Add fields from hooks
341 $parameters = array();
342 $reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters);
343 if ($reshook >= 0) {
344 $sql .= $hookmanager->resPrint;
345 }
346 $sql .= ' HAVING SUM(ps.reel) > 0';
347 }
348
349 // load only one page of products
350 $sql .= $db->plimit($search_limit, $search_start);
351
352 $resql = $db->query($sql);
353 if ($resql) {
354 $rows = array();
355
356 while ($obj = $db->fetch_object($resql)) {
357 $objProd = new Product($db);
358 $objProd->fetch($obj->rowid);
359 $image = $objProd->show_photos('product', $conf->product->multidir_output[$objProd->entity], 'small', 1);
360
361 $match = array();
362 preg_match('@src="([^"]+)"@', $image, $match);
363 $file = array_pop($match);
364
365 if ($file == "") {
366 $ig = '../public/theme/common/nophoto.png';
367 } else {
368 if (!defined('INCLUDE_PHONEPAGE_FROM_PUBLIC_PAGE')) {
369 $ig = $file.'&cache=1';
370 } else {
371 $ig = $file.'&cache=1&publictakepos=1&modulepart=product';
372 }
373 }
374
375 $row = array(
376 'rowid' => $obj->rowid,
377 'ref' => $obj->ref,
378 'label' => $obj->label,
379 'tosell' => $obj->tosell,
380 'tobuy' => $obj->tobuy,
381 'barcode' => $obj->barcode,
382 'price' => empty($objProd->multiprices[$pricelevel]) ? $obj->price : $objProd->multiprices[$pricelevel],
383 'price_ttc' => empty($objProd->multiprices_ttc[$pricelevel]) ? $obj->price_ttc : $objProd->multiprices_ttc[$pricelevel],
384 'object' => 'product',
385 'img' => $ig,
386 'qty' => 1,
387 'price_formated' => price(price2num(empty($objProd->multiprices[$pricelevel]) ? $obj->price : $objProd->multiprices[$pricelevel], 'MT'), 1, $langs, 1, -1, -1, $conf->currency),
388 '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)
389 );
390 // Add entries to row from hooks
391 $parameters = array();
392 $parameters['row'] = $row;
393 $parameters['obj'] = $obj;
394 $reshook = $hookmanager->executeHooks('completeAjaxReturnArray', $parameters);
395 if ($reshook > 0) {
396 // replace
397 if (count($hookmanager->resArray)) {
398 $row = $hookmanager->resArray;
399 } else {
400 $row = array();
401 }
402 $rows[] = $row;
403 } else {
404 // add
405 if (count($hookmanager->resArray)) {
406 $rows[] = $hookmanager->resArray;
407 }
408 $rows[] = $row;
409 }
410 }
411
412 echo json_encode($rows);
413 } else {
414 echo 'Failed to search product : '.$db->lasterror();
415 }
416} elseif ($action == "opendrawer" && $term != '' && $user->hasRight('takepos', 'run')) {
417 top_httphead('application/html');
418
419 require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
420 $printer = new dolReceiptPrinter($db);
421
422 // check printer for terminal
423 if (getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0) {
424 // TODO Set the profile into $this->profile (used by initPrinter). Profile not used yet.
425
426 // Init printer
427 $printer->initPrinter(getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term));
428 // open cashdrawer
429 if ($printer->getPrintConnector()) {
430 $printer->pulse();
431 $printer->close();
432 } else {
433 print 'Failed to init printer with ID='.getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term);
434 }
435 }
436} elseif ($action == "printinvoiceticket" && $term != '' && $id > 0 && $user->hasRight('takepos', 'run') && $user->hasRight('facture', 'lire')) {
437 top_httphead('application/html');
438
439 require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
440 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
441 $printer = new dolReceiptPrinter($db);
442 // check printer for terminal
443 if ((getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term) > 0 || getDolGlobalString('TAKEPOS_PRINT_METHOD') == "takeposconnector") && getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term) > 0) {
444 $object = new Facture($db);
445 $object->fetch($id);
446
447 $printer->sendToPrinter($object, getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term));
448 }
449} elseif ($action == 'getInvoice' && $user->hasRight('takepos', 'run')) {
450 top_httphead('application/json');
451
452 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
453
454 $object = new Facture($db);
455 if ($id > 0) {
456 $object->fetch($id);
457 }
458
459 echo json_encode($object);
460} elseif ($action == 'thecheck' && $user->hasRight('takepos', 'run')) {
461 top_httphead('application/html');
462
463 require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php';
464 require_once DOL_DOCUMENT_ROOT.'/core/class/dolreceiptprinter.class.php';
465
466 $object = new Facture($db);
467 $printer = new dolReceiptPrinter($db);
468
469 $printer->sendToPrinter($object, getDolGlobalInt('TAKEPOS_TEMPLATE_TO_USE_FOR_INVOICES'.$term), getDolGlobalInt('TAKEPOS_PRINTER_TO_USE'.$term));
470}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
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 the value of a $_GET or $_POST supervariable, converted into integer.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
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.
natural_search($fields, $value, $mode=0, $nofirstand=0, $sqltoadd='')
Generate natural SQL search string for a criteria (this criteria can be tested on one or several fiel...
getDolGlobalInt($key, $default=0)
Return a 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 a 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.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.