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