@valentinadikaya

Как сделать, чтобы скидка не суммировалась?

Задача.
Есть корзина.
В корзине лежит 2 товара, один по акции, другой нет.
В корзине применяеться промо код.
Сейчас этот промокод применяеться к общей сумме товаров в корзине, то есть акционный + не акционный.
НУЖНО
Нужно сделать так, чтобы промокод не применялся к акционному товару. Идея сделать так.
Расчет значения $value : Сумма в корзине - сумма акционных товаров

Код файла со скидкой:

<?php
    /**
     * Discount counts apply - products quantity in
          */
    private $appliesControl = [];

    public $overload = 0.0;

    /**
     * __construct base object loaded
   
     */
    public function __construct() {

        parent::__construct();
        $lang = new MY_Lang();
        $lang->load('mod_discount');
        $this->load->model('discount_model_admin');
    }
    /**
     * autoload execute when get product variant
      */
    public function autoload() {
        if (BaseDiscount::checkModuleInstall()) {

              $this->applyDiscountCartItems();
//// Вычитает общую сумму от доставки
                $this->applyResultDiscount();
            /** apply Gift */
            if ($this->input->post('gift')) {
                $this->applyGift();
            }
            $giftKey = \CI::$APP->session->flashdata('makeOrderGiftKey');
            if (!empty($giftKey)) {
                BaseDiscount::create()->updateDiskApply($giftKey, 'gift');
            }

            Events::create()->setListener([$this, 'updateDiscountsApplies'], 'Cart:OrderValidated');

        }
    }

    /**
     * apply discount to Cart Items
      */
   private function applyDiscountCartItems() {
        $cart = BaseCart::getInstance();
        $cartItems = $cart->getItems('SProducts');

        if (count($cartItems['data']) == 0) {
            return;
        }
        /** @var SProducts|ShopKit $item */
      foreach ($cartItems['data'] as $item) {

            $usedDiscountVariantPrice = true;

            if (class_exists('\VariantPriceType\BaseVariantPriceType') && self::isPremiumCMS()) {

                $usedDiscountVariantPrice = \VariantPriceType\BaseVariantPriceType::checkUsedDiscount($this->dx_auth->get_role_id() !== false ? $this->dx_auth->get_role_id() : '-1', $item);
            }

            if ($item->originPrice > $item->price || $usedDiscountVariantPrice === false  ) {
                continue;
            }
 $arr_for_discount = [
                                 'product_id'  => $item->getSProducts()->getId(),
                                 'category_id' => $item->getSProducts()->getCategoryId(),
                                 'brand_id'    => $item->getSProducts()->getBrandId(),
                                 'vid'         => $item->id,
                                 'id'          => $item->getSProducts()->getId(),
                                ];
            assetManager::create()->discount = 0;
            if (BaseDiscount::checkModuleInstall()) {
                Discount_product::create()->getProductDiscount($arr_for_discount);
            }

            if ($discount = assetManager::create()->discount) {			
			//Расчет новой цены в корзине
     $priceNew = ((float) $item->originPrice - (float) $discount['discount_value'] < 0) ? 1 : (float) $item->originPrice - (float) $discount['discount_value'];
                $productData = [
                                'instance' => 'SProducts',
                                'id'       => $item->id,
                               ];
                $cartItem = $cart->getItem($productData);
                $dkey = $discount['discount_max']['key'];
                if ($cartItem['success'] === TRUE) {
                    $cartItem['data']->discountKey = $dkey;
                }
///////// скидка
            $cart->setItemPrice($productData, round($priceNew, ShopCore::app()->SSettings->getPricePrecision()));

                if (!isset($this->appliesControl[$dkey])) {
                    $appliesLeft = BaseDiscount::create()->getAppliesLeft($item->discountKey);
                    if ($appliesLeft === null) {
                        continue;
                    }
                    $this->appliesControl[$dkey] = [
                                                    'appliesLeft'    => $appliesLeft,
                                                    'assumedApplies' => 0,
                                                    'overloadPrice'  => 0.0,
                                                   ];
                }
                // gradually gathering overload (if will be)
                for ($i = 0; $i < $item->quantity; $i++) {
                    if (++$this->appliesControl[$dkey]['assumedApplies'] > $this->appliesControl[$dkey]['appliesLeft']) {
                        $this->appliesControl[$dkey]['overloadPrice'] += $discount['discount_value'];
                        $this->overload += $discount['discount_value'];
                    }
                }
            }
        }
    }

    /**
     * apply user gift
     */
    private function applyGift() {	  
        $key = $this->input->post('gift');
        $aplyGift = false;
        foreach ($this->baseDiscount->discountType['certificate'] as $disc) {
            if ($disc['key'] == $key and $disc['is_gift']) {
///Расчет 
			   $value = $this->baseDiscount->getDiscountValue ($disc, $this->baseDiscount->cart->getTotalPrice );
	      
                $this->baseDiscount->cart->gift_info = $disc['key'];
                $this->baseDiscount->cart->gift_value = Currency::create()->convertFloor($value);
               if (\ShopCore::app()->SSettings->getPricePrecision() == 0) {
                 $this->baseDiscount->cart->gift_value = floor($value);               }
	$cartTotalPrice = $this->baseDiscount->cart->getTotalPrice() - $value;
                //Выводит конечную сумму
				$this->baseDiscount->cart->setTotalPrice($cartTotalPrice > 0 ? $cartTotalPrice : BaseCart::MIN_ORDER_PRICE);
		$aplyGift = true;
                break;
            }
        }

        if (!$aplyGift) {
            $this->baseDiscount->cart->gift_error = TRUE;
        }
    }
}
/* End of file mod_discount.php */
  • Вопрос задан
  • 295 просмотров
Решения вопроса 1
myks92
@myks92 Куратор тега PHP
Нашёл решение — пометь вопрос ответом!
Используйте более приятную кодом корзину. И проблем не будет. Там можно любые калькуляторы делать. Написана на чистом php. В вашем коде сложно разобраться даже и что-то подсказать. Код не читаем.
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы