dolibarr 20.0.0
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 for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
555 if ($parent->multiprices[$i] != '' || isset($this->combination_price_levels[$i]->variation_price)) {
556 $new_type = empty($parent->multiprices_base_type[$i]) ? 'HT' : $parent->multiprices_base_type[$i];
557 $new_min_price = $parent->multiprices_min[$i];
558 $variation_price = (float) (!isset($this->combination_price_levels[$i]->variation_price) ? $this->variation_price : $this->combination_price_levels[$i]->variation_price);
559 $variation_price_percentage = (float) (!isset($this->combination_price_levels[$i]->variation_price_percentage) ? $this->variation_price_percentage : $this->combination_price_levels[$i]->variation_price_percentage);
560
561 if ($parent->prices_by_qty_list[$i]) {
562 $new_psq = 1;
563 } else {
564 $new_psq = 0;
565 }
566
567 if ($new_type == 'TTC') {
568 $new_price = $parent->multiprices_ttc[$i];
569 } else {
570 $new_price = $parent->multiprices[$i];
571 }
572
573 if ($variation_price_percentage) {
574 if ($new_price != 0) {
575 $new_price *= 1 + ($variation_price / 100);
576 }
577 } else {
578 $new_price += $variation_price;
579 }
580
581 $ret = $child->updatePrice($new_price, $new_type, $user, $new_vat, $new_min_price, $i, $new_npr, $new_psq, 0, array(), $parent->default_vat_code);
582
583 if ($ret < 0) {
584 $this->db->rollback();
585 $this->error = $child->error;
586 $this->errors = $child->errors;
587 return $ret;
588 }
589 }
590 }
591 } else {
592 $new_type = $parent->price_base_type;
593 $new_min_price = $parent->price_min;
594 $new_psq = $parent->price_by_qty;
595
596 if ($new_type == 'TTC') {
597 $new_price = $parent->price_ttc;
598 } else {
599 $new_price = $parent->price;
600 }
601
602 if ($this->variation_price_percentage) {
603 if ($new_price != 0) {
604 $new_price *= 1 + ($this->variation_price / 100);
605 }
606 } else {
607 $new_price += $this->variation_price;
608 }
609
610 $ret = $child->updatePrice($new_price, $new_type, $user, $new_vat, $new_min_price, 1, $new_npr, $new_psq);
611
612 if ($ret < 0) {
613 $this->db->rollback();
614 $this->error = $child->error;
615 $this->errors = $child->errors;
616 return $ret;
617 }
618 }
619
620 $this->db->commit();
621
622 return 1;
623 }
624
625 $this->db->rollback();
626 $this->error = $child->error;
627 $this->errors = $child->errors;
628 return -1;
629 }
630
638 public function fetchByProductCombination2ValuePairs($prodid, array $features)
639 {
640 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
641
642 $actual_comp = array();
643
644 $prodcomb2val = new ProductCombination2ValuePair($this->db);
645 $prodcomb = new ProductCombination($this->db);
646
647 $features = array_filter(
648 $features,
653 static function ($v) {
654 return !empty($v);
655 }
656 );
657
658 foreach ($features as $attr => $attr_val) {
659 $actual_comp[$attr] = $attr_val;
660 }
661
662 foreach ($prodcomb->fetchAllByFkProductParent($prodid) as $prc) {
663 $values = array();
664
665 foreach ($prodcomb2val->fetchByFkCombination($prc->id) as $value) {
666 $values[$value->fk_prod_attr] = $value->fk_prod_attr_val;
667 }
668
669 $check1 = count(array_diff_assoc($values, $actual_comp));
670 $check2 = count(array_diff_assoc($actual_comp, $values));
671
672 if (!$check1 && !$check2) {
673 return $prc;
674 }
675 }
676
677 return false;
678 }
679
688 {
689 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
690 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
691
692 // Attributes
693 // Select all unique attributes of the variants (which are to sell) of a given parent product.
694 $sql = "SELECT DISTINCT c2v.fk_prod_attr, a.position";
695 $sql .= " FROM ".MAIN_DB_PREFIX."product_attribute_combination2val c2v";
696 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute_combination c";
697 $sql .= " ON c2v.fk_prod_combination = c.rowid";
698 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product p";
699 $sql .= " ON p.rowid = c.fk_product_child";
700 $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."product_attribute a";
701 $sql .= " ON a.rowid = fk_prod_attr";
702 $sql .= " WHERE c.fk_product_parent = ".((int) $productid);
703 $sql .= " AND p.tosell = 1";
704 $sql .= $this->db->order('a.position', 'asc');
705
706 $resql = $this->db->query($sql);
707
708 // Values
709 $variants = array();
710 while ($obj = $this->db->fetch_object($resql)) {
711 $attr = new ProductAttribute($this->db);
712 $attr->fetch($obj->fk_prod_attr);
713
714 $tmp = new stdClass();
715 $tmp->id = $attr->id;
716 $tmp->ref = $attr->ref;
717 $tmp->label = $attr->label;
718 $tmp->values = array();
719
720 $attrval = new ProductAttributeValue($this->db);
721 // fetch only the used values of this attribute
722 foreach ($attrval->fetchAllByProductAttribute($attr->id, true) as $val) {
723 '@phan-var-force ProductAttributeValue $val';
724 $tmp->values[] = $val;
725 }
726
727 $variants[] = $tmp;
728 }
729
730 return $variants;
731 }
732
756 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 = '')
757 {
758 global $conf;
759
760 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttribute.class.php';
761 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductAttributeValue.class.php';
762
763 $this->db->begin();
764
765 $price_impact = array(1 => 0); // init level price impact
766
767 $forced_refvar = trim((string) $forced_refvar);
768
769 if (!empty($forced_refvar) && $forced_refvar != $product->ref) {
770 $existingProduct = new Product($this->db);
771 $result = $existingProduct->fetch(0, $forced_refvar);
772 if ($result > 0) {
773 $newproduct = $existingProduct;
774 } else {
775 $existingProduct = false;
776 $newproduct = clone $product;
777 $newproduct->ref = $forced_refvar;
778 }
779 } else {
780 $forced_refvar = false;
781 $existingProduct = false;
782 $newproduct = clone $product;
783 }
784
785 //Final weight impact
786 $weight_impact = (float) $forced_weightvar; // If false, return 0
787
788 //Final price impact
789 if (!is_array($forced_pricevar)) {
790 $price_impact[1] = (float) $forced_pricevar; // If false, return 0
791 } else {
792 $price_impact = $forced_pricevar;
793 }
794
795 if (!array($price_var_percent)) {
796 $price_var_percent[1] = (float) $price_var_percent;
797 }
798
799 $newcomb = new ProductCombination($this->db);
800 $existingCombination = $newcomb->fetchByProductCombination2ValuePairs($product->id, $combinations);
801
802 if ($existingCombination) {
803 $newcomb = $existingCombination;
804 } else {
805 $newcomb->fk_product_parent = $product->id;
806
807 // Create 1 entry into product_attribute_combination (1 entry for each combinations). This init also $newcomb->id
808 $result = $newcomb->create($user);
809 if ($result < 0) {
810 $this->error = $newcomb->error;
811 $this->errors = $newcomb->errors;
812 $this->db->rollback();
813 return -1;
814 }
815 }
816
817 $prodattr = new ProductAttribute($this->db);
818 $prodattrval = new ProductAttributeValue($this->db);
819
820 // $combination contains list of attributes pairs key->value. Example: array('id Color'=>id Blue, 'id Size'=>id Small, 'id Option'=>id val a, ...)
821 foreach ($combinations as $currcombattr => $currcombval) {
822 //This was checked earlier, so no need to double check
823 $prodattr->fetch($currcombattr);
824 $prodattrval->fetch($currcombval);
825
826 //If there is an existing combination, there is no need to duplicate the valuepair
827 if (!$existingCombination) {
828 $tmp = new ProductCombination2ValuePair($this->db);
829 $tmp->fk_prod_attr = $currcombattr;
830 $tmp->fk_prod_attr_val = $currcombval;
831 $tmp->fk_prod_combination = $newcomb->id;
832
833 if ($tmp->create($user) < 0) { // Create 1 entry into product_attribute_combination2val
834 $this->error = $tmp->error;
835 $this->errors = $tmp->errors;
836 $this->db->rollback();
837 return -1;
838 }
839 }
840 if ($forced_weightvar === false) {
841 $weight_impact += (float) price2num($variations[$currcombattr][$currcombval]['weight']);
842 }
843 if ($forced_pricevar === false) {
844 $price_impact[1] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
845
846 // Manage Price levels
847 if ($conf->global->PRODUIT_MULTIPRICES) {
848 for ($i = 2; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
849 $price_impact[$i] += (float) price2num($variations[$currcombattr][$currcombval]['price']);
850 }
851 }
852 }
853
854 if ($forced_refvar === false) {
855 if (isset($conf->global->PRODUIT_ATTRIBUTES_SEPARATOR)) {
856 $newproduct->ref .= getDolGlobalString('PRODUIT_ATTRIBUTES_SEPARATOR') . $prodattrval->ref;
857 } else {
858 $newproduct->ref .= '_'.$prodattrval->ref;
859 }
860 }
861
862 //The first one should not contain a linebreak
863 if ($newproduct->description) {
864 $newproduct->description .= '<br>';
865 }
866 $newproduct->description .= '<strong>'.$prodattr->label.':</strong> '.$prodattrval->value;
867 }
868
869 $newcomb->variation_price_percentage = $price_var_percent[1];
870 $newcomb->variation_price = $price_impact[1];
871 $newcomb->variation_weight = $weight_impact;
872 $newcomb->variation_ref_ext = $this->db->escape($ref_ext);
873
874 // Init price level
875 if ($conf->global->PRODUIT_MULTIPRICES) {
876 for ($i = 1; $i <= $conf->global->PRODUIT_MULTIPRICES_LIMIT; $i++) {
877 $productCombinationLevel = new ProductCombinationLevel($this->db);
878 $productCombinationLevel->fk_product_attribute_combination = $newcomb->id;
879 $productCombinationLevel->fk_price_level = $i;
880 $productCombinationLevel->variation_price = $price_impact[$i];
881
882 if (is_array($price_var_percent)) {
883 $productCombinationLevel->variation_price_percentage = (empty($price_var_percent[$i]) ? false : $price_var_percent[$i]);
884 } else {
885 $productCombinationLevel->variation_price_percentage = $price_var_percent;
886 }
887
888 $newcomb->combination_price_levels[$i] = $productCombinationLevel;
889 }
890 }
891 //var_dump($newcomb->combination_price_levels);
892
893 $newproduct->weight += $weight_impact;
894
895 // Now create the product
896 //print 'Create prod '.$newproduct->ref.'<br>'."\n";
897 if ($existingProduct === false) {
898 //To avoid wrong information in price history log
899 $newproduct->price = 0;
900 $newproduct->price_ttc = 0;
901 $newproduct->price_min = 0;
902 $newproduct->price_min_ttc = 0;
903
904 // A new variant must use a new barcode (not same product)
905 $newproduct->barcode = -1;
906 $result = $newproduct->create($user);
907
908 if ($result < 0) {
909 //In case the error is not related with an already existing product
910 if ($newproduct->error != 'ErrorProductAlreadyExists') {
911 $this->error = $newproduct->error;
912 $this->errors = $newproduct->errors;
913 $this->db->rollback();
914 return -1;
915 }
916
922 if ($newcomb->fk_product_child) {
923 $res = $newproduct->fetch($existingCombination->fk_product_child);
924 } else {
925 $orig_prod_ref = $newproduct->ref;
926 $i = 1;
927
928 do {
929 $newproduct->ref = $orig_prod_ref.$i;
930 $res = $newproduct->create($user);
931
932 if ($newproduct->error != 'ErrorProductAlreadyExists') {
933 $this->errors[] = $newproduct->error;
934 break;
935 }
936
937 $i++;
938 } while ($res < 0);
939 }
940
941 if ($res < 0) {
942 $this->db->rollback();
943 return -1;
944 }
945 }
946 } else {
947 $result = $newproduct->update($newproduct->id, $user);
948 if ($result < 0) {
949 $this->db->rollback();
950 return -1;
951 }
952 }
953
954 $newcomb->fk_product_child = $newproduct->id;
955
956 if ($newcomb->update($user) < 0) {
957 $this->error = $newcomb->error;
958 $this->errors = $newcomb->errors;
959 $this->db->rollback();
960 return -1;
961 }
962
963 $this->db->commit();
964 return $newproduct->id;
965 }
966
975 public function copyAll(User $user, $origProductId, Product $destProduct)
976 {
977 require_once DOL_DOCUMENT_ROOT.'/variants/class/ProductCombination2ValuePair.class.php';
978
979 //To prevent a loop
980 if ($origProductId == $destProduct->id) {
981 return -1;
982 }
983
984 $prodcomb2val = new ProductCombination2ValuePair($this->db);
985
986 //Retrieve all product combinations
987 $combinations = $this->fetchAllByFkProductParent($origProductId);
988
989 foreach ($combinations as $combination) {
990 $variations = array();
991
992 foreach ($prodcomb2val->fetchByFkCombination($combination->id) as $tmp_pc2v) {
993 $variations[$tmp_pc2v->fk_prod_attr] = $tmp_pc2v->fk_prod_attr_val;
994 }
995
996 if ($this->createProductCombination(
997 $user,
998 $destProduct,
999 $variations,
1000 array(),
1001 $combination->variation_price_percentage,
1002 $combination->variation_price,
1003 $combination->variation_weight
1004 ) < 0) {
1005 return -1;
1006 }
1007 }
1008
1009 return 1;
1010 }
1011
1017 public function getCombinationLabel($prod_child)
1018 {
1019 $label = '';
1020 $sql = 'SELECT pav.value AS label';
1021 $sql .= ' FROM '.MAIN_DB_PREFIX.'product_attribute_combination pac';
1022 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_attribute_combination2val pac2v ON pac2v.fk_prod_combination=pac.rowid';
1023 $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'product_attribute_value pav ON pav.rowid=pac2v.fk_prod_attr_val';
1024 $sql .= ' WHERE pac.fk_product_child='.((int) $prod_child);
1025
1026 $resql = $this->db->query($sql);
1027 if ($resql) {
1028 $num = $this->db->num_rows($resql);
1029
1030 $i = 0;
1031
1032 while ($i < $num) {
1033 $obj = $this->db->fetch_object($resql);
1034
1035 if ($obj->label) {
1036 $label .= ' '.$obj->label;
1037 }
1038 $i++;
1039 }
1040 }
1041 return $label;
1042 }
1043}
1044
1045
1046
1052{
1057 public $db;
1058
1062 public $table_element = 'product_attribute_combination_price_level';
1063
1068 public $id;
1069
1074 public $fk_product_attribute_combination;
1075
1080 public $fk_price_level;
1081
1086 public $variation_price;
1087
1092 public $variation_price_percentage = false;
1093
1097 public $error;
1098
1102 public $errors = array();
1103
1109 public function __construct(DoliDB $db)
1110 {
1111 $this->db = $db;
1112 }
1113
1120 public function fetch($rowid)
1121 {
1122 $sql = "SELECT rowid, fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1123 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1124 $sql .= " WHERE rowid = ".(int) $rowid;
1125
1126 $resql = $this->db->query($sql);
1127 if ($resql) {
1128 $obj = $this->db->fetch_object($resql);
1129 if ($obj) {
1130 return $this->fetchFormObj($obj);
1131 }
1132 }
1133
1134 return -1;
1135 }
1136
1137
1145 public function fetchAll($fk_product_attribute_combination, $fk_price_level = 0)
1146 {
1147 $result = array();
1148
1149 $sql = "SELECT rowid, fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1150 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1151 $sql .= " WHERE fk_product_attribute_combination = ".intval($fk_product_attribute_combination);
1152 if (!empty($fk_price_level)) {
1153 $sql .= ' AND fk_price_level = '.intval($fk_price_level);
1154 }
1155
1156 $res = $this->db->query($sql);
1157 if ($res) {
1158 if ($this->db->num_rows($res) > 0) {
1159 while ($obj = $this->db->fetch_object($res)) {
1160 $productCombinationLevel = new ProductCombinationLevel($this->db);
1161 $productCombinationLevel->fetchFormObj($obj);
1162 $result[$obj->fk_price_level] = $productCombinationLevel;
1163 }
1164 }
1165 } else {
1166 return -1;
1167 }
1168
1169 return $result;
1170 }
1171
1178 public function fetchFormObj($obj)
1179 {
1180 if (!$obj) {
1181 return -1;
1182 }
1183
1184 $this->id = $obj->rowid;
1185 $this->fk_product_attribute_combination = (int) $obj->fk_product_attribute_combination;
1186 $this->fk_price_level = intval($obj->fk_price_level);
1187 $this->variation_price = (float) $obj->variation_price;
1188 $this->variation_price_percentage = (bool) $obj->variation_price_percentage;
1189
1190 return 1;
1191 }
1192
1193
1199 public function save()
1200 {
1201 if (($this->id > 0 && empty($this->fk_product_attribute_combination)) || empty($this->fk_price_level)) {
1202 return -1;
1203 }
1204
1205 // Check if level exist in DB before add
1206 if ($this->fk_product_attribute_combination > 0 && empty($this->id)) {
1207 $sql = "SELECT rowid id";
1208 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element;
1209 $sql .= " WHERE fk_product_attribute_combination = ".(int) $this->fk_product_attribute_combination;
1210 $sql .= ' AND fk_price_level = '.((int) $this->fk_price_level);
1211
1212 $resql = $this->db->query($sql);
1213 if ($resql) {
1214 $obj = $this->db->fetch_object($resql);
1215 if ($obj) {
1216 $this->id = $obj->id;
1217 }
1218 }
1219 }
1220
1221 // Update
1222 if (!empty($this->id)) {
1223 $sql = 'UPDATE '.MAIN_DB_PREFIX.$this->table_element;
1224 $sql .= ' SET variation_price = '.(float) $this->variation_price.' , variation_price_percentage = '.intval($this->variation_price_percentage);
1225 $sql .= ' WHERE rowid = '.((int) $this->id);
1226
1227 $res = $this->db->query($sql);
1228 if ($res > 0) {
1229 return $this->id;
1230 } else {
1231 $this->error = $this->db->error();
1232 $this->errors[] = $this->error;
1233 return -1;
1234 }
1235 } else {
1236 // Add
1237 $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (";
1238 $sql .= "fk_product_attribute_combination, fk_price_level, variation_price, variation_price_percentage";
1239 $sql .= ") VALUES (";
1240 $sql .= (int) $this->fk_product_attribute_combination;
1241 $sql .= ", ".intval($this->fk_price_level);
1242 $sql .= ", ".(float) $this->variation_price;
1243 $sql .= ", ".intval($this->variation_price_percentage);
1244 $sql .= ")";
1245
1246 $res = $this->db->query($sql);
1247 if ($res) {
1248 $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
1249 } else {
1250 $this->error = $this->db->error();
1251 $this->errors[] = $this->error;
1252 return -1;
1253 }
1254 }
1255
1256 return $this->id;
1257 }
1258
1259
1265 public function delete()
1266 {
1267 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".(int) $this->id;
1268 $res = $this->db->query($sql);
1269
1270 return $res ? 1 : -1;
1271 }
1272
1273
1280 public function deleteAllForCombination($fk_product_attribute_combination)
1281 {
1282 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE fk_product_attribute_combination = ".(int) $fk_product_attribute_combination;
1283 $res = $this->db->query($sql);
1284
1285 return $res ? 1 : -1;
1286 }
1287
1288
1295 public function clean($fk_product_attribute_combination)
1296 {
1297 global $conf;
1298
1299 $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element;
1300 $sql .= " WHERE fk_product_attribute_combination = ".(int) $fk_product_attribute_combination;
1301 $sql .= " AND fk_price_level > ".intval($conf->global->PRODUIT_MULTIPRICES_LIMIT);
1302 $res = $this->db->query($sql);
1303
1304 return $res ? 1 : -1;
1305 }
1306
1307
1316 public static function createFromParent(DoliDB $db, ProductCombination $productCombination, $fkPriceLevel)
1317 {
1318 $productCombinationLevel = new self($db);
1319 $productCombinationLevel->fk_price_level = $fkPriceLevel;
1320 $productCombinationLevel->fk_product_attribute_combination = $productCombination->id;
1321 $productCombinationLevel->variation_price = $productCombination->variation_price;
1322 $productCombinationLevel->variation_price_percentage = (bool) $productCombination->variation_price_percentage;
1323
1324 return $productCombinationLevel;
1325 }
1326}
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 '.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.