dolibarr 20.0.5
ProductCombination.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2016 Marcos García <marcosgdf@gmail.com>
3 * Copyright (C) 2018 Juanjo Menent <jmenent@2byte.es>
4 * Copyright (C) 2022 Open-Dsi <support@open-dsi.fr>
5 * Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
6 * Copyright (C) 2024 Frédéric France <frederic.france@free.fr>
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
42{
47 public $db;
48
53 public $id;
54
59 public $fk_product_parent;
60
65 public $fk_product_child;
66
71 public $variation_price;
72
78 public $variation_price_percentage = false;
79
84 public $variation_weight;
85
90 public $entity;
91
96 public $combination_price_levels;
97
102 public $variation_ref_ext = '';
103
108 public $error;
109
114 public $errors = array();
115
121 public function __construct(DoliDB $db)
122 {
123 global $conf;
124
125 $this->db = $db;
126 $this->entity = $conf->entity;
127 }
128
135 public function fetch($rowid)
136 {
137 $sql = "SELECT rowid, fk_product_parent, fk_product_child, variation_price, variation_price_percentage, variation_weight, variation_ref_ext FROM ".MAIN_DB_PREFIX."product_attribute_combination WHERE rowid = ".((int) $rowid)." AND entity IN (".getEntity('product').")";
138
139 $query = $this->db->query($sql);
140
141 if (!$query) {
142 return -1;
143 }
144
145 if (!$this->db->num_rows($query)) {
146 return -1;
147 }
148
149 $obj = $this->db->fetch_object($query);
150
151 $this->id = $obj->rowid;
152 $this->fk_product_parent = $obj->fk_product_parent;
153 $this->fk_product_child = $obj->fk_product_child;
154 $this->variation_price = $obj->variation_price;
155 $this->variation_price_percentage = $obj->variation_price_percentage;
156 $this->variation_weight = $obj->variation_weight;
157 $this->variation_ref_ext = $obj->variation_ref_ext;
158
159 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
161 }
162
163 return 1;
164 }
165
166
174 public function fetchCombinationPriceLevels($fk_price_level = 0, $useCache = true)
175 {
176 global $conf;
177
178 // Check cache
179 if (!empty($this->combination_price_levels) && $useCache) {
180 if ((!empty($fk_price_level) && isset($this->combination_price_levels[$fk_price_level])) || empty($fk_price_level)) {
181 return 1;
182 }
183 }
184
185 if (!is_array($this->combination_price_levels)
186 || empty($fk_price_level) // if fetch an unique level don't erase all already fetched
187 ) {
188 $this->combination_price_levels = array();
189 }
190
191 $staticProductCombinationLevel = new ProductCombinationLevel($this->db);
192 $combination_price_levels = $staticProductCombinationLevel->fetchAll($this->id, $fk_price_level);
193
194 if (!is_array($combination_price_levels)) {
195 return -1;
196 }
197
198 if (empty($combination_price_levels)) {
202 if ($fk_price_level > 0) {
203 $combination_price_levels[$fk_price_level] = ProductCombinationLevel::createFromParent($this->db, $this, $fk_price_level);
204 } else {
205 for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
206 $combination_price_levels[$i] = ProductCombinationLevel::createFromParent($this->db, $this, $i);
207 }
208 }
209 }
210
211 $this->combination_price_levels = $combination_price_levels;
212
213 return 1;
214 }
215
222 public function saveCombinationPriceLevels($clean = 1)
223 {
224 global $conf;
225
226 $error = 0;
227
228 $staticProductCombinationLevel = new ProductCombinationLevel($this->db);
229
230 // Delete all
231 if (empty($this->combination_price_levels)) {
232 return $staticProductCombinationLevel->deleteAllForCombination($this->id);
233 }
234
235 // Clean not needed price levels (level higher than number max defined into setup)
236 if ($clean) {
237 $res = $staticProductCombinationLevel->clean($this->id);
238 if ($res < 0) {
239 $this->errors[] = 'Fail to clean not needed price levels';
240 return -1;
241 }
242 }
243
244 foreach ($this->combination_price_levels as $fk_price_level => $combination_price_level) {
245 $res = $combination_price_level->save();
246 if ($res < 1) {
247 $this->error = 'Error saving combination price level '.$fk_price_level.' : '.$combination_price_level->error;
248 $this->errors[] = $this->error;
249 $error++;
250 break;
251 }
252 }
253
254 if ($error) {
255 return $error * -1;
256 } else {
257 return 1;
258 }
259 }
260
268 public function fetchByFkProductChild($productid, $donotloadpricelevel = 0)
269 {
270 global $conf;
271
272 $sql = "SELECT rowid, fk_product_parent, fk_product_child, variation_price, variation_price_percentage, variation_weight";
273 $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute_combination WHERE fk_product_child = ".((int) $productid)." AND entity IN (".getEntity('product').")";
274
275 $query = $this->db->query($sql);
276
277 if (!$query) {
278 return -1;
279 }
280
281 if (!$this->db->num_rows($query)) {
282 return 0;
283 }
284
285 $result = $this->db->fetch_object($query);
286
287 $this->id = $result->rowid;
288 $this->fk_product_parent = $result->fk_product_parent;
289 $this->fk_product_child = $result->fk_product_child;
290 $this->variation_price = $result->variation_price;
291 $this->variation_price_percentage = $result->variation_price_percentage;
292 $this->variation_weight = $result->variation_weight;
293
294 if (empty($donotloadpricelevel) && getDolGlobalString('PRODUIT_MULTIPRICES')) {
296 }
297
298 return (int) $this->fk_product_parent;
299 }
300
308 public function fetchAllByFkProductParent($fk_product_parent, $sort_by_ref = false)
309 {
310 global $conf;
311
312 $sql = "SELECT pac.rowid, pac.fk_product_parent, pac.fk_product_child, pac.variation_price, pac.variation_price_percentage, pac.variation_ref_ext, pac.variation_weight";
313 $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute_combination AS pac";
314 if ($sort_by_ref) {
315 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product AS p ON p.rowid = pac.fk_product_child";
316 }
317 $sql .= " WHERE pac.fk_product_parent = ".((int) $fk_product_parent)." AND pac.entity IN (".getEntity('product').")";
318 if ($sort_by_ref) {
319 $sql .= $this->db->order('p.ref', 'ASC');
320 }
321
322 $query = $this->db->query($sql);
323
324 if (!$query) {
325 return -1;
326 }
327
328 $return = array();
329
330 while ($result = $this->db->fetch_object($query)) {
331 $tmp = new ProductCombination($this->db);
332 $tmp->id = $result->rowid;
333 $tmp->fk_product_parent = $result->fk_product_parent;
334 $tmp->fk_product_child = $result->fk_product_child;
335 $tmp->variation_price = $result->variation_price;
336 $tmp->variation_price_percentage = $result->variation_price_percentage;
337 $tmp->variation_weight = $result->variation_weight;
338 $tmp->variation_ref_ext = $result->variation_ref_ext;
339
340 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
341 $tmp->fetchCombinationPriceLevels();
342 }
343
344 $return[] = $tmp;
345 }
346
347 return $return;
348 }
349
356 public function countNbOfCombinationForFkProductParent($fk_product_parent)
357 {
358 $nb = 0;
359 $sql = "SELECT count(rowid) as nb FROM ".MAIN_DB_PREFIX."product_attribute_combination WHERE fk_product_parent = ".((int) $fk_product_parent)." AND entity IN (".getEntity('product').")";
360
361 $resql = $this->db->query($sql);
362 if ($resql) {
363 $obj = $this->db->fetch_object($resql);
364 if ($obj) {
365 $nb = $obj->nb;
366 }
367 }
368
369 return $nb;
370 }
371
378 public function create($user)
379 {
380 global $conf;
381
382 /* $this->fk_product_child may be empty and will be filled later after subproduct has been created */
383
384 $sql = "INSERT INTO ".MAIN_DB_PREFIX."product_attribute_combination";
385 $sql .= " (fk_product_parent, fk_product_child, variation_price, variation_price_percentage, variation_weight, variation_ref_ext, entity)";
386 $sql .= " VALUES (".((int) $this->fk_product_parent).", ".((int) $this->fk_product_child).",";
387 $sql .= (float) $this->variation_price.", ".(int) $this->variation_price_percentage.",";
388 $sql .= (float) $this->variation_weight.", '".$this->db->escape($this->variation_ref_ext)."', ".(int) $this->entity.")";
389
390 $resql = $this->db->query($sql);
391 if ($resql) {
392 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.'product_attribute_combination');
393 } else {
394 $this->error = $this->db->lasterror();
395 return -1;
396 }
397
398 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
399 $res = $this->saveCombinationPriceLevels();
400 if ($res < 0) {
401 return -2;
402 }
403 }
404
405 return 1;
406 }
407
414 public function update(User $user)
415 {
416 global $conf;
417
418 $sql = "UPDATE ".MAIN_DB_PREFIX."product_attribute_combination";
419 $sql .= " SET fk_product_parent = ".(int) $this->fk_product_parent.", fk_product_child = ".(int) $this->fk_product_child.",";
420 $sql .= " variation_price = ".(float) $this->variation_price.", variation_price_percentage = ".(int) $this->variation_price_percentage.",";
421 $sql .= " variation_ref_ext = '".$this->db->escape($this->variation_ref_ext)."',";
422 $sql .= " variation_weight = ".(float) $this->variation_weight." WHERE rowid = ".((int) $this->id);
423
424 $resql = $this->db->query($sql);
425 if (!$resql) {
426 return -1;
427 }
428
429 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
430 $res = $this->saveCombinationPriceLevels();
431 if ($res < 0) {
432 return -2;
433 }
434 }
435
436 $parent = new Product($this->db);
437 $parent->fetch($this->fk_product_parent);
438
439 $this->updateProperties($parent, $user);
440
441 return 1;
442 }
443
450 public function delete(User $user)
451 {
452 $this->db->begin();
453
454 $comb2val = new ProductCombination2ValuePair($this->db);
455 $comb2val->deleteByFkCombination($this->id);
456
457 // remove combination price levels
458 if (!$this->db->query("DELETE FROM ".MAIN_DB_PREFIX."product_attribute_combination_price_level WHERE fk_product_attribute_combination = ".(int) $this->id)) {
459 $this->db->rollback();
460 return -1;
461 }
462
463 $sql = "DELETE FROM ".MAIN_DB_PREFIX."product_attribute_combination WHERE rowid = ".(int) $this->id;
464
465 if ($this->db->query($sql)) {
466 $this->db->commit();
467 return 1;
468 }
469
470 $this->db->rollback();
471 return -1;
472 }
473
481 public function deleteByFkProductParent($user, $fk_product_parent)
482 {
483 $this->db->begin();
484
485 foreach ($this->fetchAllByFkProductParent($fk_product_parent) as $prodcomb) {
486 $prodstatic = new Product($this->db);
487
488 $res = $prodstatic->fetch($prodcomb->fk_product_child);
489
490 if ($res > 0) {
491 $res = $prodcomb->delete($user);
492 }
493
494 if ($res > 0 && !$prodstatic->isObjectUsed($prodstatic->id)) {
495 $res = $prodstatic->delete($user);
496 }
497
498 if ($res < 0) {
499 $this->db->rollback();
500 return -1;
501 }
502 }
503
504 $this->db->commit();
505 return 1;
506 }
507
516 public function updateProperties(Product $parent, User $user)
517 {
518 global $conf;
519
520 $this->db->begin();
521
522 $child = new Product($this->db);
523 $child->fetch($this->fk_product_child);
524
525 $child->price_autogen = $parent->price_autogen;
526 $child->weight = $parent->weight;
527 // Only when Parent Status are updated
528 if (is_object($parent->oldcopy) && !$parent->oldcopy->isEmpty() && ($parent->status != $parent->oldcopy->status)) {
529 $child->status = $parent->status;
530 }
531 if (is_object($parent->oldcopy) && !$parent->oldcopy->isEmpty() && ($parent->status_buy != $parent->oldcopy->status_buy)) {
532 $child->status_buy = $parent->status_buy;
533 }
534
535 if ($this->variation_weight) { // If we must add a delta on weight
536 $child->weight = ($child->weight ? $child->weight : 0) + $this->variation_weight;
537 }
538 $child->weight_units = $parent->weight_units;
539
540 // Don't update the child label if the user has already modified it.
541 if ($child->label == $parent->label) {
542 // This will trigger only at variant creation time
543 $varlabel = $this->getCombinationLabel($this->fk_product_child);
544 $child->label = $parent->label.$varlabel;
545 }
546
547
548 if ($child->update($child->id, $user) > 0) {
549 $new_vat = $parent->tva_tx;
550 $new_npr = $parent->tva_npr;
551
552 // MultiPrix
553 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
554 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
555 for ($i = 1; $i <= $maxi; $i++) {
556 if ($parent->multiprices[$i] != '' || isset($this->combination_price_levels[$i]->variation_price)) {
557 $new_type = empty($parent->multiprices_base_type[$i]) ? 'HT' : $parent->multiprices_base_type[$i];
558 $new_min_price = $parent->multiprices_min[$i];
559 $variation_price = (float) (!isset($this->combination_price_levels[$i]->variation_price) ? $this->variation_price : $this->combination_price_levels[$i]->variation_price);
560 $variation_price_percentage = (bool) (!isset($this->combination_price_levels[$i]->variation_price_percentage) ? $this->variation_price_percentage : $this->combination_price_levels[$i]->variation_price_percentage);
561
562 if ($parent->prices_by_qty_list[$i]) {
563 $new_psq = 1;
564 } else {
565 $new_psq = 0;
566 }
567
568 if ($new_type == 'TTC') {
569 $new_price = $parent->multiprices_ttc[$i];
570 } else {
571 $new_price = $parent->multiprices[$i];
572 }
573
574 if ($variation_price_percentage) {
575 if ($new_price != 0) {
576 $new_price *= 1 + ($variation_price / 100);
577 }
578 } else {
579 $new_price += $variation_price;
580 }
581
582 $ret = $child->updatePrice($new_price, $new_type, $user, $new_vat, $new_min_price, $i, $new_npr, $new_psq, 0, array(), $parent->default_vat_code);
583
584 if ($ret < 0) {
585 $this->db->rollback();
586 $this->error = $child->error;
587 $this->errors = $child->errors;
588 return $ret;
589 }
590 }
591 }
592 } else {
593 $new_type = $parent->price_base_type;
594 $new_min_price = $parent->price_min;
595 $new_psq = $parent->price_by_qty;
596
597 if ($new_type == 'TTC') {
598 $new_price = $parent->price_ttc;
599 } else {
600 $new_price = $parent->price;
601 }
602
603 if ($this->variation_price_percentage) {
604 if ($new_price != 0) {
605 $new_price *= 1 + ($this->variation_price / 100);
606 }
607 } else {
608 $new_price += $this->variation_price;
609 }
610
611 $ret = $child->updatePrice($new_price, $new_type, $user, $new_vat, $new_min_price, 1, $new_npr, $new_psq);
612
613 if ($ret < 0) {
614 $this->db->rollback();
615 $this->error = $child->error;
616 $this->errors = $child->errors;
617 return $ret;
618 }
619 }
620
621 $this->db->commit();
622
623 return 1;
624 }
625
626 $this->db->rollback();
627 $this->error = $child->error;
628 $this->errors = $child->errors;
629 return -1;
630 }
631
639 public function fetchByProductCombination2ValuePairs($prodid, array $features)
640 {
641 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
642
643 $actual_comp = array();
644
645 $prodcomb2val = new ProductCombination2ValuePair($this->db);
646 $prodcomb = new ProductCombination($this->db);
647
648 $features = array_filter(
649 $features,
654 static function ($v) {
655 return !empty($v);
656 }
657 );
658
659 foreach ($features as $attr => $attr_val) {
660 $actual_comp[$attr] = $attr_val;
661 }
662
663 foreach ($prodcomb->fetchAllByFkProductParent($prodid) as $prc) {
664 $values = array();
665
666 foreach ($prodcomb2val->fetchByFkCombination($prc->id) as $value) {
667 $values[$value->fk_prod_attr] = $value->fk_prod_attr_val;
668 }
669
670 $check1 = count(array_diff_assoc($values, $actual_comp));
671 $check2 = count(array_diff_assoc($actual_comp, $values));
672
673 if (!$check1 && !$check2) {
674 return $prc;
675 }
676 }
677
678 return false;
679 }
680
689 {
690 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
691 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
692
693 // Attributes
694 // Select all unique attributes of the variants (which are to sell) of a given parent product.
695 $sql = "SELECT DISTINCT c2v.fk_prod_attr, a.position";
696 $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute_combination2val c2v";
697 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination c";
698 $sql .= " ON c2v.fk_prod_combination = c.rowid";
699 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product p";
700 $sql .= " ON p.rowid = c.fk_product_child";
701 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute a";
702 $sql .= " ON a.rowid = fk_prod_attr";
703 $sql .= " WHERE c.fk_product_parent = ".((int) $productid);
704 $sql .= " AND p.tosell = 1";
705 $sql .= $this->db->order('a.position', 'asc');
706
707 $resql = $this->db->query($sql);
708
709 // Values
710 $variants = array();
711 while ($obj = $this->db->fetch_object($resql)) {
712 $attr = new ProductAttribute($this->db);
713 $attr->fetch($obj->fk_prod_attr);
714
715 $tmp = new stdClass();
716 $tmp->id = $attr->id;
717 $tmp->ref = $attr->ref;
718 $tmp->label = $attr->label;
719 $tmp->values = array();
720
721 $attrval = new ProductAttributeValue($this->db);
722 // fetch only the used values of this attribute
723 foreach ($attrval->fetchAllByProductAttribute($attr->id, true) as $val) {
724 '@phan-var-force ProductAttributeValue $val';
725 $tmp->values[] = $val;
726 }
727
728 $variants[] = $tmp;
729 }
730
731 return $variants;
732 }
733
757 public function createProductCombination(User $user, Product $product, array $combinations, array $variations, $price_var_percent = false, $forced_pricevar = false, $forced_weightvar = false, $forced_refvar = false, $ref_ext = '')
758 {
759 global $conf;
760
761 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
762 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
763
764 $this->db->begin();
765
766 $price_impact = array(1 => 0); // init level price impact
767
768 $forced_refvar = trim((string) $forced_refvar);
769
770 if (!empty($forced_refvar) && $forced_refvar != $product->ref) {
771 $existingProduct = new Product($this->db);
772 $result = $existingProduct->fetch(0, $forced_refvar);
773 if ($result > 0) {
774 $newproduct = $existingProduct;
775 } else {
776 $existingProduct = false;
777 $newproduct = clone $product;
778 $newproduct->ref = $forced_refvar;
779 }
780 } else {
781 $forced_refvar = false;
782 $existingProduct = false;
783 $newproduct = clone $product;
784 }
785
786 // To avoid warning with unique extrafields values
787 $newproduct->context['createproductcombination'] = 'createproductcombination';
788
789 //Final weight impact
790 $weight_impact = (float) $forced_weightvar; // If false, return 0
791
792 //Final price impact
793 if (!is_array($forced_pricevar)) {
794 $price_impact[1] = (float) $forced_pricevar; // If false, return 0
795 } else {
796 $price_impact = $forced_pricevar;
797 }
798
799 if (!is_array($price_var_percent)) {
800 $price_var_percent = array(1 => (bool) $price_var_percent);
801 }
802
803 $newcomb = new ProductCombination($this->db);
804 $existingCombination = $newcomb->fetchByProductCombination2ValuePairs($product->id, $combinations);
805
806 if ($existingCombination) {
807 $newcomb = $existingCombination;
808 } else {
809 $newcomb->fk_product_parent = $product->id;
810
811 // Create 1 entry into product_attribute_combination (1 entry for each combinations). This init also $newcomb->id
812 $result = $newcomb->create($user);
813 if ($result < 0) {
814 $this->error = $newcomb->error;
815 $this->errors = $newcomb->errors;
816 $this->db->rollback();
817 return -1;
818 }
819 }
820
821 $prodattr = new ProductAttribute($this->db);
822 $prodattrval = new ProductAttributeValue($this->db);
823
824 // $combination contains list of attributes pairs key->value. Example: array('id Color'=>id Blue, 'id Size'=>id Small, 'id Option'=>id val a, ...)
825 foreach ($combinations as $currcombattr => $currcombval) {
826 //This was checked earlier, so no need to double check
827 $prodattr->fetch($currcombattr);
828 $prodattrval->fetch($currcombval);
829
830 //If there is an existing combination, there is no need to duplicate the valuepair
831 if (!$existingCombination) {
832 $tmp = new ProductCombination2ValuePair($this->db);
833 $tmp->fk_prod_attr = $currcombattr;
834 $tmp->fk_prod_attr_val = $currcombval;
835 $tmp->fk_prod_combination = $newcomb->id;
836
837 if ($tmp->create($user) < 0) { // Create 1 entry into product_attribute_combination2val
838 $this->error = $tmp->error;
839 $this->errors = $tmp->errors;
840 $this->db->rollback();
841 return -1;
842 }
843 }
844 if ($forced_weightvar === false) {
845 $weight_impact += (float) price2num($variations[$currcombattr][$currcombval]['weight']);
846 }
847 if ($forced_pricevar === false) {
848 $price_impact[1] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
849
850 // Manage Price levels
851 if ($conf->global->PRODUIT_MULTIPRICES) {
852 for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
853 $price_impact[$i] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
854 }
855 }
856 }
857
858 if ($forced_refvar === false) {
859 if (isset($conf->global->PRODUIT_ATTRIBUTES_SEPARATOR)) {
860 $newproduct->ref .= getDolGlobalString('PRODUIT_ATTRIBUTES_SEPARATOR') . $prodattrval->ref;
861 } else {
862 $newproduct->ref .= '_'.$prodattrval->ref;
863 }
864 }
865
866 //The first one should not contain a linebreak
867 if ($newproduct->description) {
868 $newproduct->description .= '<br>';
869 }
870 $newproduct->description .= '<strong>'.$prodattr->label.':</strong> '.$prodattrval->value;
871 }
872
873 $newcomb->variation_price_percentage = (bool) $price_var_percent[1];
874 $newcomb->variation_price = $price_impact[1];
875 $newcomb->variation_weight = $weight_impact;
876 $newcomb->variation_ref_ext = $this->db->escape($ref_ext);
877
878 // Init price level
879 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
880 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
881 for ($i = 1; $i <= $maxi; $i++) {
882 $productCombinationLevel = new ProductCombinationLevel($this->db);
883 $productCombinationLevel->fk_product_attribute_combination = $newcomb->id;
884 $productCombinationLevel->fk_price_level = $i;
885 $productCombinationLevel->variation_price = $price_impact[$i];
886
887 if (is_array($price_var_percent)) {
888 $productCombinationLevel->variation_price_percentage = (bool) $price_var_percent[$i] ;
889 } else {
890 $productCombinationLevel->variation_price_percentage = $price_var_percent;
891 }
892
893 $newcomb->combination_price_levels[$i] = $productCombinationLevel;
894 }
895 }
896 //var_dump($newcomb->combination_price_levels);
897
898 $newproduct->weight += $weight_impact;
899
900 // Now create the product
901 //print 'Create prod '.$newproduct->ref.'<br>'."\n";
902 if ($existingProduct === false) {
903 //To avoid wrong information in price history log
904 $newproduct->price = 0;
905 $newproduct->price_ttc = 0;
906 $newproduct->price_min = 0;
907 $newproduct->price_min_ttc = 0;
908
909 // A new variant must use a new barcode (not same product)
910 $newproduct->barcode = -1;
911 $result = $newproduct->create($user);
912
913 if ($result < 0) {
914 //In case the error is not related with an already existing product
915 if ($newproduct->error != 'ErrorProductAlreadyExists') {
916 $this->error = $newproduct->error;
917 $this->errors = $newproduct->errors;
918 $this->db->rollback();
919 return -1;
920 }
921
927 if ($newcomb->fk_product_child) {
928 $res = $newproduct->fetch($existingCombination->fk_product_child);
929 } else {
930 $orig_prod_ref = $newproduct->ref;
931 $i = 1;
932
933 do {
934 $newproduct->ref = $orig_prod_ref.$i;
935 $res = $newproduct->create($user);
936
937 if ($newproduct->error != 'ErrorProductAlreadyExists') {
938 $this->errors[] = $newproduct->error;
939 break;
940 }
941
942 $i++;
943 } while ($res < 0);
944 }
945
946 if ($res < 0) {
947 $this->db->rollback();
948 return -1;
949 }
950 }
951 } else {
952 $result = $newproduct->update($newproduct->id, $user);
953 if ($result < 0) {
954 $this->db->rollback();
955 return -1;
956 }
957 }
958
959 $newcomb->fk_product_child = $newproduct->id;
960
961 if ($newcomb->update($user) < 0) {
962 $this->error = $newcomb->error;
963 $this->errors = $newcomb->errors;
964 $this->db->rollback();
965 return -1;
966 }
967
968 $this->db->commit();
969 return $newproduct->id;
970 }
971
980 public function copyAll(User $user, $origProductId, Product $destProduct)
981 {
982 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
983
984 //To prevent a loop
985 if ($origProductId == $destProduct->id) {
986 return -1;
987 }
988
989 $prodcomb2val = new ProductCombination2ValuePair($this->db);
990
991 //Retrieve all product combinations
992 $combinations = $this->fetchAllByFkProductParent($origProductId);
993
994 foreach ($combinations as $combination) {
995 $variations = array();
996
997 foreach ($prodcomb2val->fetchByFkCombination($combination->id) as $tmp_pc2v) {
998 $variations[$tmp_pc2v->fk_prod_attr] = $tmp_pc2v->fk_prod_attr_val;
999 }
1000
1001 $variation_price_percentage = $combination->variation_price_percentage;
1002 $variation_price = $combination->variation_price;
1003
1004 if (getDolGlobalInt('PRODUIT_MULTIPRICES') && getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT') > 1) {
1005 $variation_price_percentage = [ ];
1006 $variation_price = [ ];
1007
1008 foreach ($combination->combination_price_levels as $productCombinationLevel) {
1009 $variation_price_percentage[$productCombinationLevel->fk_price_level] = $productCombinationLevel->variation_price_percentage;
1010 $variation_price[$productCombinationLevel->fk_price_level] = $productCombinationLevel->variation_price;
1011 }
1012 }
1013
1014 if ($this->createProductCombination(
1015 $user,
1016 $destProduct,
1017 $variations,
1018 array(),
1019 $variation_price_percentage,
1020 $variation_price,
1021 $combination->variation_weight
1022 ) < 0) {
1023 return -1;
1024 }
1025 }
1026
1027 return 1;
1028 }
1029
1035 public function getCombinationLabel($prod_child)
1036 {
1037 $label = '';
1038 $sql = 'SELECT pav.value AS label';
1039 $sql .= ' FROM '.MAIN_DB_PREFIX.'product_attribute_combination pac';
1040 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_attribute_combination2val pac2v ON pac2v.fk_prod_combination=pac.rowid';
1041 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_attribute_value pav ON pav.rowid=pac2v.fk_prod_attr_val';
1042 $sql .= ' WHERE pac.fk_product_child='.((int) $prod_child);
1043
1044 $resql = $this->db->query($sql);
1045 if ($resql) {
1046 $num = $this->db->num_rows($resql);
1047
1048 $i = 0;
1049
1050 while ($i < $num) {
1051 $obj = $this->db->fetch_object($resql);
1052
1053 if ($obj->label) {
1054 $label .= ' '.$obj->label;
1055 }
1056 $i++;
1057 }
1058 }
1059 return $label;
1060 }
1061}
1062
1063
1064
1070{
1075 public $db;
1076
1080 public $table_element = 'product_attribute_combination_price_level';
1081
1086 public $id;
1087
1092 public $fk_product_attribute_combination;
1093
1098 public $fk_price_level;
1099
1104 public $variation_price;
1105
1110 public $variation_price_percentage = false;
1111
1115 public $error;
1116
1120 public $errors = array();
1121
1127 public function __construct(DoliDB $db)
1128 {
1129 $this->db = $db;
1130 }
1131
1138 public function fetch($rowid)
1139 {
1140 $sql = "SELECT rowid, fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1141 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1142 $sql .= " WHERE rowid = ".(int) $rowid;
1143
1144 $resql = $this->db->query($sql);
1145 if ($resql) {
1146 $obj = $this->db->fetch_object($resql);
1147 if ($obj) {
1148 return $this->fetchFormObj($obj);
1149 }
1150 }
1151
1152 return -1;
1153 }
1154
1155
1163 public function fetchAll($fk_product_attribute_combination, $fk_price_level = 0)
1164 {
1165 $result = array();
1166
1167 $sql = "SELECT rowid, fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1168 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1169 $sql .= " WHERE fk_product_attribute_combination = ".intval($fk_product_attribute_combination);
1170 if (!empty($fk_price_level)) {
1171 $sql .= ' AND fk_price_level = '.intval($fk_price_level);
1172 }
1173
1174 $res = $this->db->query($sql);
1175 if ($res) {
1176 if ($this->db->num_rows($res) > 0) {
1177 while ($obj = $this->db->fetch_object($res)) {
1178 $productCombinationLevel = new ProductCombinationLevel($this->db);
1179 $productCombinationLevel->fetchFormObj($obj);
1180 $result[$obj->fk_price_level] = $productCombinationLevel;
1181 }
1182 }
1183 } else {
1184 return -1;
1185 }
1186
1187 return $result;
1188 }
1189
1196 public function fetchFormObj($obj)
1197 {
1198 if (!$obj) {
1199 return -1;
1200 }
1201
1202 $this->id = $obj->rowid;
1203 $this->fk_product_attribute_combination = (int) $obj->fk_product_attribute_combination;
1204 $this->fk_price_level = intval($obj->fk_price_level);
1205 $this->variation_price = (float) $obj->variation_price;
1206 $this->variation_price_percentage = (bool) $obj->variation_price_percentage;
1207
1208 return 1;
1209 }
1210
1211
1217 public function save()
1218 {
1219 if (($this->id > 0 && empty($this->fk_product_attribute_combination)) || empty($this->fk_price_level)) {
1220 return -1;
1221 }
1222
1223 // Check if level exist in DB before add
1224 if ($this->fk_product_attribute_combination > 0 && empty($this->id)) {
1225 $sql = "SELECT rowid id";
1226 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1227 $sql .= " WHERE fk_product_attribute_combination = ".(int) $this->fk_product_attribute_combination;
1228 $sql .= ' AND fk_price_level = '.((int) $this->fk_price_level);
1229
1230 $resql = $this->db->query($sql);
1231 if ($resql) {
1232 $obj = $this->db->fetch_object($resql);
1233 if ($obj) {
1234 $this->id = $obj->id;
1235 }
1236 }
1237 }
1238
1239 // Update
1240 if (!empty($this->id)) {
1241 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1242 $sql .= ' SET variation_price = '.(float) $this->variation_price.' , variation_price_percentage = '.intval($this->variation_price_percentage);
1243 $sql .= ' WHERE rowid = '.((int) $this->id);
1244
1245 $res = $this->db->query($sql);
1246 if ($res > 0) {
1247 return $this->id;
1248 } else {
1249 $this->error = $this->db->error();
1250 $this->errors[] = $this->error;
1251 return -1;
1252 }
1253 } else {
1254 // Add
1255 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1256 $sql .= "fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1257 $sql .= ") VALUES (";
1258 $sql .= (int) $this->fk_product_attribute_combination;
1259 $sql .= ", ".intval($this->fk_price_level);
1260 $sql .= ", ".(float) $this->variation_price;
1261 $sql .= ", ".intval($this->variation_price_percentage);
1262 $sql .= ")";
1263
1264 $res = $this->db->query($sql);
1265 if ($res) {
1266 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
1267 } else {
1268 $this->error = $this->db->error();
1269 $this->errors[] = $this->error;
1270 return -1;
1271 }
1272 }
1273
1274 return $this->id;
1275 }
1276
1277
1283 public function delete()
1284 {
1285 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".(int) $this->id;
1286 $res = $this->db->query($sql);
1287
1288 return $res ? 1 : -1;
1289 }
1290
1291
1298 public function deleteAllForCombination($fk_product_attribute_combination)
1299 {
1300 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE fk_product_attribute_combination = ".(int) $fk_product_attribute_combination;
1301 $res = $this->db->query($sql);
1302
1303 return $res ? 1 : -1;
1304 }
1305
1306
1313 public function clean($fk_product_attribute_combination)
1314 {
1315 global $conf;
1316
1317 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
1318 $sql .= " WHERE fk_product_attribute_combination = ".(int) $fk_product_attribute_combination;
1319 $sql .= " AND fk_price_level > ".intval($conf->global->PRODUIT_MULTIPRICES_LIMIT);
1320 $res = $this->db->query($sql);
1321
1322 return $res ? 1 : -1;
1323 }
1324
1325
1334 public static function createFromParent(DoliDB $db, ProductCombination $productCombination, $fkPriceLevel)
1335 {
1336 $productCombinationLevel = new self($db);
1337 $productCombinationLevel->fk_price_level = $fkPriceLevel;
1338 $productCombinationLevel->fk_product_attribute_combination = $productCombination->id;
1339 $productCombinationLevel->variation_price = $productCombination->variation_price;
1340 $productCombinationLevel->variation_price_percentage = (bool) $productCombination->variation_price_percentage;
1341
1342 return $productCombinationLevel;
1343 }
1344}
Class to manage Dolibarr database access.
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.
update(User $user)
Updates a product combination.
countNbOfCombinationForFkProductParent($fk_product_parent)
Retrieves all product combinations by the product parent row id.
getUniqueAttributesAndValuesByFkProductParent($productid)
Retrieves all unique attributes for a parent product (filtered on its 'to sell' variants)
fetchCombinationPriceLevels($fk_price_level=0, $useCache=true)
Retrieves combination price levels.
deleteByFkProductParent($user, $fk_product_parent)
Deletes all product combinations of a parent product.
updateProperties(Product $parent, User $user)
Updates the weight of the child product.
fetchByFkProductChild($productid, $donotloadpricelevel=0)
Retrieves information of a variant product and ID of its parent product.
copyAll(User $user, $origProductId, Product $destProduct)
Copies all product combinations from the origin product to the destination product.
__construct(DoliDB $db)
Constructor.
createProductCombination(User $user, Product $product, array $combinations, array $variations, $price_var_percent=false, $forced_pricevar=false, $forced_weightvar=false, $forced_refvar=false, $ref_ext='')
Creates a product combination.
create($user)
Creates a product attribute combination.
fetchAllByFkProductParent($fk_product_parent, $sort_by_ref=false)
Retrieves all product combinations by the product parent row id.
saveCombinationPriceLevels($clean=1)
Retrieves combination price levels.
getCombinationLabel($prod_child)
Return label for combinations.
fetchByProductCombination2ValuePairs($prodid, array $features)
Retrieves the combination that matches the given features.
fetch($rowid)
Retrieves a ProductCombination by its rowid.
Class ProductCombinationLevel Used to represent a product combination Level.
static createFromParent(DoliDB $db, ProductCombination $productCombination, $fkPriceLevel)
Create new Product Combination Price level from Parent.
save()
Save a price impact of a product combination for a price level.
clean($fk_product_attribute_combination)
Clean not needed price levels for a combination.
fetchAll($fk_product_attribute_combination, $fk_price_level=0)
Retrieves combination price levels.
deleteAllForCombination($fk_product_attribute_combination)
delete all for a combination
fetchFormObj($obj)
Assign vars form an stdclass like sql obj.
__construct(DoliDB $db)
Constructor.
fetch($rowid)
Retrieves a combination level by its rowid.
Class to manage products or services.
Class to manage Dolibarr users.
price2num($amount, $rounding='', $option=0)
Function that return a number with universal decimal format (decimal separator is '.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.