dolibarr 21.0.0-beta
combinations.php
1<?php
2/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
3 * Copyright (C) 2017 Laurent Destailleur <eldy@users.sourceforge.net>
4 * Copyright (C) 2018-2024 Frédéric France <frederic.france@free.fr>
5 * Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
6 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.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
22// Load Dolibarr environment
23require '../main.inc.php';
24require_once DOL_DOCUMENT_ROOT.'/core/lib/product.lib.php';
25require_once DOL_DOCUMENT_ROOT.'/product/class/product.class.php';
26require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
27require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
28require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination.class.php';
29require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
30
39$langs->loadLangs(array("products", "other"));
40
41$id = GETPOSTINT('id'); // ID of the parent Product
42$ref = GETPOST('ref', 'alpha');
43
44$combination_id = GETPOSTINT('combination_id'); // ID of the combination
45
46$reference = GETPOST('reference', 'alpha'); // Reference of the variant Product
47
48$weight_impact = GETPOSTFLOAT('weight_impact', 2);
49$price_impact_percent = (bool) GETPOST('price_impact_percent');
50$price_impact = $price_impact_percent ? GETPOSTFLOAT('price_impact', 2) : GETPOSTFLOAT('price_impact', 'MU');
51
52// for PRODUIT_MULTIPRICES
53$level_price_impact = GETPOST('level_price_impact', 'array');
54$level_price_impact = array_map('price2num', $level_price_impact);
55$level_price_impact = array_map('floatval', $level_price_impact);
56$level_price_impact_percent = GETPOST('level_price_impact_percent', 'array');
57$level_price_impact_percent = array_map('boolval', $level_price_impact_percent);
58
59$form = new Form($db);
60
61$action = GETPOST('action', 'aZ09');
62$massaction = GETPOST('massaction', 'alpha');
63$show_files = GETPOSTINT('show_files');
64$confirm = GETPOST('confirm', 'alpha');
65$toselect = GETPOST('toselect', 'array');
66$cancel = GETPOST('cancel', 'alpha');
67$delete_product = GETPOST('delete_product', 'alpha');
68$subaction = GETPOST('subaction', 'aZ09');
69$backtopage = GETPOST('backtopage', 'alpha');
70$sortfield = GETPOST('sortfield', 'aZ09comma');
71$sortorder = GETPOST('sortorder', 'aZ09comma');
72
73// Security check
74$fieldvalue = $id ?: $ref;
75$fieldtype = !empty($ref) ? 'ref' : 'rowid';
76
77$prodstatic = new Product($db);
78$prodattr = new ProductAttribute($db);
79$prodattr_val = new ProductAttributeValue($db);
80
81$object = new Product($db);
82if ($id > 0 || $ref) {
83 $object->fetch($id, $ref);
84}
85
86$selectedvariant = isset($_SESSION['addvariant_'.$object->id]) ? $_SESSION['addvariant_'.$object->id] : array();
87$selected = '';
88// Security check
89if (!isModEnabled('variants')) {
90 accessforbidden('Module not enabled');
91}
92if ($user->socid > 0) { // Protection if external user
94}
95
96if ($object->id > 0) {
97 if ($object->isProduct()) {
98 restrictedArea($user, 'produit', $object->id, 'product&product', '', '');
99 }
100 if ($object->isService()) {
101 restrictedArea($user, 'service', $object->id, 'product&product', '', '');
102 }
103} else {
104 restrictedArea($user, 'produit|service', $fieldvalue, 'product&product', '', '', $fieldtype);
105}
106$usercanread = (($object->isProduct() && $user->hasRight('produit', 'lire')) || ($object->isService() && $user->hasRight('service', 'lire')));
107$usercancreate = (($object->isProduct() && $user->hasRight('produit', 'creer')) || ($object->isService() && $user->hasRight('service', 'creer')));
108$usercandelete = (($object->isProduct() && $user->hasRight('produit', 'supprimer')) || ($object->isService() && $user->hasRight('service', 'supprimer')));
109
110
111/*
112 * Actions
113 */
114
115if ($cancel) {
116 $action = '';
117 $massaction = '';
118 unset($_SESSION['addvariant_'.$object->id]);
119}
120
121if (!$object->isProduct() && !$object->isService()) {
122 header('Location: '.dol_buildpath('/product/card.php?id='.$object->id, 2));
123 exit();
124}
125if ($action == 'add') { // Test on permission not required
126 unset($selectedvariant);
127 unset($_SESSION['addvariant_'.$object->id]);
128}
129if ($action == 'create' && GETPOST('selectvariant', 'alpha') && $usercancreate) { // We click on select combination
130 $action = 'add';
131 $attribute_id = GETPOSTINT('attribute');
132 $attribute_value_id = GETPOSTINT('value');
133 if ($attribute_id > 0 && $attribute_value_id > 0) {
134 $feature = $attribute_id . '-' . $attribute_value_id;
135 $selectedvariant[$feature] = $feature;
136 $_SESSION['addvariant_'.$object->id] = $selectedvariant;
137 }
138}
139if ($action == 'create' && $subaction == 'delete' && $usercancreate) { // We click on select combination
140 $action = 'add';
141 $feature = GETPOST('feature', 'intcomma');
142 if (isset($selectedvariant[$feature])) {
143 unset($selectedvariant[$feature]);
144 $_SESSION['addvariant_'.$object->id] = $selectedvariant;
145 }
146}
147
148
149$prodcomb = new ProductCombination($db);
150$prodcomb2val = new ProductCombination2ValuePair($db);
151
152$productCombination2ValuePairs1 = array();
153
154if (($action == 'add' || $action == 'create') && $usercancreate && empty($massaction) && !GETPOST('selectvariant', 'alpha') && empty($subaction)) { // We click on Create all defined combinations
155 //$features = GETPOST('features', 'array');
156 $features = !empty($_SESSION['addvariant_'.$object->id]) ? $_SESSION['addvariant_'.$object->id] : array();
157
158 if (!$features) {
159 if ($action == 'create') { // Test on permission already done
160 setEventMessages($langs->trans('ErrorFieldsRequired'), null, 'errors');
161 }
162 } else {
163 $reference = trim($reference);
164 if (empty($reference)) {
165 $reference = false;
166 }
167 $weight_impact = price2num($weight_impact);
168 $price_impact = price2num($price_impact);
169
170 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
171 $level_price_impact = array(1 => $price_impact);
172 $level_price_impact_percent = array(1 => $price_impact_percent);
173 }
174
175 $sanit_features = array();
176
177 //First, sanitize
178 foreach ($features as $feature) {
179 $explode = explode('-', $feature);
180 if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
181 continue;
182 }
183
184 // Valuepair
185 $sanit_features[(int) $explode[0]] = (int) $explode[1];
186
187 $tmp = new ProductCombination2ValuePair($db);
188 $tmp->fk_prod_attr = (int) $explode[0];
189 $tmp->fk_prod_attr_val = (int) $explode[1];
190
191 $productCombination2ValuePairs1[] = $tmp;
192 }
193
194 $db->begin();
195
196 // sanit_feature is an array with 1 (and only 1) value per attribute.
197 // For example: Color->blue, Size->Small, Option->2
198 if (!$prodcomb->fetchByProductCombination2ValuePairs($id, $sanit_features)) {
199 $result = $prodcomb->createProductCombination($user, $object, $sanit_features, array(), $level_price_impact_percent, $level_price_impact, $weight_impact, $reference);
200 if ($result > 0) {
201 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
202 unset($_SESSION['addvariant_'.$object->id]);
203
204 $db->commit();
205 header('Location: '.dol_buildpath('/variants/combinations.php?id='.$id, 2));
206 exit();
207 } else {
208 $langs->load("errors");
209 setEventMessages($prodcomb->error, $prodcomb->errors, 'errors');
210 }
211 } else {
212 setEventMessages($langs->trans('ErrorRecordAlreadyExists'), null, 'errors');
213 }
214
215 $db->rollback();
216 }
217} elseif (!empty($massaction)) {
218 $bulkaction = $massaction;
219 $error = 0;
220
221 $db->begin();
222
223 foreach ($toselect as $prodid) {
224 // need create new of Product to prevent rename dir behavior
225 $prodstatic = new Product($db);
226 if ($prodstatic->fetch($prodid) < 0) {
227 continue;
228 }
229
230 if ($bulkaction == 'on_sell') {
231 $prodstatic->status = 1;
232 $res = $prodstatic->update($prodstatic->id, $user);
233 if ($res <= 0) {
234 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
235 $error++;
236 break;
237 }
238 } elseif ($bulkaction == 'on_buy') {
239 $prodstatic->status_buy = 1;
240 $res = $prodstatic->update($prodstatic->id, $user);
241 if ($res <= 0) {
242 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
243 $error++;
244 break;
245 }
246 } elseif ($bulkaction == 'not_sell') {
247 $prodstatic->status = 0;
248 $res = $prodstatic->update($prodstatic->id, $user);
249 if ($res <= 0) {
250 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
251 $error++;
252 break;
253 }
254 } elseif ($bulkaction == 'not_buy') {
255 $prodstatic->status_buy = 0;
256 $res = $prodstatic->update($prodstatic->id, $user);
257 if ($res <= 0) {
258 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
259 $error++;
260 break;
261 }
262 } elseif ($bulkaction == 'delete') {
263 $res = $prodstatic->delete($user, $prodstatic->id);
264 if ($res <= 0) {
265 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
266 $error++;
267 break;
268 }
269 } else {
270 break;
271 }
272 }
273
274 if ($error) {
275 $db->rollback();
276 if (empty($prodstatic->error)) {
277 setEventMessages($langs->trans('CoreErrorMessage'), null, 'errors');
278 }
279 } else {
280 $db->commit();
281 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
282 }
283} elseif ($action === 'update' && $combination_id > 0 && $usercancreate) {
284 if ($prodcomb->fetch($combination_id) < 0) {
285 dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
286 exit();
287 }
288
289 $prodcomb->variation_weight = (float) price2num($weight_impact);
290
291 // for conf PRODUIT_MULTIPRICES
292 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
293 $prodcomb->variation_price = $level_price_impact[1];
294 $prodcomb->variation_price_percentage = $level_price_impact_percent[1];
295 } else {
296 $level_price_impact = array(1 => $price_impact);
297 $level_price_impact_percent = array(1 => $price_impact_percent);
298
299 $prodcomb->variation_price = $price_impact;
300 $prodcomb->variation_price_percentage = $price_impact_percent;
301 }
302
303 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
304 $prodcomb->combination_price_levels = array();
305 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
306 for ($i = 1; $i <= $maxi; $i++) {
307 $productCombinationLevel = new ProductCombinationLevel($db);
308 $productCombinationLevel->fk_product_attribute_combination = $prodcomb->id;
309 $productCombinationLevel->fk_price_level = $i;
310 $productCombinationLevel->variation_price = (float) $level_price_impact[$i];
311 $productCombinationLevel->variation_price_percentage = (bool) $level_price_impact_percent[$i];
312 $prodcomb->combination_price_levels[$i] = $productCombinationLevel;
313 }
314 }
315
316 $error = 0;
317 $db->begin();
318
319 // Update product variant ref
320 $product_child = new Product($db);
321 $product_child->fetch($prodcomb->fk_product_child);
322 $product_child->oldcopy = clone $product_child; // @phan-ignore-current-line PhanTypeMismatchProperty
323 $product_child->ref = $reference;
324
325 $result = $product_child->update($product_child->id, $user);
326 if ($result < 0) {
327 setEventMessages($product_child->error, $product_child->errors, 'errors');
328 $error++;
329 }
330
331 if (!$error) {
332 // Update product variant infos
333 $result = $prodcomb->update($user);
334 if ($result < 0) {
335 setEventMessages($prodcomb->error, $prodcomb->errors, 'errors');
336 $error++;
337 }
338 }
339
340 if (!$error) {
341 $db->commit();
342 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
343 header('Location: ' . dol_buildpath('/variants/combinations.php?id=' . $id, 2));
344 exit();
345 } else {
346 $db->rollback();
347 }
348}
349
350
351// Reload variants
352$productCombinations = $prodcomb->fetchAllByFkProductParent($object->id, true);
353
354if ($action === 'confirm_deletecombination' && $usercancreate) {
355 if ($prodcomb->fetch($combination_id) > 0) {
356 $db->begin();
357
358 if ($prodcomb->delete($user) > 0 && (empty($delete_product) || ($delete_product == 'on' && $prodstatic->fetch($prodcomb->fk_product_child) > 0 && $prodstatic->delete($user) > 0))) {
359 $db->commit();
360 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
361 header('Location: '.dol_buildpath('/variants/combinations.php?id='.$object->id, 2));
362 exit();
363 }
364
365 $db->rollback();
366 setEventMessages($langs->trans('ProductCombinationAlreadyUsed'), null, 'errors');
367 $action = '';
368 }
369} elseif ($action === 'edit' && $usercancreate) {
370 if ($prodcomb->fetch($combination_id) < 0) {
371 dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
372 exit();
373 }
374
375 $product_child = new Product($db);
376 $product_child->fetch($prodcomb->fk_product_child);
377 $reference = $product_child->ref;
378 $weight_impact = $prodcomb->variation_weight;
379 $price_impact = $prodcomb->variation_price;
380 $price_impact_percent = $prodcomb->variation_price_percentage;
381
382 $productCombination2ValuePairs1 = $prodcomb2val->fetchByFkCombination($combination_id);
383} elseif ($action === 'confirm_copycombination' && $usercancreate) {
384 //Check destination product
385 $dest_product = GETPOST('dest_product');
386
387 if ($prodstatic->fetch(0, $dest_product) > 0) {
388 //To prevent from copying to the same product
389 if ($prodstatic->ref != $object->ref) {
390 if ($prodcomb->copyAll($user, $object->id, $prodstatic) > 0) {
391 header('Location: '.dol_buildpath('/variants/combinations.php?id='.$prodstatic->id, 2));
392 exit();
393 } else {
394 setEventMessages($langs->trans('ErrorCopyProductCombinations'), null, 'errors');
395 }
396 }
397 } else {
398 setEventMessages($langs->trans('ErrorDestinationProductNotFound'), null, 'errors');
399 }
400}
401
402
403
404/*
405 * View
406 */
407
408$form = new Form($db);
409
410$title = $langs->trans("Variant");
411
412llxHeader("", $title);
413
414
415if (!empty($id) || !empty($ref)) {
416 $showbarcode = isModEnabled('barcode');
417 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
418 $showbarcode = 0;
419 }
420
421 $head = product_prepare_head($object);
422 $titre = $langs->trans("CardProduct".$object->type);
423 $picto = $object->isService() ? 'service' : 'product';
424
425 print dol_get_fiche_head($head, 'combinations', $titre, -1, $picto);
426
427 $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?type='.((int) $object->type).'">'.$langs->trans("BackToList").'</a>';
428 $object->next_prev_filter = "fk_product_type:=:".((int) $object->type); // usf filter
429
430 dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref', '', '', '', 0, '', '');
431
432 print '<div class="fichecenter">';
433
434 print '<div class="underbanner clearboth"></div>';
435 print '<table class="border centpercent tableforfield">';
436
437 // Type
438 if (isModEnabled("product") && isModEnabled("service")) {
439 $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service");
440 print '<tr><td class="titlefieldcreate">';
441 print (!getDolGlobalString('PRODUCT_DENY_CHANGE_PRODUCT_TYPE')) ? $form->editfieldkey("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat) : $langs->trans('Type');
442 print '</td><td>';
443 print $form->editfieldval("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat);
444 print '</td></tr>';
445 }
446
447 // TVA
448 print '<tr><td class="titlefieldcreate">'.$langs->trans("DefaultTaxRate").'</td><td>';
449
450 $positiverates = '';
451 if (price2num($object->tva_tx)) {
452 $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx);
453 }
454 if (price2num($object->localtax1_type)) {
455 $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx);
456 }
457 if (price2num($object->localtax2_type)) {
458 $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx);
459 }
460 if (empty($positiverates)) {
461 $positiverates = '0';
462 }
463 echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), true, $object->tva_npr);
464 /*
465 if ($object->default_vat_code)
466 {
467 print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
468 }
469 else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/
470 print '</td></tr>';
471
472 // Price
473 print '<tr><td>'.$langs->trans("SellingPrice").'</td><td>';
474 if ($object->price_base_type == 'TTC') {
475 print price($object->price_ttc).' '.$langs->trans($object->price_base_type);
476 } else {
477 print price($object->price).' '.$langs->trans($object->price_base_type);
478 }
479 print '</td></tr>';
480
481 // Price minimum
482 print '<tr><td>'.$langs->trans("MinPrice").'</td><td>';
483 if ($object->price_base_type == 'TTC') {
484 print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type);
485 } else {
486 print price($object->price_min).' '.$langs->trans($object->price_base_type);
487 }
488 print '</td></tr>';
489
490 // Weight
491 print '<tr><td>'.$langs->trans("Weight").'</td><td>';
492 if ($object->weight != '') {
493 print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units);
494 } else {
495 print '&nbsp;';
496 }
497 print "</td></tr>\n";
498
499 print "</table>\n";
500
501 print '</div>';
502 print '<div class="clearboth"></div>';
503
504 print dol_get_fiche_end();
505
506 $listofvariantselected = '';
507
508 // Create or edit a variant
509 if ($action == 'add' || ($action == 'edit')) {
510 if ($action == 'add') {
511 $title = $langs->trans('NewProductCombination');
512 // print dol_get_fiche_head();
513 $features = !empty($_SESSION['addvariant_'.$object->id]) ? $_SESSION['addvariant_'.$object->id] : array();
514 //First, sanitize
515 $listofvariantselected = '<div id="parttoaddvariant">';
516 if (!empty($features)) {
517 $toprint = array();
518 foreach ($features as $feature) {
519 $explode = explode('-', $feature);
520 if ($prodattr->fetch($explode[0]) <= 0 || $prodattr_val->fetch($explode[1]) <= 0) {
521 continue;
522 }
523 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #ddd;">' . $prodattr->label.' : '.$prodattr_val->value .
524 ' <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create&subaction=delete&feature='.urlencode($feature).'">' . img_delete() . '</a></li>';
525 }
526 $listofvariantselected .= '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
527 }
528 $listofvariantselected .= '</div>';
529 //print dol_get_fiche_end();
530 } else {
531 $title = $langs->trans('EditProductCombination');
532 }
533
534 if ($action == 'add') {
535 $prodattr_all = $prodattr->fetchAll();
536
537 if (!$selected) {
538 $selected = $prodattr_all[key($prodattr_all)]->id;
539 }
540
541 $prodattr_alljson = array();
542
543 foreach ($prodattr_all as $each) {
544 $prodattr_alljson[$each->id] = $each;
545 } ?>
546
547 <script type="text/javascript">
548
549 variants_available = <?php echo json_encode($prodattr_alljson, JSON_PARTIAL_OUTPUT_ON_ERROR); ?>;
550 variants_selected = {
551 index: [],
552 info: []
553 };
554
555 <?php
556 foreach ($productCombination2ValuePairs1 as $pc2v) {
557 $prodattr_val->fetch($pc2v->fk_prod_attr_val); ?>
558 variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
559 variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
560 attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
561 value: {
562 id: <?php echo $pc2v->fk_prod_attr_val ?>,
563 label: '<?php echo $prodattr_val->value ?>'
564 }
565 };
566 <?php
567 } ?>
568
569 restoreAttributes = function() {
570 jQuery("select[name=attribute]").empty().append('<option value="-1">&nbsp;</option>');
571
572 jQuery.each(variants_available, function (key, val) {
573 if (jQuery.inArray(val.id, variants_selected.index) == -1) {
574 jQuery("select[name=attribute]").append('<option value="' + val.id + '">' + val.label + '</option>');
575 }
576 });
577 };
578
579
580 jQuery(document).ready(function() {
581 jQuery("select#attribute").change(function () {
582 console.log("Change of field variant attribute");
583 var select = jQuery("select#value");
584
585 if (!jQuery(this).val().length || jQuery(this).val() == '-1') {
586 select.empty();
587 select.append('<option value="-1">&nbsp;</option>');
588 return;
589 }
590
591 select.empty().append('<option value="">Loading...</option>');
592
593 jQuery.getJSON("ajax/get_attribute_values.php", {
594 id: jQuery(this).val()
595 }, function(data) {
596 if (data.error) {
597 select.empty();
598 select.append('<option value="-1">&nbsp;</option>');
599 return alert(data.error);
600 }
601
602 select.empty();
603 select.append('<option value="-1">&nbsp;</option>');
604
605 jQuery(data).each(function (key, val) {
606 keyforoption = val.id
607 valforoption = val.value
608 select.append('<option value="' + keyforoption + '">' + valforoption + '</option>');
609 });
610 });
611 });
612 });
613 </script>
614
615 <?php
616 }
617
618 print '<br>';
619
620 print load_fiche_titre($title);
621
622 print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
623 print '<input type="hidden" name="token" value="'.newToken().'">';
624 print '<input type="hidden" name="action" value="'.(($combination_id > 0) ? "update" : "create").'">'."\n";
625 if ($combination_id > 0) {
626 print '<input type="hidden" name="combination_id" value="'.$combination_id.'">'."\n";
627 }
628
629 print dol_get_fiche_head();
630
631
632 if ($action == 'add') {
633 print '<table class="border" style="width: 100%">';
634 print "<!-- Variant -->\n";
635 print '<tr>';
636 print '<td class="titlefieldcreate fieldrequired"><label for="attribute">'.$langs->trans('ProductAttribute').'</label></td>';
637 print '<td>';
638 if (is_array($prodattr_all)) {
639 print '<select class="flat minwidth100" id="attribute" name="attribute">';
640 print '<option value="-1">&nbsp;</option>';
641 foreach ($prodattr_all as $attr) {
642 //print '<option value="'.$attr->id.'"'.($attr->id == GETPOST('attribute', 'int') ? ' selected="selected"' : '').'>'.$attr->label.'</option>';
643 print '<option value="'.$attr->id.'">'.$attr->label.'</option>';
644 }
645 print '</select>';
646 }
647
648 $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
649 print $form->textwithpicto('', $htmltext);
650 /*print ' &nbsp; &nbsp; <a href="'.DOL_URL_ROOT.'/variants/create.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=add&token='.newToken().'&id='.$object->id).'">';
651 print $langs->trans("Create");
652 print '</a>';*/
653
654 print '</td>';
655 print '</tr>'; ?>
656 <!-- Value -->
657 <tr>
658 <td class="fieldrequired"><label for="value"><?php echo $langs->trans('Value') ?></label></td>
659 <td>
660 <select class="flat minwidth100" id="value" name="value">
661 <option value="-1">&nbsp;</option>
662 </select>
663 <?php
664 $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
665 print $form->textwithpicto('', $htmltext);
666 /*
667 print ' &nbsp; &nbsp; <a href="'.DOL_URL_ROOT.'/variants/create.php?action=create&backtopage='.urlencode($_SERVER["PHP_SELF"].'?action=add&token='.newToken().'&id='.$object->id).'">';
668 print $langs->trans("Create");
669 print '</a>';
670 */ ?>
671 </td>
672 </tr>
673 <tr>
674 <td></td><td>
675 <input type="submit" class="button" name="selectvariant" id="selectvariant" value="<?php echo dol_escape_htmltag($langs->trans("SelectCombination")); ?>">
676 </td>
677 </tr>
678 <?php
679 print '<tr><td></td><td>';
680 print $listofvariantselected;
681 print '</td>';
682 print '</tr>';
683
684 print '</table>';
685 print '<hr>';
686 }
687
688 if (is_array($productCombination2ValuePairs1)) {
689 print '<table class="border" style="width: 100%">';
690
691 // When in edit mode
692 if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
693 ?>
694 <tr>
695 <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Attributes') ?></label></td>
696 <td class="tdtop">
697 <div class="inline-block valignmiddle quatrevingtpercent">
698 <?php
699 foreach ($productCombination2ValuePairs1 as $pc2v) {
700 $result1 = $prodattr->fetch($pc2v->fk_prod_attr);
701 $result2 = $prodattr_val->fetch($pc2v->fk_prod_attr_val);
702 if ($result1 > 0 && $result2 > 0) {
703 print $prodattr->label.' : '.$prodattr_val->value.'<br>';
704 // TODO Add delete link
705 }
706 } ?>
707 </div>
708 <!-- <div class="inline-block valignmiddle">
709 <a href="#" class="inline-block valignmiddle button" id="delfeature"><?php echo img_edit_remove() ?></a>
710 </div>-->
711 </td>
712 <td>
713 </td>
714 </tr>
715 <?php
716 } ?>
717 <tr>
718 <td><label for="reference"><?php echo $langs->trans('Reference') ?></label></td>
719 <td><input type="text" id="reference" name="reference" value="<?php echo trim($reference) ?>"></td>
720 </tr>
721 <?php
722 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
723 ?>
724 <tr>
725 <td><label for="price_impact"><?php echo $langs->trans('PriceImpact') ?></label></td>
726 <td><input type="text" id="price_impact" name="price_impact" value="<?php echo price($price_impact) ?>">
727
728 <input type="checkbox" id="price_impact_percent" name="price_impact_percent" <?php echo ($price_impact_percent ? ' checked' : '') ?>> <label for="price_impact_percent"><?php echo $langs->trans('PercentageVariation') ?></label>
729 </td>
730 </tr>
731 <?php
732 } else {
733 $prodcomb->fetchCombinationPriceLevels();
734
735 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
736 for ($i = 1; $i <= $maxi; $i++) {
737 $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i;
738 $text = $langs->trans('ImpactOnPriceLevel', $i).' - '.getDolGlobalString($keyforlabel);
739 print '<tr>';
740 print '<td><label for="level_price_impact_'.$i.'">'.$text.'</label>';
741 if ($i === 1) {
742 print '<br/><a id="apply-price-impact-to-all-level" class="classfortooltip" href="#" title="'.$langs->trans('ApplyToAllPriceImpactLevelHelp').'">('.$langs->trans('ApplyToAllPriceImpactLevel').')</a>';
743 }
744 print '</td>';
745 print '<td><input type="text" class="level_price_impact" id="level_price_impact_'.$i.'" name="level_price_impact['.$i.']" value="'.price($prodcomb->combination_price_levels[$i]->variation_price).'">';
746 print '<input type="checkbox" class="level_price_impact_percent" id="level_price_impact_percent_'.$i.'" name="level_price_impact_percent['.$i.']" '.($prodcomb->combination_price_levels[$i]->variation_price_percentage ? ' checked' : '').'> <label for="level_price_impact_percent_'.$i.'">'.$langs->trans('PercentageVariation').'</label>';
747
748 print '</td>';
749 print '</tr>';
750 }
751 }
752
753 if ($object->isProduct()) {
754 print '<tr>';
755 print '<td><label for="weight_impact">'.$langs->trans('WeightImpact').'</label></td>';
756 print '<td><input type="text" id="weight_impact" name="weight_impact" value="'.price($weight_impact).'"></td>';
757 print '</tr>';
758 }
759
760 print '</table>';
761 }
762
763 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
764 ?>
765 <script>
766 $(document).ready(function() {
767 // Apply level 1 impact to all prices impact levels
768 $('body').on('click', '#apply-price-impact-to-all-level', function(e) {
769 e.preventDefault();
770 let priceImpact = $( "#level_price_impact_1" ).val();
771 let priceImpactPrecent = $( "#level_price_impact_percent_1" ).prop("checked");
772
773 let multipricelimit = <?php print getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT'); ?>
774
775 for (let i = 2; i <= multipricelimit; i++) {
776 $( "#level_price_impact_" + i ).val(priceImpact);
777 $( "#level_price_impact_percent_" + i ).prop("checked", priceImpactPrecent);
778 }
779 });
780 });
781 </script>
782 <?php
783 }
784
785 print dol_get_fiche_end(); ?>
786
787 <div style="text-align: center">
788 <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
789 print ' disabled="disabled"';
790 } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
791 &nbsp;
792 <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
793 </div>
794
795 <?php
796
797 print '</form>';
798 } else {
799 if ($action === 'delete') {
800 if ($prodcomb->fetch($combination_id) > 0) {
801 $prodstatic->fetch($prodcomb->fk_product_child);
802
803 print $form->formconfirm(
804 "combinations.php?id=".urlencode((string) ($id))."&combination_id=".urlencode((string) ($combination_id)),
805 $langs->trans('Delete'),
806 $langs->trans('ProductCombinationDeleteDialog', $prodstatic->ref),
807 "confirm_deletecombination",
808 array(array('label' => $langs->trans('DeleteLinkedProduct'), 'type' => 'checkbox', 'name' => 'delete_product', 'value' => false)),
809 0,
810 1
811 );
812 }
813 } elseif ($action === 'copy') {
814 print $form->formconfirm('combinations.php?id='.$id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneProductCombinations'), 'confirm_copycombination', array(array('type' => 'text', 'label' => $langs->trans('CloneDestinationReference'), 'name' => 'dest_product')), 0, 1);
815 }
816
817 $comb2val = new ProductCombination2ValuePair($db);
818
819 if ($productCombinations) {
820 ?>
821
822 <script type="text/javascript">
823 jQuery(document).ready(function() {
824
825 jQuery('input[name="select_all"]').click(function() {
826
827 if (jQuery(this).prop('checked')) {
828 var checked = true;
829 } else {
830 var checked = false;
831 }
832
833 jQuery('table.liste input[type="checkbox"]').prop('checked', checked);
834 });
835
836 jQuery('input[name^="select["]').click(function() {
837 jQuery('input[name="select_all"]').prop('checked', false);
838 });
839
840 });
841 </script>
842
843 <?php
844 }
845
846 // Buttons
847 print '<div class="tabsAction">';
848
849 print ' <div class="inline-block divButAction">';
850
851 print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
852
853 if ($productCombinations) {
854 print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
855 }
856
857 print ' </div>';
858
859 print '</div>';
860
861
862
863 $arrayofselected = is_array($toselect) ? $toselect : array();
864
865
866 // List of variants
867 print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
868 print '<input type="hidden" name="token" value="'.newToken().'">';
869 print '<input type="hidden" name="action" value="massaction">';
870 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
871
872 // List of mass actions available
873
874 $aaa = '';
875 if (count($productCombinations)) {
876 $aaa = '<select id="bulk_action" name="massaction" class="flat">';
877 $aaa .= ' <option value="nothing">&nbsp;</option>';
878 $aaa .= ' <option value="not_buy" data-html="'.dol_escape_htmltag(img_picto($langs->trans("SetToStatus"), 'stop-circle', 'class="pictofixedwidth"').$langs->trans('SetToStatus', $langs->transnoentitiesnoconv('ProductStatusNotOnBuy'))).'">'.$langs->trans('ProductStatusNotOnBuy').'</option>';
879 $aaa .= ' <option value="not_sell" data-html="'.dol_escape_htmltag(img_picto($langs->trans("SetToStatus"), 'stop-circle', 'class="pictofixedwidth"').$langs->trans('SetToStatus', $langs->transnoentitiesnoconv('ProductStatusNotOnSell'))).'">'.$langs->trans('ProductStatusNotOnSell').'</option>';
880 $aaa .= ' <option value="on_buy" data-html="'.dol_escape_htmltag(img_picto($langs->trans("SetToStatus"), 'stop-circle', 'class="pictofixedwidth"').$langs->trans('SetToStatus', $langs->transnoentitiesnoconv('ProductStatusOnBuy'))).'">'.$langs->trans('ProductStatusOnBuy').'</option>';
881 $aaa .= ' <option value="on_sell" data-html="'.dol_escape_htmltag(img_picto($langs->trans("SetToStatus"), 'stop-circle', 'class="pictofixedwidth"').$langs->trans('SetToStatus', $langs->transnoentitiesnoconv('ProductStatusOnSell'))).'">'.$langs->trans('ProductStatusOnSell').'</option>';
882 $aaa .= ' <option value="delete" data-html="'.dol_escape_htmltag(img_picto($langs->trans("Delete"), 'delete', 'class="pictofixedwidth"').$langs->trans('Delete')).'">'.$langs->trans('Delete').'</option>';
883 $aaa .= '</select>';
884 $aaa .= ajax_combobox("bulk_action");
885 $aaa .= '<input type="submit" value="'.dol_escape_htmltag($langs->trans("Apply")).'" class="button small">';
886 }
887 $massactionbutton = $aaa;
888
889 $title = $langs->trans("ProductCombinations");
890
891 print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $aaa, 0);
892
893 print '<div class="div-table-responsive">'; ?>
894 <table class="liste">
895 <tr class="liste_titre">
896 <?php
897 // Action column
898 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
899 print '<td class="liste_titre center">';
900 $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
901 print $searchpicto;
902 print '</td>';
903 } ?>
904 <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
905 <td class="liste_titre"><?php echo $langs->trans('Attributes') ?></td>
906 <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
907 <?php if ($object->isProduct()) {
908 print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
909 } ?>
910 <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
911 <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
912 <td class="liste_titre"></td>
913 <?php
914 // Action column
915 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
916 print '<td class="liste_titre center">';
917 $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
918 print $searchpicto;
919 print '</td>';
920 } ?>
921 </tr>
922 <?php
923
924 if (count($productCombinations)) {
925 foreach ($productCombinations as $currcomb) {
926 $prodstatic->fetch($currcomb->fk_product_child);
927 print '<tr class="oddeven">';
928
929 // Action column
930 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
931 print '<td class="nowrap center">';
932 if (!empty($productCombinations) || $massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
933 $selected = 0;
934 if (in_array($prodstatic->id, $arrayofselected)) {
935 $selected = 1;
936 }
937 print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
938 }
939 print '</td>';
940 }
941
942 print '<td>'.$prodstatic->getNomUrl(1).'</td>';
943 print '<td>';
944 foreach ($comb2val->fetchByFkCombination($currcomb->id) as $pc2v) {
945 print dol_htmlentities($pc2v).'<br>';
946 }
947 print '</td>';
948 print '<td class="right">'.($currcomb->variation_price >= 0 ? '+' : '').price($currcomb->variation_price).($currcomb->variation_price_percentage ? ' %' : '').'</td>';
949 if ($object->isProduct()) {
950 print '<td class="right">'.($currcomb->variation_weight >= 0 ? '+' : '').price($currcomb->variation_weight).' '.measuringUnitString(0, 'weight', $prodstatic->weight_units).'</td>';
951 }
952 print '<td class="center">'.$prodstatic->getLibStatut(2, 0).'</td>';
953 print '<td class="center">'.$prodstatic->getLibStatut(2, 1).'</td>';
954
955 print '<td class="right">';
956 print '<a class="paddingleft paddingright editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=edit&token='.newToken().'&combination_id='.$currcomb->id.'">'.img_edit().'</a>';
957 print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&combination_id='.$currcomb->id.'">'.img_delete().'</a>';
958 print '</td>';
959
960 // Action column
961 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
962 print '<td class="nowrap center">';
963 if (!empty($productCombinations) || $massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined
964 $selected = 0;
965 if (in_array($prodstatic->id, $arrayofselected)) {
966 $selected = 1;
967 }
968 print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
969 }
970 print '</td>';
971 }
972
973 print '</tr>';
974 }
975 } else {
976 print '<tr><td colspan="8"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
977 }
978 print '</table>';
979 print '</div>';
980 print '</form>';
981 }
982}
983
984// End of page
985llxFooter();
986$db->close();
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
ajax_combobox($htmlname, $events=array(), $minLengthToAutocomplete=0, $forcefocus=0, $widthTypeOfAutocomplete='resolve', $idforemptyvalue='-1', $morecss='')
Convert a html select field into an ajax combobox.
Definition ajax.lib.php:459
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:87
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:71
Class to manage generation of HTML components Only common components must be here.
Class ProductAttribute Used to represent a Product attribute Examples:
Class ProductAttributeValue Used to represent a product attribute value.
Class ProductCombination2ValuePair Used to represent the relation between a variant and its attribute...
Class ProductCombination Used to represent the relation between a product and one of its variants.
Class ProductCombinationLevel Used to represent a product combination Level.
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.
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.
print_barre_liste($title, $page, $file, $options='', $sortfield='', $sortorder='', $morehtmlcenter='', $num=-1, $totalnboflines='', $picto='generic', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limit=-1, $selectlimitsuffix=0, $hidenavigation=0, $pagenavastextinput=0, $morehtmlrightbeforearrow='')
Print a title with navigation controls for pagination.
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
img_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2)
Show picto whatever it's its name (generic function)
GETPOSTINT($paramname, $method=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
dol_get_fiche_head($links=array(), $active='', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='', $limittoshow=0, $moretabssuffix='', $dragdropfile=0)
Show tabs of a record.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
dol_get_fiche_end($notab=0)
Return tab footer of a card.
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.
newToken()
Return the value of token currently saved into session with name 'newtoken'.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
GETPOSTFLOAT($paramname, $rounding='')
Return the value of a $_GET or $_POST supervariable, converted into float.
dol_buildpath($path, $type=0, $returnemptyifnotfound=0)
Return path of url or filesystem.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
img_edit($titlealt='default', $float=0, $other='')
Show logo edit/modify fiche.
img_edit_remove($titlealt='default', $other='')
Show logo -.
treeview li table
No Email.
product_prepare_head($object)
Prepare array with list of tabs.
measuringUnitString($unitid, $measuring_style='', $unitscale='', $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
if(preg_match('/crypted:/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:149
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:152
restrictedArea(User $user, $features, $object=0, $tableandshare='', $feature2='', $dbt_keyfield='fk_soc', $dbt_select='rowid', $isdraft=0, $mode=0)
Check permissions of a user to show a page and an object.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0, $params=null)
Show a message to say access is forbidden and stop program.