dolibarr 22.0.5
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 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
27// TODO We must add a confirmation on button because this will make a mass change
28// FIXME Should also change table product_price for price levels
29
30// Load Dolibarr environment
31require '../../main.inc.php';
32require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
33require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
34require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
35require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.product.class.php';
36
46// Load translation files required by the page
47$langs->loadLangs(array('admin', 'products'));
48
49// Security check
50if (!$user->admin) {
52}
53
54$action = GETPOST('action', 'aZ09');
55$oldvatrate = GETPOST('oldvatrate', 'alpha');
56$newvatrate = GETPOST('newvatrate', 'alpha');
57//$price_base_type=GETPOST('price_base_type');
58
59
60
61/*
62 * Actions
63 */
64
65if ($action == 'convert') {
66 $error = 0;
67
68 if ($oldvatrate == $newvatrate) {
69 $langs->load("errors");
70 setEventMessages($langs->trans("ErrorNewValueCantMatchOldValue"), null, 'errors');
71 $error++;
72 }
73
74 if (!$error) {
75 $country_id = $mysoc->country_id; // TODO Allow to choose country into form
76
77 $nbrecordsmodified = 0;
78
79 if (!getDolGlobalInt('VATUPDATE_NO_TRANSACTION')) {
80 $db->begin();
81 }
82
83 // Clean vat code old
84 $vat_src_code_old = '';
85 if (preg_match('/\‍((.*)\‍)/', $oldvatrate, $reg)) {
86 $vat_src_code_old = $reg[1];
87 $oldvatrateclean = preg_replace('/\s*\‍(.*\‍)/', '', $oldvatrate); // Remove code into vatrate.
88 } else {
89 $oldvatrateclean = $oldvatrate;
90 }
91
92 // Clean vat code new
93 $vat_src_code_new = '';
94 if (preg_match('/\‍((.*)\‍)/', $newvatrate, $reg)) {
95 $vat_src_code_new = $reg[1];
96 $newvatrateclean = preg_replace('/\s*\‍(.*\‍)/', '', $newvatrate); // Remove code into vatrate.
97 } else {
98 $newvatrateclean = $newvatrate;
99 }
100
101 // If country to edit is my country, so we change customer prices
102 if ($country_id == $mysoc->country_id) {
103 $sql = 'SELECT rowid';
104 $sql .= ' FROM '.MAIN_DB_PREFIX.'product';
105 $sql .= ' WHERE entity IN ('.getEntity('product').')';
106 $sql .= " AND tva_tx = '".$db->escape($oldvatrateclean)."'";
107 if ($vat_src_code_old) {
108 $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
109 } else {
110 $sql .= " AND default_vat_code = IS NULL";
111 }
112
113 $resql = $db->query($sql);
114 if ($resql) {
115 $num = $db->num_rows($resql);
116
117 $i = 0;
118 while ($i < $num) {
119 $obj = $db->fetch_object($resql);
120
121 $objectstatic = new Product($db); // Object init must be into loop to avoid to get value of previous step
122 $ret = $objectstatic->fetch($obj->rowid);
123 if ($ret > 0) {
124 $ret = 0;
125 $retm = 0;
126 $updatelevel1 = false;
127
128 // Update multiprice
129 $listofmulti = array_reverse($objectstatic->multiprices, true); // To finish with level 1
130 foreach ($listofmulti as $level => $multiprices) {
131 $price_base_type = $objectstatic->multiprices_base_type[$level]; // Get price_base_type of product/service to keep the same for update
132 if (empty($price_base_type)) {
133 continue; // Discard not defined price levels
134 }
135
136 if ($price_base_type == 'TTC') {
137 $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)
138 $newminprice = $objectstatic->multiprices_min_ttc[$level];
139 } else {
140 $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)
141 $newminprice = $objectstatic->multiprices_min[$level];
142 }
143 if ($newminprice > $newprice) {
144 $newminprice = $newprice;
145 }
146
147 $newvat = str_replace('*', '', $newvatrate);
148 $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
149 $newnpr = $objectstatic->multiprices_recuperableonly[$level];
150 $newdefaultvatcode = $vat_src_code_new;
151 $newlevel = $level;
152
153 //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
154 $retm = $objectstatic->updatePrice((float) $newprice, $price_base_type, $user, (float) $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode);
155 if ($retm < 0) {
156 $error++;
157 break;
158 }
159
160 if ($newlevel == 1) {
161 $updatelevel1 = true;
162 }
163 }
164
165 // Update single price
166 $price_base_type = $objectstatic->price_base_type; // Get price_base_type of product/service to keep the same for update
167 if ($price_base_type == 'TTC') {
168 $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)
169 $newminprice = $objectstatic->price_min_ttc;
170 } else {
171 $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)
172 $newminprice = $objectstatic->price_min;
173 }
174 if ($newminprice > $newprice) {
175 $newminprice = $newprice;
176 }
177 $newvat = str_replace('*', '', $newvatrate);
178 $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
179 $newnpr = $objectstatic->tva_npr;
180 $newdefaultvatcode = $vat_src_code_new;
181 $newlevel = 0;
182 if (!empty($price_base_type) && !$updatelevel1) {
183 //print "$objectstatic->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
184 $ret = $objectstatic->updatePrice((float) $newprice, $price_base_type, $user, (float) $newvatrateclean, $newminprice, $newlevel, $newnpr, 0, 0, $localtaxes_type, $newdefaultvatcode);
185 }
186
187 if ($ret < 0 || $retm < 0) {
188 $error++;
189 } else {
190 $nbrecordsmodified++;
191 }
192 }
193 unset($objectstatic);
194
195 $i++;
196 }
197 } else {
198 dol_print_error($db);
199 }
200 }
201
202 $fourn = new Fournisseur($db);
203
204 // Change supplier prices
205 $sql = 'SELECT pfp.rowid, pfp.fk_soc, pfp.price as price, pfp.quantity as qty, pfp.fk_availability, pfp.ref_fourn';
206 $sql .= ' FROM '.MAIN_DB_PREFIX.'product_fournisseur_price as pfp, '.MAIN_DB_PREFIX.'societe as s';
207 $sql .= ' WHERE pfp.fk_soc = s.rowid AND pfp.entity IN ('.getEntity('product').')';
208 $sql .= " AND tva_tx = '".$db->escape($oldvatrate)."'";
209 if ($vat_src_code_old) {
210 $sql .= " AND default_vat_code = '".$db->escape($vat_src_code_old)."'";
211 } else {
212 $sql .= " AND default_vat_code = IS NULL";
213 }
214 $sql .= " AND s.fk_pays = ".((int) $country_id);
215
216 $resql = $db->query($sql);
217 if ($resql) {
218 $num = $db->num_rows($resql);
219
220 $i = 0;
221 while ($i < $num) {
222 $obj = $db->fetch_object($resql);
223
224 $objectstatic2 = new ProductFournisseur($db); // Object init must be into loop to avoid to get value of previous step
225 $ret = $objectstatic2->fetch_product_fournisseur_price($obj->rowid);
226 if ($ret > 0) {
227 $ret = 0;
228 $retm = 0;
229 $updatelevel1 = false;
230
231 $price_base_type = 'HT';
232 //$price_base_type = $objectstatic2->price_base_type; // Get price_base_type of product/service to keep the same for update
233 //if ($price_base_type == 'TTC')
234 //{
235 // $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)
236 // $newminprice=$objectstatic2->price_min_ttc;
237 //}
238 //else
239 //{
240 $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)
241 //$newminprice=$objectstatic2->fourn_price_min;
242 //}
243 //if ($newminprice > $newprice) $newminprice=$newprice;
244 $newvat = str_replace('*', '', $newvatrate);
245 $localtaxes_type = getLocalTaxesFromRate($newvat, 0, $mysoc, $mysoc);
246 //$newnpr=$objectstatic2->tva_npr;
247 $newnpr = 0;
248 $newdefaultvatcode = $vat_src_code_new;
249
250 $newpercent = $objectstatic2->fourn_remise_percent;
251 $newdeliverydelay = $objectstatic2->delivery_time_days;
252 $newsupplierreputation = $objectstatic2->supplier_reputation;
253
254 $newlevel = 0;
255 if (!empty($price_base_type) && !$updatelevel1) {
256 //print "$objectstatic2->id $newprice, $price_base_type, $newvat, $newminprice, $newlevel, $newnpr<br>\n";
257 $fourn->id = $obj->fk_soc;
258 $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);
259 }
260
261 if ($ret < 0 || $retm < 0) {
262 $error++;
263 } else {
264 $nbrecordsmodified++;
265 }
266 }
267 unset($objectstatic2);
268
269 $i++;
270 }
271 } else {
272 dol_print_error($db);
273 }
274
275
276 // add hook for external modules
277 $parameters = array('oldvatrate' => $oldvatrate, 'newvatrate' => $newvatrate);
278 $reshook = $hookmanager->executeHooks('hookAfterVatUpdate', $parameters);
279 if ($reshook < 0) {
280 setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
281 $error++;
282 }
283
284 if (!getDolGlobalInt('VATUPDATE_NO_TRANSACTION')) {
285 if (!$error) {
286 $db->commit();
287 } else {
288 $db->rollback();
289 }
290 }
291
292 // Output result
293 if (!$error) {
294 if ($nbrecordsmodified > 0) {
295 setEventMessages($langs->trans("RecordsModified", $nbrecordsmodified), null, 'mesgs');
296 } else {
297 setEventMessages($langs->trans("NoRecordFound"), null, 'warnings');
298 }
299 } else {
300 setEventMessages($langs->trans("Error"), null, 'errors');
301 }
302 }
303}
304
305/*
306 * View
307 */
308
309$form = new Form($db);
310
311$title = $langs->trans('ProductVatMassChange');
312
313llxHeader('', $title, '', '', 0, 0, '', '', '', 'mod-product page-admin_product_tools');
314
315print load_fiche_titre($title, '', 'title_setup');
316
317print $langs->trans("ProductVatMassChangeDesc").'<br><br>';
318
319if (empty($mysoc->country_code)) {
320 $langs->load("errors");
321 $warnpicto = img_error($langs->trans("WarningMandatorySetupNotComplete"));
322 print '<br><a href="'.DOL_URL_ROOT.'/admin/company.php?mainmenu=home">'.$warnpicto.' '.$langs->trans("WarningMandatorySetupNotComplete").'</a>';
323} else {
324 print '<form method="POST" action="'.$_SERVER['PHP_SELF'].'">';
325 print '<input type="hidden" name="token" value="'.newToken().'" />';
326 print '<input type="hidden" name="action" value="convert" />';
327
328 print '<table class="noborder centpercent">';
329 print '<tr class="liste_titre">';
330 print '<td>'.$langs->trans("Parameters").'</td>'."\n";
331 print '<td class="right" width="60">'.$langs->trans("Value").'</td>'."\n";
332 print '</tr>'."\n";
333
334
335 print '<tr class="oddeven">'."\n";
336 print '<td>'.$langs->trans("OldVATRates").'</td>'."\n";
337 print '<td width="60" class="right">'."\n";
338 print $form->load_tva('oldvatrate', $oldvatrate, $mysoc, null, 0, 0, '', false, 1);
339 print '</td>'."\n";
340 print '</tr>'."\n";
341
342
343 print '<tr class="oddeven">'."\n";
344 print '<td>'.$langs->trans("NewVATRates").'</td>'."\n";
345 print '<td width="60" class="right">'."\n";
346 print $form->load_tva('newvatrate', $newvatrate, $mysoc, null, 0, 0, '', false, 1);
347 print '</td>'."\n";
348 print '</tr>'."\n";
349
350 /*
351
352 print '<tr class="oddeven">'."\n";
353 print '<td>'.$langs->trans("PriceBaseTypeToChange").'</td>'."\n";
354 print '<td width="60" class="right">'."\n";
355 print $form->selectPriceBaseType($price_base_type);
356 print '</td>'."\n";
357 print '</tr>'."\n";
358 */
359
360 print '</table>';
361
362 print '<br>';
363
364 // Buttons for actions
365
366 print '<div class="center">';
367 print '<input type="submit" id="convert_vatrate" name="convert_vatrate" value="'.$langs->trans("MassConvert").'" class="button" />';
368 print '</div>';
369
370 print '</form>';
371}
372
373// End of page
374llxFooter();
375$db->close();
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:91
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.
load_fiche_titre($title, $morehtmlright='', $picto='generic', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
price2num($amount, $rounding='', $option=0)
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)
Return value of a param into GET or POST supervariable.
img_error($titlealt='default')
Show error logo.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.