Prevent Discount code on selected items

aamirch
Shopify Partner
12 0 0

Hello,
             I am running script base discount which is applying on selected variants_id. i am trying to  prevent the discount code apply on variants (mention in script), so that already discounted variants not get another discount. for this is i set key property for line_items when applying discount. which set successfully. i can see key value in cart page.
however when I run my code (which check each lime_item if match with key value then reject the discount code) is fail to execute. its seems not find lime_item key, but key is there. here is my code

this is the code where I am setting line item key , and it set successfully , I can see in cart page

class DiscountApplicator
  def initialize(discount_type, discount_amount, discount_message)
    @discount_type = discount_type
    @discount_message = discount_message

    @discount_amount = if discount_type == :percent
      1 - (discount_amount * 0.01)
    else
      Money.new(cents: 100) * discount_amount
    end
  end

  def apply(line_item)
    new_line_price = if @discount_type == :percent
      line_item.line_price * @discount_amount
    else
      [line_item.line_price - (@discount_amount * line_item.quantity), Money.zero].max
    end

    line_item.change_line_price(new_line_price, message: @discount_message)
    line_item.change_properties({
            'key' => '_saleitem'
          },{ message: 'Updated value' }) 
  end
  
end

 

and below is the code where I am checking if key value _saleitem found, then stop executing discount code.

CART_REJECTION_MESSAGE = "Cannot Use Discount Code on Sale Items"
product=''
condition_is_met = false
if Input.cart.discount_code != nil
  Input.cart.line_items.each do |line_item|
    product = line_item.properties
    if product.key?('_saleitem')
   condition_is_met = true
    end
  end
end

if condition_is_met
  Input.cart.discount_code.reject({
    message: CART_REJECTION_MESSAGE
  })
end

 the issue is "condition_is_met = true" is not executing even key exists (_saleitem) which I can see in cart page as well. any idea what is wrong ? your help will be appreciated.

Replies 0 (0)