> For the complete documentation index, see [llms.txt](https://integrate.skio.com/skio/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://integrate.skio.com/skio/rules/apply-volume-discounts.md).

# Apply Volume Discounts

## Front End Script&#x20;

Below is the front-end code that will fetch a list of rules from the Skio API and select the eligible volume discount rule that would apply. Upon hitting the checkout button, a discount code will automatically be added to the cart to apply the volume discount.&#x20;

{% hint style="info" %}
For Shopify Plus, we recommend creating a custom script that matches the setup in Skio to automatically apply the discount.

Volume discounts will be updated to use Shopify Functions, which will work for both Plus and non-Plus merchants in the near future.&#x20;
{% endhint %}

***

Create this file `assets/skio-volume-discount.js` and copy in the large code block below.&#x20;

On all pages that have a checkout button, make sure to include this script using this script include.

```html
<script src="{{ 'skio-volume-discount.js' | asset_url }}" defer></script>
```

{% hint style="warning" %}
Make sure that the <mark style="color:blue;">`selector`</mark>will match all checkout buttons
{% endhint %}

{% code title="skio-volume-discount.js" %}

```javascript
 /**
 * Setup: add the below script include to pages that have a checkout button
 * 
 * <script src="{{ 'skio-volume-discount.js' | asset_url }}" defer="defer"></script>
 * 
 * Make sure the selector below covers all checkout buttons
 */

// scope variables
(() => {
  const selector = '#checkout'
  
  const checkoutHandler = async (event) => {
    if (!window.skio_ran_tier_discount && event.target.matches(selector)) {
      event.preventDefault()
  
      // Get Skio rules and the current cart
      const [{rules}, cart] = await Promise.all([
        (await fetch(`https://api.skio.com/storefront-http/get-rules-by-domain-or-hostname?domain=${window?.Shopify?.shop}`)).json(), 
        (await fetch('/cart.js')).json()
      ])
    
      // console.log('rules', rules)
      // console.log('cart', cart)
    
      // Check each rule to find the eligible rule 
      // with the largest min quantity
      let largestMinQuantity = {
        value: -1,
        index: -1,
      }
      rules.forEach((rule, index) => {
        if (rule.code &&
            largestMinQuantity.value < rule.minQuantityToDiscount
        ) {
          // Gets the count of eligible items in the cart for this rule
          const eligibleCount = cart.items.reduce(
            (aggregate, item) => rule.productVariantIds.some(gid => gid.includes(item.id)) ? 
                aggregate + item.quantity : aggregate 
            , 0)
          if (rule.minQuantityToDiscount <= eligibleCount) {
            largestMinQuantity.value = rule.minQuantityToDiscount
            largestMinQuantity.index = index
          }
        }
      })
    
      const rule = largestMinQuantity.index > -1 ? rules[largestMinQuantity.index] : null
      // console.log(rule)
      
      // Apply code
      if (rule) await fetch(`/discount/${rule.code}`)
      
      window.skio_ran_tier_discount = true
      
      event.target.click()
    }
  }
  
  // Event delegation
  document.body.addEventListener('click', checkoutHandler)
})()
```

{% endcode %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://integrate.skio.com/skio/rules/apply-volume-discounts.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
