Syncing Quantities Using Shopify Scripts

Utilizing Shopify Scripts to Remove Detached Warranties and Sync Quantities

Overview

Within the Mulberry SDK, functionality exists to remove detached warranties and sync quantities. However, it really makes more sense to take care of this kind of logic on the back end. Shopify Scripts provides a way for Shopify developers to implement specific back-end behaviors.

Using Shopify Scripts, you can add an additional layer of certainty around Mulberry warranties that are being sold, ensuring that it is fully impossible to end up with a cart that contains a stray warranty or mismatched quantities.

The script provided here will run any time a product or warranty is added or removed from cart and whenever a product quantity is changed.

1. Install Shopify Scripts

Shopify Scripts is developed by Shopify and available to Shopify Plus retailers in the app store. To install, simply add the Script Editor app from the Shopify App store.

2. Creating the Mulberry Script

  1. In your Shopify admin, navigate to Apps > Script Editor.

  2. Click "Create Script" in the top right corner.

  3. In "Line Items", select "Blank Template" and click "Create Script" as illustrated in the below image.

12541254
  1. At the top, click into the title box and insert: "Mulberry - Removing Detached Warranties and Syncing Quantities".

  2. Click "Code" and paste the following snippet into the Ruby Source Code text box, replacing any of the existing contents. Your input boxes should look like the image below.

line_item_quantities = {}

Input.cart.line_items.each do |line_item|
  variant = line_item.variant
  variant_id = variant.id
  quantity = line_item.quantity
  line_item_quantities[variant_id] = quantity
end

Input.cart.line_items.each do |line_item|
  product = line_item.variant.product
  next if product.vendor != "Mulberry"
  variant_id = line_item.variant.id
  properties = line_item.properties
  if properties.key?("_variantId")
    associated_variant_id = properties["_variantId"].to_i
    if line_item_quantities.key?(associated_variant_id)
      associated_variant_quantity = line_item_quantities[associated_variant_id]
      warranty_quantity = line_item.quantity
      if warranty_quantity != associated_variant_quantity
        line_item.instance_variable_set(:@quantity, associated_variant_quantity)
      end
    else
      line_item.instance_variable_set(:@quantity, 0)
    end
  else
    line_item.instance_variable_set(:@quantity, 0)
  end
end

Output.cart = Input.cart
15301530
  1. Save and publish. That's all, now your cart quantity syncing will be automatically handled by the script set up in the script editor.