dolibarr 25.0.0-alpha
product_tools.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2012 Regis Houssin <regis.houssin@inodbox.com>
3 * Copyright (C) 2013-2015 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2025-2026 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2026 Jose Martinez <jose.martinez@pichinov.com>
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 3 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
28// TODO We must add a confirmation on button because this will make a mass change
29// FIXME Should also change table product_price for price levels
30
31// Load Dolibarr environment
32require '../../main.inc.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/core/lib/ajax.lib.php';
35require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
36require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
37require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
38
48// Load translation files required by the page
49$langs->loadLangs(array('admin', 'products', 'stocks'));
50
51// Security check
52if (!$user->admin) {
54}
55
56$action = GETPOST('action', 'aZ09');
57$oldvatrate = GETPOST('oldvatrate', 'alpha');
58$newvatrate = GETPOST('newvatrate', 'alpha');
59//$price_base_type=GETPOST('price_base_type');
60
61$hookmanager->initHooks(array('productvatadmin'));
62
63/*
64 * Actions
65 */
66
67if ($action == 'convert') {
68 $error = 0;
69
70 if ($oldvatrate == $newvatrate) {
71 $langs->load("errors");
72 setEventMessages($langs->trans("ErrorNewValueCantMatchOldValue"), null, 'errors');
73 $error++;
74 }
75
76 if (!$error) {
77 $country_id = $mysoc->country_id; // TODO Allow to choose country into form
78
79 $nbrecordsmodified = 0;
80
81 if (!getDolGlobalInt('VATUPDATE_NO_TRANSACTION')) {
82 $db->begin();
83 }
84
85 // Clean vat code old
86 $vat_src_code_old = '';
87 if (preg_match('/\‍((.*)\‍)/', $oldvatrate, $reg)) {
88 $vat_src_code_old = $reg[1];
89 $oldvatrateclean = preg_replace('/\s*\‍(.*\‍)/', '', $oldvatrate); // Remove code into vatrate.
90 } else {
91 $oldvatrateclean = $oldvatrate;
92 }
93
94 // Clean vat code new
95 $vat_src_code_new = '';
96 if (preg_match('/\‍((.*)\‍)/', $newvatrate, $reg)) {
97 $vat_src_code_new = $reg[1];
98 $newvatrateclean = preg_replace('/\s*\‍(.*\‍)/', '', $newvatrate); // Remove code into vatrate.
99 } else {
100 $newvatrateclean = $newvatrate;
101 }
102
103 // If country to edit is my country, so we change customer prices
104 if ($country_id == $mysoc->country_id) {
105 $sql = 'SELECT rowid';
106 $sql .= ' FROM '.MAIN_DB_PREFIX.'product';
107 $sql .= ' WHERE entity IN ('.getEntity('product').')';
108 $sql .= " AND tva_tx = '".$db->escape($oldvatrateclean)."'";
109 if ($vat_src_code_old) {
110 $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
111 } else {
112 $sql .= " AND (default_vat_code IS NULL OR default_vat_code = '')";
113 }
114
115 $resql = $db->query($sql);
116 if ($resql) {
117 $num = $db->num_rows($resql);
118
119 $i = 0;
120 while ($i < $num) {
121 $obj = $db->fetch_object($resql);
122
123 $objectstatic = new Product($db); // Object init must be into loop to avoid to get value of previous step
124 $ret = $objectstatic->fetch($obj->rowid);
125 if ($ret > 0) {
126 $ret = 0;
127 $retm = 0;
128 $updatelevel1 = false;
129
130 // Update multiprice
131 $listofmulti = array_reverse($objectstatic->multiprices, true); // To finish with level 1
132 foreach ($listofmulti as $level => $multiprices) {
133 $price_base_type = $objectstatic->multiprices_base_type[$level]; // Get price_base_type of product/service to keep the same for update
134 if (empty($price_base_type)) {
135 continue; // Discard not defined price levels
136 }
137
138 if ($price_base_type == 'TTC') {
139 $newprice = price2num($objectstatic->multiprices_ttc[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
140 $newminprice = $objectstatic->multiprices_min_ttc[$level];
141 } else {
142 $newprice = price2num($objectstatic->multiprices[$level], 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
143 $newminprice = $objectstatic->multiprices_min[$level];
144 }
145 if ($newminprice > $newprice) {
146 $newminprice = $newprice;
147 }
148
149 $newvat = str_replace('*', '', $newvatrate);
150 $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
151 $newnpr = $objectstatic->multiprices_recuperableonly[$level];
152 $newdefaultvatcode = $vat_src_code_new;
153 $newlevel = $level;
154
155 //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
156 $retm = $objectstatic->updatePrice((float) $newprice, $price_base_type, $user, (float) $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode);
157 if ($retm < 0) {
158 $error++;
159 break;
160 }
161
162 if ($newlevel == 1) {
163 $updatelevel1 = true;
164 }
165 }
166
167 // Update single price
168 $price_base_type = $objectstatic->price_base_type; // Get price_base_type of product/service to keep the same for update
169 if ($price_base_type == 'TTC') {
170 $newprice = price2num($objectstatic->price_ttc, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
171 $newminprice = $objectstatic->price_min_ttc;
172 } else {
173 $newprice = price2num($objectstatic->price, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
174 $newminprice = $objectstatic->price_min;
175 }
176 if ($newminprice > $newprice) {
177 $newminprice = $newprice;
178 }
179 $newvat = str_replace('*', '', $newvatrate);
180 $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
181 $newnpr = $objectstatic->tva_npr;
182 $newdefaultvatcode = $vat_src_code_new;
183 $newlevel = 0;
184 if (!empty($price_base_type) && !$updatelevel1) {
185 //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
186 $ret = $objectstatic->updatePrice((float) $newprice, $price_base_type, $user, (float) $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode);
187 }
188
189 if ($ret < 0 || $retm < 0) {
190 $error++;
191 } else {
192 $nbrecordsmodified++;
193 }
194 }
195 unset($objectstatic);
196
197 $i++;
198 }
199 } else {
200 dol_print_error($db);
201 }
202
203 // Sweep: updatePrice() above only reaches products that have a defined price. Set the target
204 // rate and VAT code directly on any product/price row still matching the old value (products
205 // without a price, and historical price rows), so the mass change is complete.
206 $sweepwhere = " AND tva_tx = '".$db->escape($oldvatrateclean)."'";
207 if ($vat_src_code_old) {
208 $sweepwhere .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
209 } else {
210 $sweepwhere .= " AND (default_vat_code IS NULL OR default_vat_code = '')";
211 }
212 $db->query("UPDATE ".MAIN_DB_PREFIX."product SET tva_tx = '".$db->escape($newvatrateclean)."', default_vat_code = '".$db->escape($vat_src_code_new)."' WHERE entity IN (".getEntity('product').")".$sweepwhere);
213 $db->query("UPDATE ".MAIN_DB_PREFIX."product_price SET tva_tx = '".$db->escape($newvatrateclean)."', default_vat_code = '".$db->escape($vat_src_code_new)."' WHERE 1 = 1".$sweepwhere);
214 }
215
216 $fourn = new Fournisseur($db);
217
218 // Change supplier prices
219 $sql = 'SELECT pfp.rowid, pfp.fk_soc, pfp.price as price, pfp.quantity as qty, pfp.fk_availability, pfp.ref_fourn';
220 $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp, '.MAIN_DB_PREFIX.'societe as s';
221 $sql .= ' WHERE pfp.fk_soc = s.rowid AND pfp.entity IN ('.getEntity('product').')';
222 $sql .= " AND tva_tx = '".$db->escape($oldvatrate)."'";
223 if ($vat_src_code_old) {
224 $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
225 } else {
226 $sql .= " AND (default_vat_code IS NULL OR default_vat_code = '')";
227 }
228 $sql .= " AND s.fk_pays = ".((int) $country_id);
229
230 $resql = $db->query($sql);
231 if ($resql) {
232 $num = $db->num_rows($resql);
233
234 $i = 0;
235 while ($i < $num) {
236 $obj = $db->fetch_object($resql);
237
238 $objectstatic2 = new ProductFournisseur($db); // Object init must be into loop to avoid to get value of previous step
239 $ret = $objectstatic2->fetch_product_fournisseur_price($obj->rowid);
240 if ($ret > 0) {
241 $ret = 0;
242 $retm = 0;
243 $updatelevel1 = false;
244
245 $price_base_type = 'HT';
246 //$price_base_type = $objectstatic2->price_base_type; // Get price_base_type of product/service to keep the same for update
247 //if ($price_base_type == 'TTC')
248 //{
249 // $newprice=price2num($objectstatic2->price_ttc,'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
250 // $newminprice=$objectstatic2->price_min_ttc;
251 //}
252 //else
253 //{
254 $newprice = price2num($obj->price, 'MU'); // Second param must be MU (we want a unit price so 'MU'. If unit price was on 4 decimal, we must keep 4 decimals)
255 //$newminprice=$objectstatic2->fourn_price_min;
256 //}
257 //if ($newminprice > $newprice) $newminprice=$newprice;
258 $newvat = str_replace('*', '', $newvatrate);
259 $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
260 //$newnpr=$objectstatic2->tva_npr;
261 $newnpr = 0;
262 $newdefaultvatcode = $vat_src_code_new;
263
264 $newpercent = $objectstatic2->fourn_remise_percent;
265 $newdeliverydelay = $objectstatic2->delivery_time_days;
266 $newsupplierreputation = $objectstatic2->supplier_reputation;
267
268 $newlevel = 0;
269 if (!empty($price_base_type) && !$updatelevel1) {
270 //print "$objectstatic2->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
271 $fourn->id = $obj->fk_soc;
272 $ret = $objectstatic2->update_buyprice($obj->qty, (float) $newprice, $user, $price_base_type, $fourn, $obj->fk_availability, $obj->ref_fourn, (float) $newvat, '', $newpercent, 0, $newnpr, $newdeliverydelay, $newsupplierreputation, $localtaxes_type, $newdefaultvatcode);
273 }
274
275 if ($ret < 0 || $retm < 0) {
276 $error++;
277 } else {
278 $nbrecordsmodified++;
279 }
280 }
281 unset($objectstatic2);
282
283 $i++;
284 }
285 } else {
286 dol_print_error($db);
287 }
288
289
290 // add hook for external modules
291 $parameters = array('oldvatrate' => $oldvatrate, 'newvatrate' => $newvatrate);
292 $reshook = $hookmanager->executeHooks('hookAfterVatUpdate', $parameters);
293 if ($reshook < 0) {
294 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
295 $error++;
296 }
297
298 if (!getDolGlobalInt('VATUPDATE_NO_TRANSACTION')) {
299 if (!$error) {
300 $db->commit();
301 } else {
302 $db->rollback();
303 }
304 }
305
306 // Output result
307 if (!$error) {
308 if ($nbrecordsmodified > 0) {
309 setEventMessages($langs->trans("RecordsModified", $nbrecordsmodified), null, 'mesgs');
310 } else {
311 setEventMessages($langs->trans("NoRecordFound"), null, 'warnings');
312 }
313 } else {
314 setEventMessages($langs->trans("Error"), null, 'errors');
315 }
316 }
317}
318
319/*
320 * View
321 */
322
323$form = new Form($db);
324
325$title = $langs->trans('ProductVatMassChange');
326
327llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-product page-admin_product_tools');
328
329print load_fiche_titre($title, '', 'title_setup');
330
331print '<div class="info">'.$langs->trans("ProductVatMassChangeDesc").'</div>';
332print '<br>';
333
334if (empty($mysoc->country_code)) {
335 $langs->load("errors");
336 $warnpicto = img_error($langs->trans("WarningMandatorySetupNotComplete"));
337 print '<br><a href="'.DOL_URL_ROOT.'/admin/company.php?mainmenu=home">'.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").'</a>';
338} else {
339 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
340 print '<input type="hidden" name="token" value="'.newToken().'" />';
341 print '<input type="hidden" name="action" value="convert" />';
342
343 print '<table class="noborder centpercent">';
344 print '<tr class="liste_titre">';
345 print '<td>'.$langs->trans("From").'/'.$langs->trans("To").'</td>'."\n";
346 print '<td class="right" width="60"></td>'."\n";
347 print '</tr>'."\n";
348
349
350 print '<tr class="oddeven">'."\n";
351 print '<td>'.$langs->trans("OldVATRates").'</td>'."\n";
352 print '<td width="60" class="right">'."\n";
353 // Old VAT rate: distinct (rate, code) pairs present on products, with the count of products for
354 // each -- so the source to convert (including rates without a VAT code) is visible and quantified.
355 print '<select class="flat" name="oldvatrate" id="oldvatrate">';
356 $sqloldvat = "SELECT tva_tx, default_vat_code, COUNT(*) as nb FROM ".MAIN_DB_PREFIX."product";
357 $sqloldvat .= " WHERE entity IN (".getEntity('product').") AND tva_tx IS NOT NULL";
358 $sqloldvat .= " GROUP BY tva_tx, default_vat_code ORDER BY tva_tx DESC, default_vat_code";
359 $resqloldvat = $db->query($sqloldvat);
360 while ($resqloldvat && $objoldvat = $db->fetch_object($resqloldvat)) {
361 $rateclean = price2num($objoldvat->tva_tx);
362 $hascode = !empty($objoldvat->default_vat_code);
363 $optval = $rateclean.($hascode ? ' ('.$objoldvat->default_vat_code.')' : '');
364 $optlbl = vatrate($rateclean, true).($hascode ? ' ('.$objoldvat->default_vat_code.')' : ' ('.$langs->trans("WithoutVATCode").')').' &nbsp; ['.$objoldvat->nb.' '.$langs->trans("Products").']';
365 print '<option value="'.dol_escape_htmltag($optval).'"'.((string) $oldvatrate === (string) $optval ? ' selected' : '').'>'.$optlbl.'</option>';
366 }
367 print '</select>';
368 print ajax_combobox('oldvatrate');
369 print '</td>'."\n";
370 print '</tr>'."\n";
371
372
373 print '<tr class="oddeven">'."\n";
374 print '<td>'.$langs->trans("NewVATRates").'</td>'."\n";
375 print '<td width="60" class="right">'."\n";
376 print $form->load_tva('newvatrate', $newvatrate, $mysoc, null, 0, 0, '', false, 1);
377 print ajax_combobox('newvatrate');
378 print '</td>'."\n";
379 print '</tr>'."\n";
380
381 /*
382
383 print '<tr class="oddeven">'."\n";
384 print '<td>'.$langs->trans("PriceBaseTypeToChange").'</td>'."\n";
385 print '<td width="60" class="right">'."\n";
386 print $form->selectPriceBaseType($price_base_type);
387 print '</td>'."\n";
388 print '</tr>'."\n";
389 */
390
391 print '</table>';
392
393 print '<br>';
394
395 // Buttons for actions
396
397 print '<div class="center">';
398 print '<input type="submit" id="convert_vatrate" name="convert_vatrate" value="'.$langs->trans("MassConvert").'" class="button" />';
399 print '</div>';
400
401 print '</form>';
402
403 // The conversion loops over every matching product with updatePrice(): on a large
404 // catalog the request runs for minutes with no feedback, which invites re-submits.
405 // Show the native blocking overlay (dolBlockUI + working.gif) while it runs.
406 print '<script>
407 jQuery(function() {
408 jQuery("#convert_vatrate").closest("form").on("submit", function() {
409 dolBlockUI(\''.dol_escape_js($langs->transnoentities("MassConvertInProgress")).'\');
410 });
411 });
412 </script>';
413}
414
415// End of page
416llxFooter();
417$db->close();
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='', $placeholder='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:488
if(!defined('NOREQUIRESOC')) if(!defined( 'NOREQUIRETRAN')) if(!defined('NOTOKENRENEWAL')) if(!defined( 'NOREQUIREMENU')) if(!defined('NOREQUIREHTML')) if(!defined( 'NOREQUIREAJAX')) llxHeader($head='', $title='', $help_url='', $target='', $disablejs=0, $disablehead=0, $arrayofjs='', $arrayofcss='', $morequerystring='', $morecssonbody='', $replacemainareaby='', $disablenofollow=0, $disablenoindex=0)
Empty header.
Definition wrapper.php:73
Class to manage generation of HTML components Only common components must be here.
Class to manage suppliers.
Class to manage predefined suppliers products.
Class to manage products or services.
global $mysoc
vatrate($rate, $addpercent=false, $info_bits=0, $usestarfornpr=0, $html=0)
Return a string with VAT rate label formatted for view output Used into pdf and HTML pages.
price2num($amount, $rounding='', $option=0, $currencycode='')
Function that return a number with universal decimal format (decimal separator is '.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getLocalTaxesFromRate($vatrate, $local, $buyer, $seller, $firstparamisid=0)
Get type and rate of localtaxes for a particular vat rate/country of a thirdparty.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='', $morecssonpicto='widthpictotitle')
Load a title with picto.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.