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) && ($massaction == 'delete' ? $usercandelete : $usercancreate)) {
218 $bulkaction = $massaction;
219 $error = 0;
220
221 // The mass action can only target the variants of this product
222 $childids = array();
223 $tmpcombinations = $prodcomb->fetchAllByFkProductParent($object->id);
224 if (is_array($tmpcombinations)) {
225 foreach ($tmpcombinations as $tmpcombination) {
226 $childids[] = (int) $tmpcombination->fk_product_child;
227 }
228 }
229
230 $db->begin();
231
232 foreach ($toselect as $prodid) {
233 if (!in_array((int) $prodid, $childids)) {
234 continue;
235 }
236 // need create new of Product to prevent rename dir behavior
237 $prodstatic = new Product($db);
238 if ($prodstatic->fetch($prodid) < 0) {
239 continue;
240 }
241
242 if ($bulkaction == 'on_sell') {
243 $prodstatic->status = 1;
244 $res = $prodstatic->update($prodstatic->id, $user);
245 if ($res <= 0) {
246 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
247 $error++;
248 break;
249 }
250 } elseif ($bulkaction == 'on_buy') {
251 $prodstatic->status_buy = 1;
252 $res = $prodstatic->update($prodstatic->id, $user);
253 if ($res <= 0) {
254 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
255 $error++;
256 break;
257 }
258 } elseif ($bulkaction == 'not_sell') {
259 $prodstatic->status = 0;
260 $res = $prodstatic->update($prodstatic->id, $user);
261 if ($res <= 0) {
262 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
263 $error++;
264 break;
265 }
266 } elseif ($bulkaction == 'not_buy') {
267 $prodstatic->status_buy = 0;
268 $res = $prodstatic->update($prodstatic->id, $user);
269 if ($res <= 0) {
270 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
271 $error++;
272 break;
273 }
274 } elseif ($bulkaction == 'delete') {
275 $res = $prodstatic->delete($user, $prodstatic->id);
276 if ($res <= 0) {
277 setEventMessages($prodstatic->error, $prodstatic->errors, 'errors');
278 $error++;
279 break;
280 }
281 } else {
282 break;
283 }
284 }
285
286 if ($error) {
287 $db->rollback();
288 if (empty($prodstatic->error)) {
289 setEventMessages($langs->trans('CoreErrorMessage'), null, 'errors');
290 }
291 } else {
292 $db->commit();
293 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
294 }
295} elseif ($action === 'update' && $combination_id > 0 && $usercancreate) {
296 if ($prodcomb->fetch($combination_id) < 0) {
297 dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
298 exit();
299 }
300
301 $prodcomb->variation_weight = (float) price2num($weight_impact);
302
303 // for conf PRODUIT_MULTIPRICES
304 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
305 $prodcomb->variation_price = $level_price_impact[1];
306 $prodcomb->variation_price_percentage = $level_price_impact_percent[1];
307 } else {
308 $level_price_impact = array(1 => $price_impact);
309 $level_price_impact_percent = array(1 => $price_impact_percent);
310
311 $prodcomb->variation_price = $price_impact;
312 $prodcomb->variation_price_percentage = $price_impact_percent;
313 }
314
315 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
316 $prodcomb->combination_price_levels = array();
317 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
318 for ($i = 1; $i <= $maxi; $i++) {
319 $productCombinationLevel = new ProductCombinationLevel($db);
320 $productCombinationLevel->fk_product_attribute_combination = $prodcomb->id;
321 $productCombinationLevel->fk_price_level = $i;
322 $productCombinationLevel->variation_price = (float) $level_price_impact[$i];
323 $productCombinationLevel->variation_price_percentage = (bool) $level_price_impact_percent[$i];
324 $prodcomb->combination_price_levels[$i] = $productCombinationLevel;
325 }
326 }
327
328 $error = 0;
329 $db->begin();
330
331 // Update product variant ref
332 $product_child = new Product($db);
333 $product_child->fetch($prodcomb->fk_product_child);
334 $product_child->oldcopy = clone $product_child; // @phan-suppress-current-line PhanTypeMismatchProperty
335 $product_child->ref = $reference;
336
337 $result = $product_child->update($product_child->id, $user);
338 if ($result < 0) {
339 setEventMessages($product_child->error, $product_child->errors, 'errors');
340 $error++;
341 }
342
343 if (!$error) {
344 // Update product variant infos
345 $result = $prodcomb->update($user);
346 if ($result < 0) {
347 setEventMessages($prodcomb->error, $prodcomb->errors, 'errors');
348 $error++;
349 }
350 }
351
352 if (!$error) {
353 $db->commit();
354 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
355 header('Location: ' . dol_buildpath('/variants/combinations.php?id=' . $id, 2));
356 exit();
357 } else {
358 $db->rollback();
359 }
360}
361
362
363// Reload variants
364$productCombinations = $prodcomb->fetchAllByFkProductParent($object->id, true);
365
366if ($action === 'confirm_deletecombination' && $usercancreate) {
367 if ($prodcomb->fetch($combination_id) > 0) {
368 $db->begin();
369
370 if ($prodcomb->delete($user) > 0 && (empty($delete_product) || ($delete_product == 'on' && $prodstatic->fetch($prodcomb->fk_product_child) > 0 && $prodstatic->delete($user) > 0))) {
371 $db->commit();
372 setEventMessages($langs->trans('RecordSaved'), null, 'mesgs');
373 header('Location: '.dol_buildpath('/variants/combinations.php?id='.$object->id, 2));
374 exit();
375 }
376
377 $db->rollback();
378 setEventMessages($langs->trans('ProductCombinationAlreadyUsed'), null, 'errors');
379 $action = '';
380 }
381} elseif ($action === 'edit' && $usercancreate) {
382 if ($prodcomb->fetch($combination_id) < 0) {
383 dol_print_error($db, $langs->trans('ErrorRecordNotFound'));
384 exit();
385 }
386
387 $product_child = new Product($db);
388 $product_child->fetch($prodcomb->fk_product_child);
389 $reference = $product_child->ref;
390 $weight_impact = $prodcomb->variation_weight;
391 $price_impact = $prodcomb->variation_price;
392 $price_impact_percent = $prodcomb->variation_price_percentage;
393
394 $productCombination2ValuePairs1 = $prodcomb2val->fetchByFkCombination($combination_id);
395} elseif ($action === 'confirm_copycombination' && $usercancreate) {
396 //Check destination product
397 $dest_product = GETPOST('dest_product');
398
399 if ($prodstatic->fetch(0, $dest_product) > 0) {
400 //To prevent from copying to the same product
401 if ($prodstatic->ref != $object->ref) {
402 if ($prodcomb->copyAll($user, $object->id, $prodstatic) > 0) {
403 header('Location: '.dol_buildpath('/variants/combinations.php?id='.$prodstatic->id, 2));
404 exit();
405 } else {
406 setEventMessages($langs->trans('ErrorCopyProductCombinations'), null, 'errors');
407 }
408 }
409 } else {
410 setEventMessages($langs->trans('ErrorDestinationProductNotFound'), null, 'errors');
411 }
412}
413
414
415
416/*
417 * View
418 */
419
420$form = new Form($db);
421
422$title = $langs->trans("Variant");
423
424llxHeader("", $title);
425
426
427if (!empty($id) || !empty($ref)) {
428 $showbarcode = isModEnabled('barcode');
429 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('barcode', 'lire_advance')) {
430 $showbarcode = 0;
431 }
432
433 $head = product_prepare_head($object);
434 $titre = $langs->trans("CardProduct".$object->type);
435 $picto = $object->isService() ? 'service' : 'product';
436
437 print dol_get_fiche_head($head, 'combinations', $titre, -1, $picto);
438
439 $linkback = '<a href="'.DOL_URL_ROOT.'/product/list.php?type='.((int) $object->type).'">'.$langs->trans("BackToList").'</a>';
440 $object->next_prev_filter = "(te.fk_product_type:=:".((int) $object->type).")";
441
442 dol_banner_tab($object, 'ref', $linkback, ($user->socid ? 0 : 1), 'ref', '', '', '', 0, '', '');
443
444 print '<div class="fichecenter">';
445
446 print '<div class="underbanner clearboth"></div>';
447 print '<table class="border centpercent tableforfield">';
448
449 // Type
450 if (isModEnabled("product") && isModEnabled("service")) {
451 $typeformat = 'select;0:'.$langs->trans("Product").',1:'.$langs->trans("Service");
452 print '<tr><td class="titlefieldcreate">';
453 print (!getDolGlobalString('PRODUCT_DENY_CHANGE_PRODUCT_TYPE')) ? $form->editfieldkey("Type", 'fk_product_type', (string) $object->type, $object, (int) $usercancreate, $typeformat) : $langs->trans('Type');
454 print '</td><td>';
455 print $form->editfieldval("Type", 'fk_product_type', $object->type, $object, $usercancreate, $typeformat);
456 print '</td></tr>';
457 }
458
459 // TVA
460 print '<tr><td class="titlefieldcreate">'.$langs->trans("DefaultTaxRate").'</td><td>';
461
462 $positiverates = '';
463 if (price2num($object->tva_tx)) {
464 $positiverates .= ($positiverates ? '/' : '').price2num($object->tva_tx);
465 }
466 if (price2num($object->localtax1_type)) {
467 $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax1_tx);
468 }
469 if (price2num($object->localtax2_type)) {
470 $positiverates .= ($positiverates ? '/' : '').price2num($object->localtax2_tx);
471 }
472 if (empty($positiverates)) {
473 $positiverates = '0';
474 }
475 echo vatrate($positiverates.($object->default_vat_code ? ' ('.$object->default_vat_code.')' : ''), true, $object->tva_npr);
476 /*
477 if ($object->default_vat_code)
478 {
479 print vatrate($object->tva_tx, true) . ' ('.$object->default_vat_code.')';
480 }
481 else print vatrate($object->tva_tx, true, $object->tva_npr, true);*/
482 print '</td></tr>';
483
484 // Price
485 print '<tr><td>'.$langs->trans("SellingPrice").'</td><td>';
486 if ($object->price_base_type == 'TTC') {
487 print price($object->price_ttc).' '.$langs->trans($object->price_base_type);
488 } else {
489 print price($object->price).' '.$langs->trans($object->price_base_type);
490 }
491 print '</td></tr>';
492
493 // Price minimum
494 print '<tr><td>'.$langs->trans("MinPrice").'</td><td>';
495 if ($object->price_base_type == 'TTC') {
496 print price($object->price_min_ttc).' '.$langs->trans($object->price_base_type);
497 } else {
498 print price($object->price_min).' '.$langs->trans($object->price_base_type);
499 }
500 print '</td></tr>';
501
502 // Weight
503 print '<tr><td>'.$langs->trans("Weight").'</td><td>';
504 if ($object->weight != '') {
505 print $object->weight." ".measuringUnitString(0, "weight", $object->weight_units);
506 } else {
507 print '&nbsp;';
508 }
509 print "</td></tr>\n";
510
511 print "</table>\n";
512
513 print '</div>';
514 print '<div class="clearboth"></div>';
515
516 print dol_get_fiche_end();
517
518 $listofvariantselected = '';
519
520 // Create or edit a variant
521 if ($action == 'add' || ($action == 'edit')) {
522 if ($action == 'add') {
523 $title = $langs->trans('NewProductCombination');
524 // print dol_get_fiche_head();
525 $features = !empty($_SESSION['addvariant_'.$object->id]) ? $_SESSION['addvariant_'.$object->id] : array();
526 //First, sanitize
527 $listofvariantselected = '<div id="parttoaddvariant">';
528 if (!empty($features)) {
529 $toprint = array();
530 foreach ($features as $feature) {
531 $explode = explode('-', $feature);
532 if ($prodattr->fetch((int) $explode[0]) <= 0 || $prodattr_val->fetch((int) $explode[1]) <= 0) {
533 continue;
534 }
535 $toprint[] = '<li class="select2-search-choice-dolibarr noborderoncategories" style="background: #ddd;">' . $prodattr->label.' : '.$prodattr_val->value .
536 ' <a class="reposition" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&action=create&subaction=delete&feature='.urlencode($feature).'">' . img_delete() . '</a></li>';
537 }
538 $listofvariantselected .= '<div class="select2-container-multi-dolibarr" style="width: 90%;"><ul class="select2-choices-dolibarr">' . implode(' ', $toprint) . '</ul></div>';
539 }
540 $listofvariantselected .= '</div>';
541 //print dol_get_fiche_end();
542 } else {
543 $title = $langs->trans('EditProductCombination');
544 }
545
546 $prodattr_alljson = null;
547 $prodattr_all = null;
548 if ($action == 'add') {
549 $prodattr_all = $prodattr->fetchAll();
550
551 if (!$selected && !empty($prodattr_all)) {
552 $selected = $prodattr_all[key($prodattr_all)]->id;
553 }
554
555 $prodattr_alljson = array();
556
557 foreach ($prodattr_all as $each) {
558 $prodattr_alljson[$each->id] = $each;
559 } ?>
560
561 <script type="text/javascript">
562
563 variants_available = <?php echo json_encode($prodattr_alljson, JSON_PARTIAL_OUTPUT_ON_ERROR); ?>;
564 variants_selected = {
565 index: [],
566 info: []
567 };
568
569 <?php
570 foreach ($productCombination2ValuePairs1 as $pc2v) {
571 $prodattr_val->fetch($pc2v->fk_prod_attr_val); ?>
572 variants_selected.index.push(<?php echo $pc2v->fk_prod_attr ?>);
573 variants_selected.info[<?php echo $pc2v->fk_prod_attr ?>] = {
574 attribute: variants_available[<?php echo $pc2v->fk_prod_attr ?>],
575 value: {
576 id: <?php echo $pc2v->fk_prod_attr_val ?>,
577 label: '<?php echo $prodattr_val->value ?>'
578 }
579 };
580 <?php
581 } ?>
582
583 restoreAttributes = function() {
584 jQuery("select[name=attribute]").empty().append('<option value="-1">&nbsp;</option>');
585
586 jQuery.each(variants_available, function (key, val) {
587 if (jQuery.inArray(val.id, variants_selected.index) == -1) {
588 jQuery("select[name=attribute]").append('<option value="' + val.id + '">' + val.label + '</option>');
589 }
590 });
591 };
592
593
594 jQuery(document).ready(function() {
595 jQuery("select#attribute").change(function () {
596 console.log("Change of field variant attribute");
597 var select = jQuery("select#value");
598
599 if (!jQuery(this).val().length || jQuery(this).val() == '-1') {
600 select.empty();
601 select.append('<option value="-1">&nbsp;</option>');
602 return;
603 }
604
605 select.empty().append('<option value="">Loading...</option>');
606
607 jQuery.getJSON("ajax/get_attribute_values.php", {
608 id: jQuery(this).val()
609 }, function(data) {
610 if (data.error) {
611 select.empty();
612 select.append('<option value="-1">&nbsp;</option>');
613 return alert(data.error);
614 }
615
616 select.empty();
617 select.append('<option value="-1">&nbsp;</option>');
618
619 jQuery(data).each(function (key, val) {
620 keyforoption = val.id
621 valforoption = val.value
622 select.append('<option value="' + keyforoption + '">' + valforoption + '</option>');
623 });
624 });
625 });
626 });
627 </script>
628
629 <?php
630 }
631
632 print '<br>';
633
634 print load_fiche_titre($title);
635
636 print '<form method="post" id="combinationform" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">'."\n";
637 print '<input type="hidden" name="token" value="'.newToken().'">';
638 print '<input type="hidden" name="action" value="'.(($combination_id > 0) ? "update" : "create").'">'."\n";
639 if ($combination_id > 0) {
640 print '<input type="hidden" name="combination_id" value="'.$combination_id.'">'."\n";
641 }
642
643 print dol_get_fiche_head();
644
645
646 if ($action == 'add') {
647 print '<table class="border" style="width: 100%">';
648 print "<!-- Variant -->\n";
649 print '<tr>';
650 print '<td class="titlefieldcreate fieldrequired"><label for="attribute">'.$langs->trans('ProductAttribute').'</label></td>';
651 print '<td>';
652 if (is_array($prodattr_all)) {
653 print '<select class="flat minwidth100" id="attribute" name="attribute">';
654 print '<option value="-1">&nbsp;</option>';
655 foreach ($prodattr_all as $attr) {
656 //print '<option value="'.$attr->id.'"'.($attr->id == GETPOST('attribute', 'int') ? ' selected="selected"' : '').'>'.$attr->label.'</option>';
657 print '<option value="'.$attr->id.'">'.$attr->label.'</option>';
658 }
659 print '</select>';
660 }
661
662 $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
663 print $form->textwithpicto('', $htmltext);
664 /*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).'">';
665 print $langs->trans("Create");
666 print '</a>';*/
667
668 print '</td>';
669 print '</tr>'; ?>
670 <!-- Value -->
671 <tr>
672 <td class="fieldrequired"><label for="value"><?php echo $langs->trans('Value') ?></label></td>
673 <td>
674 <select class="flat minwidth100" id="value" name="value">
675 <option value="-1">&nbsp;</option>
676 </select>
677 <?php
678 $htmltext = $langs->trans("GoOnMenuToCreateVairants", $langs->transnoentities("Product"), $langs->transnoentities("VariantAttributes"));
679 print $form->textwithpicto('', $htmltext);
680 /*
681 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).'">';
682 print $langs->trans("Create");
683 print '</a>';
684 */ ?>
685 </td>
686 </tr>
687 <tr>
688 <td></td><td>
689 <input type="submit" class="button" name="selectvariant" id="selectvariant" value="<?php echo dol_escape_htmltag($langs->trans("SelectCombination")); ?>">
690 </td>
691 </tr>
692 <?php
693 print '<tr><td></td><td>';
694 print $listofvariantselected;
695 print '</td>';
696 print '</tr>';
697
698 print '</table>';
699 print '<hr>';
700 }
701
702 if (is_array($productCombination2ValuePairs1)) {
703 print '<table class="border" style="width: 100%">';
704
705 // When in edit mode
706 if (is_array($productCombination2ValuePairs1) && count($productCombination2ValuePairs1)) {
707 ?>
708 <tr>
709 <td class="titlefieldcreate tdtop"><label for="features"><?php echo $langs->trans('Attributes') ?></label></td>
710 <td class="tdtop">
711 <div class="inline-block valignmiddle quatrevingtpercent">
712 <?php
713 foreach ($productCombination2ValuePairs1 as $pc2v) {
714 $result1 = $prodattr->fetch($pc2v->fk_prod_attr);
715 $result2 = $prodattr_val->fetch($pc2v->fk_prod_attr_val);
716 if ($result1 > 0 && $result2 > 0) {
717 print $prodattr->label.' : '.$prodattr_val->value.'<br>';
718 // TODO Add delete link
719 }
720 } ?>
721 </div>
722 <!-- <div class="inline-block valignmiddle">
723 <a href="#" class="inline-block valignmiddle button" id="delfeature"><?php echo img_edit_remove() ?></a>
724 </div>-->
725 </td>
726 <td>
727 </td>
728 </tr>
729 <?php
730 } ?>
731 <tr>
732 <td><label for="reference"><?php echo $langs->trans('Reference') ?></label></td>
733 <td><input type="text" id="reference" name="reference" value="<?php echo trim($reference) ?>"></td>
734 </tr>
735 <?php
736 if (!getDolGlobalString('PRODUIT_MULTIPRICES')) {
737 ?>
738 <tr>
739 <td><label for="price_impact"><?php echo $langs->trans('PriceImpact') ?></label></td>
740 <td><input type="text" id="price_impact" name="price_impact" value="<?php echo price($price_impact) ?>">
741
742 <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>
743 </td>
744 </tr>
745 <?php
746 } else {
747 $prodcomb->fetchCombinationPriceLevels();
748
749 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
750 for ($i = 1; $i <= $maxi; $i++) {
751 $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i;
752 $text = $langs->trans('ImpactOnPriceLevel', $i).' - '.getDolGlobalString($keyforlabel);
753 print '<tr>';
754 print '<td><label for="level_price_impact_'.$i.'">'.$text.'</label>';
755 if ($i === 1) {
756 print '<br/><a id="apply-price-impact-to-all-level" class="classfortooltip" href="#" title="'.$langs->trans('ApplyToAllPriceImpactLevelHelp').'">('.$langs->trans('ApplyToAllPriceImpactLevel').')</a>';
757 }
758 print '</td>';
759 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).'">';
760 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>';
761
762 print '</td>';
763 print '</tr>';
764 }
765 }
766
767 if ($object->isProduct()) {
768 print '<tr>';
769 print '<td><label for="weight_impact">'.$langs->trans('WeightImpact').'</label></td>';
770 print '<td><input type="text" id="weight_impact" name="weight_impact" value="'.price($weight_impact).'"></td>';
771 print '</tr>';
772 }
773
774 print '</table>';
775 }
776
777 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
778 ?>
779 <script>
780 $(document).ready(function() {
781 // Apply level 1 impact to all prices impact levels
782 $('body').on('click', '#apply-price-impact-to-all-level', function(e) {
783 e.preventDefault();
784 let priceImpact = $( "#level_price_impact_1" ).val();
785 let priceImpactPrecent = $( "#level_price_impact_percent_1" ).prop("checked");
786
787 let multipricelimit = <?php print getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT'); ?>
788
789 for (let i = 2; i <= multipricelimit; i++) {
790 $( "#level_price_impact_" + i ).val(priceImpact);
791 $( "#level_price_impact_percent_" + i ).prop("checked", priceImpactPrecent);
792 }
793 });
794 });
795 </script>
796 <?php
797 }
798
799 print dol_get_fiche_end(); ?>
800
801 <div style="text-align: center">
802 <input type="submit" name="create" <?php if (!is_array($productCombination2ValuePairs1)) {
803 print ' disabled="disabled"';
804 } ?> value="<?php echo $action == 'add' ? $langs->trans('Create') : $langs->trans("Save") ?>" class="button button-save">
805 &nbsp;
806 <input type="submit" name="cancel" value="<?php echo $langs->trans("Cancel"); ?>" class="button button-cancel">
807 </div>
808
809 <?php
810
811 print '</form>';
812 } else {
813 if ($action === 'delete') {
814 if ($prodcomb->fetch($combination_id) > 0) {
815 $prodstatic->fetch($prodcomb->fk_product_child);
816
817 print $form->formconfirm(
818 "combinations.php?id=".urlencode((string) ($id))."&combination_id=".urlencode((string) ($combination_id)),
819 $langs->trans('Delete'),
820 $langs->trans('ProductCombinationDeleteDialog', $prodstatic->ref),
821 "confirm_deletecombination",
822 array(array('label' => $langs->trans('DeleteLinkedProduct'), 'type' => 'checkbox', 'name' => 'delete_product', 'value' => false)),
823 0,
824 1
825 );
826 }
827 } elseif ($action === 'copy') {
828 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);
829 }
830
831 $comb2val = new ProductCombination2ValuePair($db);
832
833 if ($productCombinations) {
834 ?>
835
836 <script type="text/javascript">
837 jQuery(document).ready(function() {
838
839 jQuery('input[name="select_all"]').click(function() {
840
841 if (jQuery(this).prop('checked')) {
842 var checked = true;
843 } else {
844 var checked = false;
845 }
846
847 jQuery('table.liste input[type="checkbox"]').prop('checked', checked);
848 });
849
850 jQuery('input[name^="select["]').click(function() {
851 jQuery('input[name="select_all"]').prop('checked', false);
852 });
853
854 });
855 </script>
856
857 <?php
858 }
859
860 // Buttons
861 print '<div class="tabsAction">';
862
863 print ' <div class="inline-block divButAction">';
864
865 print '<a href="combinations.php?id='.$object->id.'&action=add&token='.newToken().'" class="butAction">'.$langs->trans('NewProductCombination').'</a>'; // NewVariant
866
867 if ($productCombinations) {
868 print '<a href="combinations.php?id='.$object->id.'&action=copy&token='.newToken().'" class="butAction">'.$langs->trans('PropagateVariant').'</a>';
869 }
870
871 print ' </div>';
872
873 print '</div>';
874
875
876
877 $arrayofselected = is_array($toselect) ? $toselect : array();
878
879
880 // List of variants
881 print '<form method="POST" action="'.$_SERVER["PHP_SELF"] .'?id='.$object->id.'">';
882 print '<input type="hidden" name="token" value="'.newToken().'">';
883 print '<input type="hidden" name="action" value="massaction">';
884 print '<input type="hidden" name="backtopage" value="'.$backtopage.'">';
885
886 // List of mass actions available
887
888 $aaa = '';
889 if (count($productCombinations)) {
890 $aaa = '<select id="bulk_action" name="massaction" class="flat">';
891 $aaa .= ' <option value="nothing">&nbsp;</option>';
892 $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>';
893 $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>';
894 $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>';
895 $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>';
896 $aaa .= ' <option value="delete" data-html="'.dol_escape_htmltag(img_picto($langs->trans("Delete"), 'delete', 'class="pictofixedwidth"').$langs->trans('Delete')).'">'.$langs->trans('Delete').'</option>';
897 $aaa .= '</select>';
898 $aaa .= ajax_combobox("bulk_action");
899 $aaa .= '<input type="submit" value="'.dol_escape_htmltag($langs->trans("Apply")).'" class="button small">';
900 }
901 $massactionbutton = $aaa;
902
903 $title = $langs->trans("ProductCombinations");
904
905 print_barre_liste($title, 0, $_SERVER["PHP_SELF"], '', $sortfield, $sortorder, $aaa, 0);
906
907 print '<div class="div-table-responsive">'; ?>
908 <table class="liste">
909 <tr class="liste_titre">
910 <?php
911 // Action column
912 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
913 print '<td class="liste_titre center">';
914 $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
915 print $searchpicto;
916 print '</td>';
917 } ?>
918 <td class="liste_titre"><?php echo $langs->trans('Product') ?></td>
919 <td class="liste_titre"><?php echo $langs->trans('Attributes') ?></td>
920 <td class="liste_titre right"><?php echo $langs->trans('PriceImpact') ?></td>
921 <?php if ($object->isProduct()) {
922 print'<td class="liste_titre right">'.$langs->trans('WeightImpact').'</td>';
923 } ?>
924 <td class="liste_titre center"><?php echo $langs->trans('OnSell') ?></td>
925 <td class="liste_titre center"><?php echo $langs->trans('OnBuy') ?></td>
926 <td class="liste_titre"></td>
927 <?php
928 // Action column
929 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
930 print '<td class="liste_titre center">';
931 $searchpicto = $form->showCheckAddButtons('checkforselect', 1);
932 print $searchpicto;
933 print '</td>';
934 } ?>
935 </tr>
936 <?php
937
938 if (count($productCombinations)) {
939 foreach ($productCombinations as $currcomb) {
940 $prodstatic->fetch($currcomb->fk_product_child);
941 print '<tr class="oddeven">';
942
943 // Action column
944 if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
945 print '<td class="nowrap center">';
946 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
947 $selected = 0;
948 if (in_array($prodstatic->id, $arrayofselected)) {
949 $selected = 1;
950 }
951 print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
952 }
953 print '</td>';
954 }
955
956 print '<td>'.$prodstatic->getNomUrl(1).'</td>';
957 print '<td>';
958 foreach ($comb2val->fetchByFkCombination($currcomb->id) as $pc2v) {
959 print dol_htmlentities($pc2v).'<br>';
960 }
961 print '</td>';
962 print '<td class="right">'.($currcomb->variation_price >= 0 ? '+' : '').price($currcomb->variation_price).($currcomb->variation_price_percentage ? ' %' : '').'</td>';
963 if ($object->isProduct()) {
964 print '<td class="right">'.($currcomb->variation_weight >= 0 ? '+' : '').price($currcomb->variation_weight).' '.measuringUnitString(0, 'weight', $prodstatic->weight_units).'</td>';
965 }
966 print '<td class="center">'.$prodstatic->getLibStatut(2, 0).'</td>';
967 print '<td class="center">'.$prodstatic->getLibStatut(2, 1).'</td>';
968
969 print '<td class="right">';
970 print '<a class="paddingleft paddingright editfielda" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=edit&token='.newToken().'&combination_id='.$currcomb->id.'">'.img_edit().'</a>';
971 print '<a class="paddingleft paddingright" href="'.$_SERVER["PHP_SELF"].'?id='.$id.'&action=delete&token='.newToken().'&combination_id='.$currcomb->id.'">'.img_delete().'</a>';
972 print '</td>';
973
974 // Action column
975 if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) {
976 print '<td class="nowrap center">';
977 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
978 $selected = 0;
979 if (in_array($prodstatic->id, $arrayofselected)) {
980 $selected = 1;
981 }
982 print '<input id="cb'.$prodstatic->id.'" class="flat checkforselect" type="checkbox" name="toselect[]" value="'.$prodstatic->id.'"'.($selected ? ' checked="checked"' : '').'>';
983 }
984 print '</td>';
985 }
986
987 print '</tr>';
988 }
989 } else {
990 print '<tr><td colspan="8"><span class="opacitymedium">'.$langs->trans("None").'</span></td></tr>';
991 }
992 print '</table>';
993 print '</div>';
994 print '</form>';
995 }
996}
997
998// End of page
999llxFooter();
1000$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.