dolibarr 22.0.5
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-2025 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((int) $explode[0]) <= 0 || $prodattr_val->fetch((int) $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, (float) $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-suppress-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 = "(te.fk_product_type:=:".((int) $object->type).")";
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', (string) $object->type, $object, (int) $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((int) $explode[0]) <= 0 || $prodattr_val->fetch((int) $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 $prodattr_alljson = null;
535 $prodattr_all = null;
536 if ($action == 'add') {
537 $prodattr_all = $prodattr->fetchAll();
538
539 if (!$selected && !empty($prodattr_all)) {
540 $selected = $prodattr_all[key($prodattr_all)]->id;
541 }
542
543 $prodattr_alljson = array();
544
545 foreach ($prodattr_all as $each) {
546 $prodattr_alljson[$each->id] = $each;
547 } ?>
548
549 <script type="text/javascript">
550
551 variants_available = <?php echo json_encode($prodattr_alljson, JSON_PARTIAL_OUTPUT_ON_ERROR); ?>;
552 variants_selected = {
553 index: [],
554 info: []
555 };
556
557 <?php
558 foreach ($productCombination2ValuePairs1 as $pc2v) {
559 $prodattr_val->fetch($pc2v->fk_prod_attr_val); ?>
560 variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
561 variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
562 attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
563 value: {
564 id: <?php echo $pc2v->fk_prod_attr_val ?>,
565 label: '<?php echo $prodattr_val->value ?>'
566 }
567 };
568 <?php
569 } ?>
570
571 restoreAttributes = function() {
572 jQuery("select[name=attribute]").empty().append('<option value="-1">&nbsp;</option>');
573
574 jQuery.each(variants_available, function (key, val) {
575 if (jQuery.inArray(val.id, variants_selected.index) == -1) {
576 jQuery("select[name=attribute]").append('<option value="' + val.id + '">' + val.label + '</option>');
577 }
578 });
579 };
580
581
582 jQuery(document).ready(function() {
583 jQuery("select#attribute").change(function () {
584 console.log("Change of field variant attribute");
585 var select = jQuery("select#value");
586
587 if (!jQuery(this).val().length || jQuery(this).val() == '-1') {
588 select.empty();
589 select.append('<option value="-1">&nbsp;</option>');
590 return;
591 }
592
593 select.empty().append('<option value="">Loading...</option>');
594
595 jQuery.getJSON("ajax/get_attribute_values.php", {
596 id: jQuery(this).val()
597 }, function(data) {
598 if (data.error) {
599 select.empty();
600 select.append('<option value="-1">&nbsp;</option>');
601 return alert(data.error);
602 }
603
604 select.empty();
605 select.append('<option value="-1">&nbsp;</option>');
606
607 jQuery(data).each(function (key, val) {
608 keyforoption = val.id
609 valforoption = val.value
610 select.append('<option value="' + keyforoption + '">' + valforoption + '</option>');
611 });
612 });
613 });
614 });
615 </script>
616
617 <?php
618 }
619
620 print '<br>';
621
622 print load_fiche_titre($title);
623
624 print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
625 print '<input type="hidden" name="token" value="'.newToken().'">';
626 print '<input type="hidden" name="action" value="'.(($combination_id > 0) ? "update" : "create").'">'."\n";
627 if ($combination_id > 0) {
628 print '<input type="hidden" name="combination_id" value="'.$combination_id.'">'."\n";
629 }
630
631 print dol_get_fiche_head();
632
633
634 if ($action == 'add') {
635 print '<table class="border" style="width: 100%">';
636 print "<!-- Variant -->\n";
637 print '<tr>';
638 print '<td class="titlefieldcreate fieldrequired"><label for="attribute">'.$langs->trans('ProductAttribute').'</label></td>';
639 print '<td>';
640 if (is_array($prodattr_all)) {
641 print '<select class="flat minwidth100" id="attribute" name="attribute">';
642 print '<option value="-1">&nbsp;</option>';
643 foreach ($prodattr_all as $attr) {
644 //print '<option value="'.$attr->id.'"'.($attr->id == GETPOST('attribute', 'int') ? ' selected="selected"' : '').'>'.$attr->label.'</option>';
645 print '<option value="'.$attr->id.'">'.$attr->label.'</option>';
646 }
647 print '</select>';
648 }
649
650 $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
651 print $form->textwithpicto('', $htmltext);
652 /*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).'">';
653 print $langs->trans("Create");
654 print '</a>';*/
655
656 print '</td>';
657 print '</tr>'; ?>
658 <!-- Value -->
659 <tr>
660 <td class="fieldrequired"><label for="value"><?php echo $langs->trans('Value') ?></label></td>
661 <td>
662 <select class="flat minwidth100" id="value" name="value">
663 <option value="-1">&nbsp;</option>
664 </select>
665 <?php
666 $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
667 print $form->textwithpicto('', $htmltext);
668 /*
669 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).'">';
670 print $langs->trans("Create");
671 print '</a>';
672 */ ?>
673 </td>
674 </tr>
675 <tr>
676 <td></td><td>
677 <input type="submit" class="button" name="selectvariant" id="selectvariant" value="<?php echo dol_escape_htmltag($langs->trans("SelectCombination")); ?>">
678 </td>
679 </tr>
680 <?php
681 print '<tr><td></td><td>';
682 print $listofvariantselected;
683 print '</td>';
684 print '</tr>';
685
686 print '</table>';
687 print '<hr>';
688 }
689
690 if (is_array($productCombination2ValuePairs1)) {
691 print '<table class="border" style="width: 100%">';
692
693 // When in edit mode
694 if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
695 ?>
696 <tr>
697 <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Attributes') ?></label></td>
698 <td class="tdtop">
699 <div class="inline-block valignmiddle quatrevingtpercent">
700 <?php
701 foreach ($productCombination2ValuePairs1 as $pc2v) {
702 $result1 = $prodattr->fetch($pc2v->fk_prod_attr);
703 $result2 = $prodattr_val->fetch($pc2v->fk_prod_attr_val);
704 if ($result1 > 0 && $result2 > 0) {
705 print $prodattr->label.' : '.$prodattr_val->value.'<br>';
706 // TODO Add delete link
707 }
708 } ?>
709 </div>
710 <!-- <div class="inline-block valignmiddle">
711 <a href="#" class="inline-block valignmiddle button" id="delfeature"><?php echo img_edit_remove() ?></a>
712 </div>-->
713 </td>
714 <td>
715 </td>
716 </tr>
717 <?php
718 } ?>
719 <tr>
720 <td><label for="reference"><?php echo $langs->trans('Reference') ?></label></td>
721 <td><input type="text" id="reference" name="reference" value="<?php echo trim($reference) ?>"></td>
722 </tr>
723 <?php
724 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
725 ?>
726 <tr>
727 <td><label for="price_impact"><?php echo $langs->trans('PriceImpact') ?></label></td>
728 <td><input type="text" id="price_impact" name="price_impact" value="<?php echo price($price_impact) ?>">
729
730 <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>
731 </td>
732 </tr>
733 <?php
734 } else {
735 $prodcomb->fetchCombinationPriceLevels();
736
737 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
738 for ($i = 1; $i <= $maxi; $i++) {
739 $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i;
740 $text = $langs->trans('ImpactOnPriceLevel', $i).' - '.getDolGlobalString($keyforlabel);
741 print '<tr>';
742 print '<td><label for="level_price_impact_'.$i.'">'.$text.'</label>';
743 if ($i === 1) {
744 print '<br/><a id="apply-price-impact-to-all-level" class="classfortooltip" href="#" title="'.$langs->trans('ApplyToAllPriceImpactLevelHelp').'">('.$langs->trans('ApplyToAllPriceImpactLevel').')</a>';
745 }
746 print '</td>';
747 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).'">';
748 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>';
749
750 print '</td>';
751 print '</tr>';
752 }
753 }
754
755 if ($object->isProduct()) {
756 print '<tr>';
757 print '<td><label for="weight_impact">'.$langs->trans('WeightImpact').'</label></td>';
758 print '<td><input type="text" id="weight_impact" name="weight_impact" value="'.price($weight_impact).'"></td>';
759 print '</tr>';
760 }
761
762 print '</table>';
763 }
764
765 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
766 ?>
767 <script>
768 $(document).ready(function() {
769 // Apply level 1 impact to all prices impact levels
770 $('body').on('click', '#apply-price-impact-to-all-level', function(e) {
771 e.preventDefault();
772 let priceImpact = $( "#level_price_impact_1" ).val();
773 let priceImpactPrecent = $( "#level_price_impact_percent_1" ).prop("checked");
774
775 let multipricelimit = <?php print getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT'); ?>
776
777 for (let i = 2; i <= multipricelimit; i++) {
778 $( "#level_price_impact_" + i ).val(priceImpact);
779 $( "#level_price_impact_percent_" + i ).prop("checked", priceImpactPrecent);
780 }
781 });
782 });
783 </script>
784 <?php
785 }
786
787 print dol_get_fiche_end(); ?>
788
789 <div style="text-align: center">
790 <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
791 print ' disabled="disabled"';
792 } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
793 &nbsp;
794 <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
795 </div>
796
797 <?php
798
799 print '</form>';
800 } else {
801 if ($action === 'delete') {
802 if ($prodcomb->fetch($combination_id) > 0) {
803 $prodstatic->fetch($prodcomb->fk_product_child);
804
805 print $form->formconfirm(
806 "combinations.php?id=".urlencode((string) ($id))."&combination_id=".urlencode((string) ($combination_id)),
807 $langs->trans('Delete'),
808 $langs->trans('ProductCombinationDeleteDialog', $prodstatic->ref),
809 "confirm_deletecombination",
810 array(array('label' => $langs->trans('DeleteLinkedProduct'), 'type' => 'checkbox', 'name' => 'delete_product', 'value' => false)),
811 0,
812 1
813 );
814 }
815 } elseif ($action === 'copy') {
816 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);
817 }
818
819 $comb2val = new ProductCombination2ValuePair($db);
820
821 if ($productCombinations) {
822 ?>
823
824 <script type="text/javascript">
825 jQuery(document).ready(function() {
826
827 jQuery('input[name="select_all"]').click(function() {
828
829 if (jQuery(this).prop('checked')) {
830 var checked = true;
831 } else {
832 var checked = false;
833 }
834
835 jQuery('table.liste input[type="checkbox"]').prop('checked', checked);
836 });
837
838 jQuery('input[name^="select["]').click(function() {
839 jQuery('input[name="select_all"]').prop('checked', false);
840 });
841
842 });
843 </script>
844
845 <?php
846 }
847
848 // Buttons
849 print '<div class="tabsAction">';
850
851 print ' <div class="inline-block divButAction">';
852
853 print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
854
855 if ($productCombinations) {
856 print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
857 }
858
859 print ' </div>';
860
861 print '</div>';
862
863
864
865 $arrayofselected = is_array($toselect) ? $toselect : array();
866
867
868 // List of variants
869 print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
870 print '<input type="hidden" name="token" value="'.newToken().'">';
871 print '<input type="hidden" name="action" value="massaction">';
872 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
873
874 // List of mass actions available
875
876 $aaa = '';
877 if (count($productCombinations)) {
878 $aaa = '<select id="bulk_action" name="massaction" class="flat">';
879 $aaa .= ' <option value="nothing">&nbsp;</option>';
880 $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>';
881 $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>';
882 $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>';
883 $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>';
884 $aaa .= ' <option value="delete" data-html="'.dol_escape_htmltag(img_picto($langs->trans("Delete"), 'delete', 'class="pictofixedwidth"').$langs->trans('Delete')).'">'.$langs->trans('Delete').'</option>';
885 $aaa .= '</select>';
886 $aaa .= ajax_combobox("bulk_action");
887 $aaa .= '<input type="submit" value="'.dol_escape_htmltag($langs->trans("Apply")).'" class="button small">';
888 }
889 $massactionbutton = $aaa;
890
891 $title = $langs->trans("ProductCombinations");
892
893 print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $aaa, 0);
894
895 print '<div class="div-table-responsive">'; ?>
896 <table class="liste">
897 <tr class="liste_titre">
898 <?php
899 // Action column
900 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
901 print '<td class="liste_titre center">';
902 $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
903 print $searchpicto;
904 print '</td>';
905 } ?>
906 <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
907 <td class="liste_titre"><?php echo $langs->trans('Attributes') ?></td>
908 <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
909 <?php if ($object->isProduct()) {
910 print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
911 } ?>
912 <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
913 <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
914 <td class="liste_titre"></td>
915 <?php
916 // Action column
917 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
918 print '<td class="liste_titre center">';
919 $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
920 print $searchpicto;
921 print '</td>';
922 } ?>
923 </tr>
924 <?php
925
926 if (count($productCombinations)) {
927 foreach ($productCombinations as $currcomb) {
928 $prodstatic->fetch($currcomb->fk_product_child);
929 print '<tr class="oddeven">';
930
931 // Action column
932 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
933 print '<td class="nowrap center">';
934 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
935 $selected = 0;
936 if (in_array($prodstatic->id, $arrayofselected)) {
937 $selected = 1;
938 }
939 print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
940 }
941 print '</td>';
942 }
943
944 print '<td>'.$prodstatic->getNomUrl(1).'</td>';
945 print '<td>';
946 foreach ($comb2val->fetchByFkCombination($currcomb->id) as $pc2v) {
947 print dol_htmlentities($pc2v).'<br>';
948 }
949 print '</td>';
950 print '<td class="right">'.($currcomb->variation_price >= 0 ? '+' : '').price($currcomb->variation_price).($currcomb->variation_price_percentage ? ' %' : '').'</td>';
951 if ($object->isProduct()) {
952 print '<td class="right">'.($currcomb->variation_weight >= 0 ? '+' : '').price($currcomb->variation_weight).' '.measuringUnitString(0, 'weight', $prodstatic->weight_units).'</td>';
953 }
954 print '<td class="center">'.$prodstatic->getLibStatut(2, 0).'</td>';
955 print '<td class="center">'.$prodstatic->getLibStatut(2, 1).'</td>';
956
957 print '<td class="right">';
958 print '<a class="paddingleft paddingright editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=edit&token='.newToken().'&combination_id='.$currcomb->id.'">'.img_edit().'</a>';
959 print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&combination_id='.$currcomb->id.'">'.img_delete().'</a>';
960 print '</td>';
961
962 // Action column
963 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
964 print '<td class="nowrap center">';
965 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
966 $selected = 0;
967 if (in_array($prodstatic->id, $arrayofselected)) {
968 $selected = 1;
969 }
970 print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
971 }
972 print '</td>';
973 }
974
975 print '</tr>';
976 }
977 } else {
978 print '<tr><td colspan="8"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
979 }
980 print '</table>';
981 print '</div>';
982 print '</form>';
983 }
984}
985
986// End of page
987llxFooter();
988$db->close();
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:67
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:475
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 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_picto($titlealt, $picto, $moreatt='', $pictoisfullpath=0, $srconly=0, $notitle=0, $alt='', $morecss='', $marginleftonlyshort=2, $allowothertags=array())
Show picto whatever it's its name (generic function)
img_delete($titlealt='default', $other='class="pictodelete"', $morecss='')
Show delete logo.
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, $morecssdiv='')
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.
measuringUnitString($unitid, $measuring_style='', $unitscale=null, $use_short_label=0, $outputlangs=null)
Return translation label of a unit key.
product_prepare_head($object)
Prepare array with list of tabs.
if(preg_match('/(crypted|dolcrypt):/i', $dolibarr_main_db_pass)||!empty($dolibarr_main_db_encrypted_pass)) $conf db type
Definition repair.php:158
$conf db name
Only used if Module[ID]Name translation string is not found.
Definition repair.php:161
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.