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