dolibarr 25.0.0-alpha
products.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2006 Andre Cianfarani <acianfa@free.fr>
3 * Copyright (C) 2005-2013 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2007-2011 Laurent Destailleur <eldy@users.sourceforge.net>
5 * Copyright (C) 2020 Josep Lluís Amador <joseplluis@lliuretic.cat>
6 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
7 * Copyright (C) 2025 MDW <mdeweerd@users.noreply.github.com>
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 3 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
28if (!defined('NOTOKENRENEWAL')) {
29 define('NOTOKENRENEWAL', 1); // Disables token renewal
30}
31if (!defined('NOREQUIREMENU')) {
32 define('NOREQUIREMENU', '1');
33}
34if (!defined('NOREQUIREHTML')) {
35 define('NOREQUIREHTML', '1');
36}
37if (!defined('NOREQUIREAJAX')) {
38 define('NOREQUIREAJAX', '1');
39}
40if (empty($_GET['keysearch']) && !defined('NOREQUIREHTML')) { // Keep $_GET here, GETPOST is not yet defined
41 define('NOREQUIREHTML', '1');
42}
43
44// Load Dolibarr environment
45require '../../main.inc.php';
55$htmlname = GETPOST('htmlname', 'aZ09');
56$socid = GETPOSTINT('socid');
57// type can be empty string or 0 or 1
58$type = GETPOST('type', 'int');
59$mode = GETPOSTINT('mode');
60$status = ((GETPOSTINT('status') >= 0) ? GETPOSTINT('status') : - 1); // status buy when mode = customer , status purchase when mode = supplier
61$status_purchase = ((GETPOSTINT('status_purchase') >= 0) ? GETPOSTINT('status_purchase') : - 1); // status purchase when mode = customer
62$outjson = (GETPOSTINT('outjson') ? GETPOSTINT('outjson') : 0);
63$price_level = GETPOSTINT('price_level');
64$action = GETPOST('action', 'aZ09');
65$id = GETPOSTINT('id');
66$price_by_qty_rowid = GETPOSTINT('pbq');
67$finished = GETPOSTINT('finished');
68$alsoproductwithnosupplierprice = GETPOSTINT('alsoproductwithnosupplierprice');
69$warehouseStatus = GETPOST('warehousestatus', 'alpha');
70$hidepriceinlabel = GETPOSTINT('hidepriceinlabel');
71$warehouseId = GETPOSTINT('warehouseid');
72
73// Security check
74restrictedArea($user, 'produit|service|commande|propal|facture', 0, 'product&product');
75
76
77/*
78 * Actions
79 */
80
81// None
82
83
84/*
85 * View
86 */
87
88// print '<!-- Ajax page called with url '.dol_escape_htmltag($_SERVER["PHP_SELF"]).'?'.dol_escape_htmltag($_SERVER["QUERY_STRING"]).' -->'."\n";
89
90if ($action == 'fetch' && !empty($id)) {
91 // action='fetch' is used to get product information on a product. So when action='fetch', id must be the product id.
92 require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
93 require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
94 if (isModEnabled('variants')) {
95 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
96 }
97
98 top_httphead('application/json');
99
100 $outjson = array();
101
102 $object = new Product($db);
103 if (isModEnabled('variants')) {
104 $combinations = GETPOST('combinations', 'array:alphanohtml');
105 if (!empty($combinations)) {
106 $prodcomb = new ProductCombination($db);
107 $combination = $prodcomb->fetchByProductCombination2ValuePairs($id, $combinations);
108 if ($combination) {
109 // Fetch the concrete variant product so returned prices include the configured price impact.
110 $id = (int) $combination->fk_product_child;
111 }
112 }
113 }
114
115 $ret = $object->fetch($id);
116 if ($ret > 0) {
117 $outref = $object->ref;
118 $outlabel = $object->label;
119 $outlabel_trans = '';
120 $default_unit = $object->fk_unit;
121 $outdesc = $object->description;
122 $outdesc_trans = '';
123 $outtype = $object->type;
124 $outprice_ht = null;
125 $outprice_ttc = null;
126 $outpricebasetype = null;
127 $outtva_tx_formated = 0;
128 $outtva_tx = 0;
129 $outdefault_vat_code = '';
130 $outqty = 1;
131 $outdiscount = null; // A discount on product price level is defined only for some price mode (like a price per customer 'PRODUIT_CUSTOMER_PRICES' or a price percustomer and quantity 'PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')
132 $mandatory_period = $object->mandatory_period;
133 $found = false;
134
135 $price_level = 1;
136 if ($socid > 0) {
137 $needchangeaccordingtothirdparty = 0;
138 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
139 $needchangeaccordingtothirdparty = 1;
140 }
141 if (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
142 $needchangeaccordingtothirdparty = 1;
143 }
144 if ($needchangeaccordingtothirdparty) {
145 $thirdpartytemp = new Societe($db);
146 $thirdpartytemp->fetch($socid);
147
148 //Load translation description and label according to thirdparty language
149 if (getDolGlobalInt('MAIN_MULTILANGS') && getDolGlobalString('PRODUIT_TEXTS_IN_THIRDPARTY_LANGUAGE')) {
150 $newlang = $thirdpartytemp->default_lang;
151
152 if (!empty($newlang)) {
153 $outputlangs = new Translate("", $conf);
154 $outputlangs->setDefaultLang($newlang);
155 $outdesc_trans = (!empty($object->multilangs[$outputlangs->defaultlang]["description"])) ? $object->multilangs[$outputlangs->defaultlang]["description"] : $object->description;
156 $outlabel_trans = (!empty($object->multilangs[$outputlangs->defaultlang]["label"])) ? $object->multilangs[$outputlangs->defaultlang]["label"] : $object->label;
157 } else {
158 $outdesc_trans = $object->description;
159 $outlabel_trans = $object->label;
160 }
161 }
162
163 //Set price level according to thirdparty
164 if (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) {
165 $price_level = $thirdpartytemp->price_level;
166 }
167 }
168 }
169
170 // Price by qty
171 if (!empty($price_by_qty_rowid) && $price_by_qty_rowid >= 1 && (getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES'))) { // If we need a particular price related to qty
172 $sql = "SELECT price, unitprice, quantity, remise_percent";
173 $sql .= " FROM ".MAIN_DB_PREFIX."product_price_by_qty";
174 $sql .= " WHERE rowid = ".((int) $price_by_qty_rowid);
175 // The price by quantity must be a price of the product asked, not the one of another product
176 $sql .= " AND fk_product_price IN (SELECT pp.rowid FROM ".MAIN_DB_PREFIX."product_price as pp WHERE pp.fk_product = ".((int) $id).")";
177
178 $result = $db->query($sql);
179 if ($result) {
180 $objp = $db->fetch_object($result);
181 if ($objp) {
182 $found = true;
183 $outprice_ht = price($objp->unitprice);
184 $outprice_ttc = price($objp->unitprice * (1 + ($object->tva_tx / 100)));
185
186 $outpricebasetype = $object->price_base_type;
187 $outtva_tx_formated = price($object->tva_tx);
188 $outtva_tx = price2num($object->tva_tx);
189 $outdefault_vat_code = $object->default_vat_code;
190
191 $outqty = $objp->quantity;
192 $outdiscount = $objp->remise_percent;
193 }
194 }
195 }
196
197 // Multiprice (1 price per level)
198 if (!$found && isset($price_level) && $price_level >= 1 && (getDolGlobalString('PRODUIT_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_BY_QTY_MULTIPRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES'))) { // If we need a particular price level (from 1 to 6)
199 $sql = "SELECT price, price_ttc, price_base_type,";
200 $sql .= " tva_tx, default_vat_code"; // Vat rate and code will be used if PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL is on.
201 $sql .= " FROM ".MAIN_DB_PREFIX."product_price ";
202 $sql .= " WHERE fk_product = ".((int) $id);
203 $sql .= " AND entity IN (".getEntity('productprice').")";
204 $sql .= " AND price_level = ".((int) $price_level);
205 $sql .= " ORDER BY date_price DESC, rowid";
206 $sql .= " DESC LIMIT 1";
207
208 $result = $db->query($sql);
209 if ($result) {
210 $objp = $db->fetch_object($result);
211 if ($objp) {
212 $found = true;
213 $outprice_ht = price($objp->price); // formatted for language user because is inserted into input field
214 $outprice_ttc = price($objp->price_ttc); // formatted for language user because is inserted into input field
215 $outpricebasetype = $objp->price_base_type;
216 if (getDolGlobalString('PRODUIT_MULTIPRICES_USE_VAT_PER_LEVEL')) {
217 $outtva_tx_formated = price($objp->tva_tx); // formatted for language user because is inserted into input field
218 $outtva_tx = price2num($objp->tva_tx); // international numeric
219 $outdefault_vat_code = $objp->default_vat_code;
220 } else {
221 // The common and default behaviour.
222 $outtva_tx_formated = price($object->tva_tx);
223 $outtva_tx = price2num($object->tva_tx);
224 $outdefault_vat_code = $object->default_vat_code;
225 }
226 }
227 }
228 }
229
230 // Price by customer
231 if ((getDolGlobalString('PRODUIT_CUSTOMER_PRICES') || getDolGlobalString('PRODUIT_CUSTOMER_PRICES_AND_MULTIPRICES')) && !empty($socid)) {
232 require_once DOL_DOCUMENT_ROOT.'/product/class/productcustomerprice.class.php';
233
234 $prodcustprice = new ProductCustomerPrice($db);
235
236 $filter = array('t.fk_product' => (string) $object->id, 't.fk_soc' => (string) $socid);
237
238 $result = $prodcustprice->fetchAll('', '', 0, 0, $filter);
239 if ($result) {
240 if (count($prodcustprice->lines) > 0) {
241 $date_now = (int) floor(dol_now() / 86400) * 86400; // date without hours
242 foreach ($prodcustprice->lines as $k => $custprice_line) {
243 if ($custprice_line->date_begin <= $date_now && (empty($custprice_line->date_end) || $date_now <= $custprice_line->date_end)) {
244 $found = true;
245 $outprice_ht = price($custprice_line->price);
246 $outprice_ttc = price($custprice_line->price_ttc);
247 $outpricebasetype = $custprice_line->price_base_type;
248 $outtva_tx_formated = price($custprice_line->tva_tx);
249 $outtva_tx = price2num($custprice_line->tva_tx);
250 $outdefault_vat_code = $custprice_line->default_vat_code;
251 $outdiscount = $custprice_line->discount_percent;
252 break;
253 }
254 }
255 }
256 }
257 }
258
259 if (!$found) {
260 $outprice_ht = price($object->price);
261 $outprice_ttc = price($object->price_ttc);
262 $outpricebasetype = $object->price_base_type;
263 $outtva_tx_formated = price($object->tva_tx);
264 $outtva_tx = price2num($object->tva_tx);
265 $outdefault_vat_code = $object->default_vat_code;
266
267 // Variant rows are kept in llx_product without their own price/vat
268 // information - the parent product holds them. If this product is a
269 // variant child and its vat fields are empty, inherit them from the
270 // parent so the sales/order line gets the default tax preselected
271 // like the non-variant flow does (#30400).
272 if (empty($outtva_tx) && empty($outdefault_vat_code)) {
273 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
274 $combination = new ProductCombination($db);
275 if ($combination->fetchByFkProductChild($object->id, 1) > 0) {
276 $parent = new Product($db);
277 if ($parent->fetch($combination->fk_product_parent) > 0) {
278 $outtva_tx_formated = price($parent->tva_tx);
279 $outtva_tx = price2num($parent->tva_tx);
280 $outdefault_vat_code = $parent->default_vat_code;
281 $product_outtva_tx_formated = $outtva_tx_formated;
282 $product_outtva_tx = $outtva_tx;
283 $product_outdefault_vat_code = $outdefault_vat_code;
284 }
285 }
286 }
287 }
288
289 // VAT to use and default VAT for product are set to same value by default
290 $product_outtva_tx_formated = $outtva_tx_formated;
291 $product_outtva_tx = $outtva_tx;
292 $product_outdefault_vat_code = $outdefault_vat_code;
293
294 // If we ask the price according to buyer, we change it.
295 if (GETPOSTINT('addalsovatforthirdpartyid')) {
296 $thirdparty_buyer = new Societe($db);
297 $thirdparty_buyer->fetch($socid);
298
299 $tmpvatwithcode = get_default_tva($mysoc, $thirdparty_buyer, $id, 0);
300
301 if (!is_numeric($tmpvatwithcode) || $tmpvatwithcode != -1) {
302 $reg = array();
303 if (preg_match('/(.+)\s\‍((.+)\‍)/', $tmpvatwithcode, $reg)) {
304 $outtva_tx = price2num($reg[1]);
305 $outtva_tx_formated = price($outtva_tx);
306 $outdefault_vat_code = $reg[2];
307 } else {
308 $outtva_tx = price2num($tmpvatwithcode);
309 $outtva_tx_formated = price($outtva_tx);
310 $outdefault_vat_code = '';
311 }
312 }
313
314 // The VAT rate above was just changed to the one applicable to this buyer, but price_ht/
315 // price_ttc are still whatever was set for the product/price line, so they can now be an
316 // inconsistent triple (e.g. a price defined as tax included, VAT rate now 0 for an EU
317 // reverse-charge buyer, but price_ttc is still the original tax-included amount). Off by
318 // default to keep historical behavior (price_ttc unchanged, whatever VAT rate applies);
319 // when enabled, price_ht is kept as the fixed reference and price_ttc is recomputed from
320 // it and the buyer's actual VAT rate instead.
321 if (getDolGlobalString('PRODUIT_RECALCULATE_TTC_ACCORDING_TO_BUYER_VAT') && isset($outprice_ht)) {
322 $outprice_ttc = price((float) price2num($outprice_ht) * (1 + ($outtva_tx / 100)));
323 }
324 }
325
326 $outjson = array(
327 'ref' => $outref,
328 'label' => $outlabel,
329 'label_trans' => $outlabel_trans,
330 'desc' => $outdesc,
331 'desc_trans' => $outdesc_trans,
332 'type' => $outtype,
333 'price_ht' => $outprice_ht,
334 'price_ttc' => $outprice_ttc,
335 'pricebasetype' => $outpricebasetype,
336 'product_tva_tx_formated' => $product_outtva_tx_formated,
337 'product_tva_tx' => $product_outtva_tx,
338 'product_default_vat_code' => $product_outdefault_vat_code,
339
340 'tva_tx_formated' => $outtva_tx_formated,
341 'tva_tx' => $outtva_tx,
342 'default_vat_code' => $outdefault_vat_code,
343
344 'qty' => $outqty,
345 'discount' => $outdiscount,
346 'mandatory_period' => $mandatory_period,
347
348 'array_options' => $object->array_options,
349
350 'default_unit' => $default_unit
351 );
352 }
353
354 echo json_encode($outjson);
355} else {
356 require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
357 if (!isset($form) || !is_object($form)) {
358 $form = new Form($db);
359 }
360
361 $langs->loadLangs(array("main", "products"));
362
363 top_httphead();
364
365 if (empty($htmlname)) {
366 print json_encode(array());
367 return;
368 }
369
370 // Filter on the product to search can be:
371 // Into an array with key $htmlname123 (we take first one found). Which page use this ?
372 // Into a var with name $htmlname can be 'prodid', 'productid', ...
373 $match = preg_grep('/('.preg_quote($htmlname, '/').'[0-9]+)/', array_keys($_GET));
374 sort($match);
375
376 $idprod = (empty($match[0]) ? '' : $match[0]); // Take first key found into GET array with matching $htmlname123
377
378 if (GETPOST($htmlname, 'alpha') == '' && (!$idprod || !GETPOST($idprod, 'alpha'))) {
379 print json_encode(array());
380 return;
381 }
382
383 // When used from jQuery, the search term is added as GET param "term".
384 $searchkey = (($idprod && GETPOST($idprod, 'alpha')) ? GETPOST($idprod, 'alpha') : (GETPOST($htmlname, 'alpha') ? GETPOST($htmlname, 'alpha') : ''));
385
386 $arrayresult = [];
387 if (empty($mode) || $mode == 1) { // mode=1: customer
388 $arrayresult = $form->select_produits_list(0, $htmlname, $type, getDolGlobalInt('PRODUIT_LIMIT_SIZE', 1000), $price_level, $searchkey, $status, $finished, $outjson, $socid, '1', 0, '', $hidepriceinlabel, $warehouseStatus, $status_purchase, $warehouseId);
389 } elseif ($mode == 2) { // mode=2: supplier
390 $arrayresult = $form->select_produits_fournisseurs_list($socid, "", $htmlname, $type, "", $searchkey, $status, $outjson, getDolGlobalInt('PRODUIT_LIMIT_SIZE', 1000), $alsoproductwithnosupplierprice, '', getDolGlobalInt('SUPPLIER_SHOW_STOCK_IN_PRODUCTS_COMBO'));
391 }
392
393 $db->close();
394
395 if ($outjson) {
396 print json_encode($arrayresult);
397 }
398}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to manage generation of HTML components Only common components must be here.
Class ProductCombination Used to represent the relation between a product and one of its variants.
File of class to manage predefined price products or services by customer.
Class to manage products or services.
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage translations.
global $mysoc
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as description
Only used if Module[ID]Desc translation string is not found.
dol_now($mode='gmt')
Return date for now.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
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 a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
get_default_tva(Societe $thirdparty_seller, Societe $thirdparty_buyer, $idprod=0, $idprodfournprice=0)
Function that return vat rate of a product line (according to seller, buyer and product vat rate) VAT...
if(!defined( 'NOREQUIREMENU')) if(!empty(GETPOST('seteventmessages', 'alpha'))) if(!function_exists("llxHeader")) top_httphead($contenttype='text/html', $forcenocache=0)
Show HTTP header.
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $nodie=0, $mode='')
Check permissions of a user to show a page and an object.