dolibarr 20.0.4
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 //Final weight impact
787 $weight_impact = (float) $forced_weightvar; // If false, return 0
788
789 //Final price impact
790 if (!is_array($forced_pricevar)) {
791 $price_impact[1] = (float) $forced_pricevar; // If false, return 0
792 } else {
793 $price_impact = $forced_pricevar;
794 }
795
796 if (!array($price_var_percent)) {
797 $price_var_percent[1] = (float) $price_var_percent;
798 }
799
800 $newcomb = new ProductCombination($this->db);
801 $existingCombination = $newcomb->fetchByProductCombination2ValuePairs($product->id, $combinations);
802
803 if ($existingCombination) {
804 $newcomb = $existingCombination;
805 } else {
806 $newcomb->fk_product_parent = $product->id;
807
808 // Create 1 entry into product_attribute_combination (1 entry for each combinations). This init also $newcomb->id
809 $result = $newcomb->create($user);
810 if ($result < 0) {
811 $this->error = $newcomb->error;
812 $this->errors = $newcomb->errors;
813 $this->db->rollback();
814 return -1;
815 }
816 }
817
818 $prodattr = new ProductAttribute($this->db);
819 $prodattrval = new ProductAttributeValue($this->db);
820
821 // $combination contains list of attributes pairs key->value. Example: array('id Color'=>id Blue, 'id Size'=>id Small, 'id Option'=>id val a, ...)
822 foreach ($combinations as $currcombattr => $currcombval) {
823 //This was checked earlier, so no need to double check
824 $prodattr->fetch($currcombattr);
825 $prodattrval->fetch($currcombval);
826
827 //If there is an existing combination, there is no need to duplicate the valuepair
828 if (!$existingCombination) {
829 $tmp = new ProductCombination2ValuePair($this->db);
830 $tmp->fk_prod_attr = $currcombattr;
831 $tmp->fk_prod_attr_val = $currcombval;
832 $tmp->fk_prod_combination = $newcomb->id;
833
834 if ($tmp->create($user) < 0) { // Create 1 entry into product_attribute_combination2val
835 $this->error = $tmp->error;
836 $this->errors = $tmp->errors;
837 $this->db->rollback();
838 return -1;
839 }
840 }
841 if ($forced_weightvar === false) {
842 $weight_impact += (float) price2num($variations[$currcombattr][$currcombval]['weight']);
843 }
844 if ($forced_pricevar === false) {
845 $price_impact[1] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
846
847 // Manage Price levels
848 if ($conf->global->PRODUIT_MULTIPRICES) {
849 for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
850 $price_impact[$i] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
851 }
852 }
853 }
854
855 if ($forced_refvar === false) {
856 if (isset($conf->global->PRODUIT_ATTRIBUTES_SEPARATOR)) {
857 $newproduct->ref .= getDolGlobalString('PRODUIT_ATTRIBUTES_SEPARATOR') . $prodattrval->ref;
858 } else {
859 $newproduct->ref .= '_'.$prodattrval->ref;
860 }
861 }
862
863 //The first one should not contain a linebreak
864 if ($newproduct->description) {
865 $newproduct->description .= '<br>';
866 }
867 $newproduct->description .= '<strong>'.$prodattr->label.':</strong> '.$prodattrval->value;
868 }
869
870 $newcomb->variation_price_percentage = (bool) $price_var_percent[1];
871 $newcomb->variation_price = $price_impact[1];
872 $newcomb->variation_weight = $weight_impact;
873 $newcomb->variation_ref_ext = $this->db->escape($ref_ext);
874
875 // Init price level
876 if (getDolGlobalString('PRODUIT_MULTIPRICES')) {
877 $maxi = getDolGlobalInt('PRODUIT_MULTIPRICES_LIMIT');
878 for ($i = 1; $i <= $maxi; $i++) {
879 $productCombinationLevel = new ProductCombinationLevel($this->db);
880 $productCombinationLevel->fk_product_attribute_combination = $newcomb->id;
881 $productCombinationLevel->fk_price_level = $i;
882 $productCombinationLevel->variation_price = $price_impact[$i];
883
884 if (is_array($price_var_percent)) {
885 $productCombinationLevel->variation_price_percentage = (bool) $price_var_percent[$i] ;
886 } else {
887 $productCombinationLevel->variation_price_percentage = $price_var_percent;
888 }
889
890 $newcomb->combination_price_levels[$i] = $productCombinationLevel;
891 }
892 }
893 //var_dump($newcomb->combination_price_levels);
894
895 $newproduct->weight += $weight_impact;
896
897 // Now create the product
898 //print 'Create prod '.$newproduct->ref.'<br>'."\n";
899 if ($existingProduct === false) {
900 //To avoid wrong information in price history log
901 $newproduct->price = 0;
902 $newproduct->price_ttc = 0;
903 $newproduct->price_min = 0;
904 $newproduct->price_min_ttc = 0;
905
906 // A new variant must use a new barcode (not same product)
907 $newproduct->barcode = -1;
908 $result = $newproduct->create($user);
909
910 if ($result < 0) {
911 //In case the error is not related with an already existing product
912 if ($newproduct->error != 'ErrorProductAlreadyExists') {
913 $this->error = $newproduct->error;
914 $this->errors = $newproduct->errors;
915 $this->db->rollback();
916 return -1;
917 }
918
924 if ($newcomb->fk_product_child) {
925 $res = $newproduct->fetch($existingCombination->fk_product_child);
926 } else {
927 $orig_prod_ref = $newproduct->ref;
928 $i = 1;
929
930 do {
931 $newproduct->ref = $orig_prod_ref.$i;
932 $res = $newproduct->create($user);
933
934 if ($newproduct->error != 'ErrorProductAlreadyExists') {
935 $this->errors[] = $newproduct->error;
936 break;
937 }
938
939 $i++;
940 } while ($res < 0);
941 }
942
943 if ($res < 0) {
944 $this->db->rollback();
945 return -1;
946 }
947 }
948 } else {
949 $result = $newproduct->update($newproduct->id, $user);
950 if ($result < 0) {
951 $this->db->rollback();
952 return -1;
953 }
954 }
955
956 $newcomb->fk_product_child = $newproduct->id;
957
958 if ($newcomb->update($user) < 0) {
959 $this->error = $newcomb->error;
960 $this->errors = $newcomb->errors;
961 $this->db->rollback();
962 return -1;
963 }
964
965 $this->db->commit();
966 return $newproduct->id;
967 }
968
977 public function copyAll(User $user, $origProductId, Product $destProduct)
978 {
979 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
980
981 //To prevent a loop
982 if ($origProductId == $destProduct->id) {
983 return -1;
984 }
985
986 $prodcomb2val = new ProductCombination2ValuePair($this->db);
987
988 //Retrieve all product combinations
989 $combinations = $this->fetchAllByFkProductParent($origProductId);
990
991 foreach ($combinations as $combination) {
992 $variations = array();
993
994 foreach ($prodcomb2val->fetchByFkCombination($combination->id) as $tmp_pc2v) {
995 $variations[$tmp_pc2v->fk_prod_attr] = $tmp_pc2v->fk_prod_attr_val;
996 }
997
998 if ($this->createProductCombination(
999 $user,
1000 $destProduct,
1001 $variations,
1002 array(),
1003 $combination->variation_price_percentage,
1004 $combination->variation_price,
1005 $combination->variation_weight
1006 ) < 0) {
1007 return -1;
1008 }
1009 }
1010
1011 return 1;
1012 }
1013
1019 public function getCombinationLabel($prod_child)
1020 {
1021 $label = '';
1022 $sql = 'SELECT pav.value AS label';
1023 $sql .= ' FROM '.MAIN_DB_PREFIX.'product_attribute_combination pac';
1024 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_attribute_combination2val pac2v ON pac2v.fk_prod_combination=pac.rowid';
1025 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_attribute_value pav ON pav.rowid=pac2v.fk_prod_attr_val';
1026 $sql .= ' WHERE pac.fk_product_child='.((int) $prod_child);
1027
1028 $resql = $this->db->query($sql);
1029 if ($resql) {
1030 $num = $this->db->num_rows($resql);
1031
1032 $i = 0;
1033
1034 while ($i < $num) {
1035 $obj = $this->db->fetch_object($resql);
1036
1037 if ($obj->label) {
1038 $label .= ' '.$obj->label;
1039 }
1040 $i++;
1041 }
1042 }
1043 return $label;
1044 }
1045}
1046
1047
1048
1054{
1059 public $db;
1060
1064 public $table_element = 'product_attribute_combination_price_level';
1065
1070 public $id;
1071
1076 public $fk_product_attribute_combination;
1077
1082 public $fk_price_level;
1083
1088 public $variation_price;
1089
1094 public $variation_price_percentage = false;
1095
1099 public $error;
1100
1104 public $errors = array();
1105
1111 public function __construct(DoliDB $db)
1112 {
1113 $this->db = $db;
1114 }
1115
1122 public function fetch($rowid)
1123 {
1124 $sql = "SELECT rowid, fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1125 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1126 $sql .= " WHERE rowid = ".(int) $rowid;
1127
1128 $resql = $this->db->query($sql);
1129 if ($resql) {
1130 $obj = $this->db->fetch_object($resql);
1131 if ($obj) {
1132 return $this->fetchFormObj($obj);
1133 }
1134 }
1135
1136 return -1;
1137 }
1138
1139
1147 public function fetchAll($fk_product_attribute_combination, $fk_price_level = 0)
1148 {
1149 $result = array();
1150
1151 $sql = "SELECT rowid, fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1152 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1153 $sql .= " WHERE fk_product_attribute_combination = ".intval($fk_product_attribute_combination);
1154 if (!empty($fk_price_level)) {
1155 $sql .= ' AND fk_price_level = '.intval($fk_price_level);
1156 }
1157
1158 $res = $this->db->query($sql);
1159 if ($res) {
1160 if ($this->db->num_rows($res) > 0) {
1161 while ($obj = $this->db->fetch_object($res)) {
1162 $productCombinationLevel = new ProductCombinationLevel($this->db);
1163 $productCombinationLevel->fetchFormObj($obj);
1164 $result[$obj->fk_price_level] = $productCombinationLevel;
1165 }
1166 }
1167 } else {
1168 return -1;
1169 }
1170
1171 return $result;
1172 }
1173
1180 public function fetchFormObj($obj)
1181 {
1182 if (!$obj) {
1183 return -1;
1184 }
1185
1186 $this->id = $obj->rowid;
1187 $this->fk_product_attribute_combination = (int) $obj->fk_product_attribute_combination;
1188 $this->fk_price_level = intval($obj->fk_price_level);
1189 $this->variation_price = (float) $obj->variation_price;
1190 $this->variation_price_percentage = (bool) $obj->variation_price_percentage;
1191
1192 return 1;
1193 }
1194
1195
1201 public function save()
1202 {
1203 if (($this->id > 0 && empty($this->fk_product_attribute_combination)) || empty($this->fk_price_level)) {
1204 return -1;
1205 }
1206
1207 // Check if level exist in DB before add
1208 if ($this->fk_product_attribute_combination > 0 && empty($this->id)) {
1209 $sql = "SELECT rowid id";
1210 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1211 $sql .= " WHERE fk_product_attribute_combination = ".(int) $this->fk_product_attribute_combination;
1212 $sql .= ' AND fk_price_level = '.((int) $this->fk_price_level);
1213
1214 $resql = $this->db->query($sql);
1215 if ($resql) {
1216 $obj = $this->db->fetch_object($resql);
1217 if ($obj) {
1218 $this->id = $obj->id;
1219 }
1220 }
1221 }
1222
1223 // Update
1224 if (!empty($this->id)) {
1225 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1226 $sql .= ' SET variation_price = '.(float) $this->variation_price.' , variation_price_percentage = '.intval($this->variation_price_percentage);
1227 $sql .= ' WHERE rowid = '.((int) $this->id);
1228
1229 $res = $this->db->query($sql);
1230 if ($res > 0) {
1231 return $this->id;
1232 } else {
1233 $this->error = $this->db->error();
1234 $this->errors[] = $this->error;
1235 return -1;
1236 }
1237 } else {
1238 // Add
1239 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1240 $sql .= "fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1241 $sql .= ") VALUES (";
1242 $sql .= (int) $this->fk_product_attribute_combination;
1243 $sql .= ", ".intval($this->fk_price_level);
1244 $sql .= ", ".(float) $this->variation_price;
1245 $sql .= ", ".intval($this->variation_price_percentage);
1246 $sql .= ")";
1247
1248 $res = $this->db->query($sql);
1249 if ($res) {
1250 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
1251 } else {
1252 $this->error = $this->db->error();
1253 $this->errors[] = $this->error;
1254 return -1;
1255 }
1256 }
1257
1258 return $this->id;
1259 }
1260
1261
1267 public function delete()
1268 {
1269 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".(int) $this->id;
1270 $res = $this->db->query($sql);
1271
1272 return $res ? 1 : -1;
1273 }
1274
1275
1282 public function deleteAllForCombination($fk_product_attribute_combination)
1283 {
1284 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE fk_product_attribute_combination = ".(int) $fk_product_attribute_combination;
1285 $res = $this->db->query($sql);
1286
1287 return $res ? 1 : -1;
1288 }
1289
1290
1297 public function clean($fk_product_attribute_combination)
1298 {
1299 global $conf;
1300
1301 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
1302 $sql .= " WHERE fk_product_attribute_combination = ".(int) $fk_product_attribute_combination;
1303 $sql .= " AND fk_price_level > ".intval($conf->global->PRODUIT_MULTIPRICES_LIMIT);
1304 $res = $this->db->query($sql);
1305
1306 return $res ? 1 : -1;
1307 }
1308
1309
1318 public static function createFromParent(DoliDB $db, ProductCombination $productCombination, $fkPriceLevel)
1319 {
1320 $productCombinationLevel = new self($db);
1321 $productCombinationLevel->fk_price_level = $fkPriceLevel;
1322 $productCombinationLevel->fk_product_attribute_combination = $productCombination->id;
1323 $productCombinationLevel->variation_price = $productCombination->variation_price;
1324 $productCombinationLevel->variation_price_percentage = (bool) $productCombination->variation_price_percentage;
1325
1326 return $productCombinationLevel;
1327 }
1328}
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.