Maintain inventory for a product bundle, with Mechanic.

Mechanic is a development platform for Shopify. :)

Maintain inventory for a product bundle

by Isaac Bowen (team@usemechanic.com)

Use this task to automatically sync inventory for a simple product bundle – no theme modifications required. When configured with unique SKUs for the bundle and its components, this task keeps the bundle inventory equal to the lowest inventory level of its component products, and appropriately subtracts from component inventory whenever the bundle is ordered. When a bundle order is refunded, the components are raised back up, appropriately.

Runs when an order is created, when a refund is created, when an inventory level is updated, and when a user triggers the task. Configuration includes bundle product sku, component product skus, and inventory buffer quantity.

15-day free trial – unlimited tasks

Documentation

Usage:

  • Run this task manually to sync the bundle's inventory with that of the component product that has the least inventory in stock.
  • This task will run automatically whenever the bundle product is ordered, and whenever the bundle product is refunded in such a way that it is restocked.

Requirements:

  • This task does not support multiple inventory locations.
  • Configure this task with unique SKUs for the bundle product and its component products. These SKUs must not be re-used for any other product variants in your store. However, any component SKU may be used for multiple copies of this task.

Notes:

  • Whenever this task runs, manual inventory updates to the bundle product will be overwritten.
  • Feel free to manually adjust inventory for component products. The bundle product's inventory will be synced appropriately.
  • Use the "Inventory buffer quantity" option to keep the bundle's inventory lower than its lowest component product's inventory, by whatever amount you prefer.

Developer details

Mechanic is designed to benefit everybody: merchants, customers, developers, agencies, Gurus, everybody.

That’s why we make it easy to configure automation without code, why we make it easy to tweak the underlying code once tasks are installed, and why we publish it all here for everyone to learn from.

Events
when an order is created (shopify/orders/create)
when a refund is created (shopify/refunds/create)
when an inventory level is updated (shopify/inventory_levels/update)
when a user triggers the task (mechanic/user/trigger)
Options
bundle product sku (required), component product skus (array, required), inventory buffer quantity (number)
Script
{% assign bundle_sku = options.bundle_product_sku__required %}
{% assign component_skus = options.component_product_skus__array_required %}
{% assign all_skus = component_skus | join: "|||" | prepend: "|||" | prepend: bundle_sku | split: "|||" %}

{% if component_skus.size > 249 %}
  {% error %}
    {{ "This task only supports up to 249 component product SKUs. You've added " | append: component_skus.size | append: "." | json }}
  {% enderror %}
{% endif %}

{% assign do_full_sync = false %}
{% assign do_component_adjustment = false %}
{% assign component_adjustment_quantity = nil %}

{% if event.topic == "mechanic/user/trigger" %}
  {% assign do_full_sync = true %}
{% endif %}

{% if event.topic == "shopify/orders/create" %}
  {% if event.preview %}
    {% capture order_json %}
      {
        "line_items": [
          {
            "sku": {{ bundle_sku | json }},
            "quantity": 1
          }
        ]
      }
    {% endcapture %}

    {% assign order = order_json | parse_json %}
  {% endif %}

  {% assign bundle_quantity = order.line_items | where: "sku", bundle_sku | map: "quantity" | sum %}
  {% if bundle_quantity != 0 %}
    {% assign do_component_adjustment = true %}
    {% assign component_adjustment_quantity = bundle_quantity | times: -1 %}
  {% endif %}
{% endif %}

{% if event.topic == "shopify/refunds/create" %}
  {% if event.preview %}
    {% capture refund_json %}
      {
        "refund_line_items": [
          {
            "quantity": 1,
            "restock_type": "cancel",
            "line_item": {
              "quantity": 1,
              "sku": {{ bundle_sku | json }}
            }
          }
        ]
      }
    {% endcapture %}

    {% assign refund = refund_json | parse_json %}
  {% endif %}

  {% assign bundle_restock_quantity = 0 %}

  {% for refund_line_item in refund.refund_line_items %}
    {% if refund_line_item.line_item.sku == bundle_sku and refund_line_item.restock_type != "no_restock" %}
      {% assign do_component_adjustment = true %}
      {% assign bundle_restock_quantity = bundle_restock_quantity | plus: refund_line_item.quantity %}
    {% endif %}
  {% endfor %}

  {% assign component_adjustment_quantity = bundle_restock_quantity %}
{% endif %}

{% if event.topic contains "shopify/inventory_levels/" %}
  {% comment %}
    Note: we don't use the "available" figure that comes in with this payload,
    to guard against receiving webhooks in the wrong order, or a delay in event
    processing.
  {% endcomment %}

  {% capture query %}
    query {
      inventoryLevel(id: {{ inventory_level.admin_graphql_api_id | json }}) {
        item {
          variant {
            sku
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "inventoryLevel": {
            "item": {
              "variant": {
                "sku": {{ component_skus.first | json }}
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = result_json | parse_json %}
  {% endif %}

  {% assign updated_sku = result.data.inventoryLevel.item.variant.sku %}

  {% if all_skus contains updated_sku %}
    {% assign do_full_sync = true %}
  {% else %}
    {% log %}
      {{ updated_sku | json | prepend: "Inventory was updated for SKU " | append: ", which is not related to this bundle." | json }}
    {% endlog %}
  {% endif %}
{% endif %}

{% if do_component_adjustment %}
  {% assign query_components = array %}
  {% for sku in component_skus %}
    {% assign query_components[query_components.size] = sku | json | prepend: "sku:" %}
  {% endfor %}

  {% capture query %}
    query {
      productVariants(
        first: {{ component_skus.size | json }}
        query: {{ query_components | join: " OR " | json }}
      ) {
        edges {
          node {
            inventoryItem {
              inventoryLevels(first: 1) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            sku
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "productVariants": {
            "edges": [
              {% for sku in component_skus %}
                {
                  "node": {
                    "inventoryItem": {
                      "inventoryLevels": {
                        "edges": [
                          {
                            "node": {
                              "id": "gid://shopify/InventoryLevel/1234567890?inventory_item_id=1234567890"
                            }
                          }
                        ]
                      }
                    },
                    "sku": {{ sku | json }}
                  }
                }
                {% unless forloop.last %},{% endunless %}
              {% endfor %}
            ]
          }
        }
      }
    {% endcapture %}

    {% assign result = result_json | parse_json %}
  {% endif %}

  {% assign variants = result.data.productVariants.edges | map: "node" %}
  {% assign found_skus = variants | map: "sku" | uniq %}

  {% if variants.size != component_skus.size or found_skus.size != variants.size %}
    {% error %}
      {{ "Expected to find " | append: component_skus.size | append: " matching component product variants with unique SKUs, based on the task configuration, but found " | append: variants.size | append: " matching variants with " | append: found_skus.size | append: " unique SKUs instead. Make sure each SKU for this task only has one associated product in your store." | json }}
    {% enderror %}
  {% endif %}

  {% action "shopify" %}
    mutation {
      {% for variant in variants %}
        inventoryAdjustQuantity{{ forloop.index }}: inventoryAdjustQuantity(
          input: {
            inventoryLevelId: {{ variant.inventoryItem.inventoryLevels.edges.first.node.id | json }}
            availableDelta: {{ component_adjustment_quantity | json }}
          }
        ) {
          inventoryLevel {
            id
            available
            item {
              variant {
                sku
              }
            }
          }
          userErrors {
            field
            message
          }
        }
      {% endfor %}
    }
  {% endaction %}
{% endif %}

{% if do_full_sync %}
  {% assign query_components = array %}
  {% for sku in all_skus %}
    {% assign query_components[query_components.size] = sku | json | prepend: "sku:" %}
  {% endfor %}

  {% capture query %}
    query {
      productVariants(
        first: {{ all_skus.size | json }}
        query: {{ query_components | join: " OR " | json }}
      ) {
        edges {
          node {
            inventoryQuantity
            inventoryItem {
              inventoryLevels(first: 1) {
                edges {
                  node {
                    id
                  }
                }
              }
            }
            sku
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "productVariants": {
            "edges": [
              {
                "node": {
                  "inventoryItem": {
                    "inventoryLevels": {
                      "edges": [
                        {
                          "node": {
                            "id": "gid://shopify/InventoryLevel/1234567890?inventory_item_id=1234567890"
                          }
                        }
                      ]
                    }
                  },
                  "inventoryQuantity": 2,
                  "sku": {{ bundle_sku | json }}
                }
              },
              {% for sku in component_skus %}
                {
                  "node": {
                    "inventoryItem": {
                      "inventoryLevels": {
                        "edges": [
                          {
                            "node": {
                              "id": "gid://shopify/InventoryLevel/1234567890?inventory_item_id=1234567890"
                            }
                          }
                        ]
                      }
                    },
                    "inventoryQuantity": 1,
                    "sku": {{ sku | json }}
                  }
                }
                {% unless forloop.last %},{% endunless %}
              {% endfor %}
            ]
          }
        }
      }
    {% endcapture %}

    {% assign result = result_json | parse_json %}
  {% endif %}

  {% assign variants = result.data.productVariants.edges | map: "node" %}
  {% assign found_skus = variants | map: "sku" | uniq %}

  {% if variants.size != all_skus.size or found_skus.size != variants.size %}
    {% error %}
      {{ "Expected to find " | append: all_skus.size | append: " matching component product variants with unique SKUs, based on the task configuration, but found " | append: variants.size | append: " matching variants with " | append: found_skus.size | append: " unique SKUs instead. Make sure each SKU for this task only has one associated product in your store." | json }}
    {% enderror %}
  {% endif %}

  {% assign minimum_inventory_variant = nil %}
  {% assign bundle_variant = nil %}

  {% for variant in variants %}
    {% if variant.sku == bundle_sku %}
      {% assign bundle_variant = variant %}
    {% elsif component_skus contains variant.sku %}
      {% if minimum_inventory_variant == nil or minimum_inventory_variant.inventoryQuantity > variant.inventoryQuantity %}
        {% assign minimum_inventory_variant = variant %}
      {% endif %}
    {% endif %}
  {% endfor %}

  {% assign delta = minimum_inventory_variant.inventoryQuantity | minus: bundle_variant.inventoryQuantity %}

  {% if options.inventory_buffer_quantity__number != blank %}
    {% assign delta = delta | minus: options.inventory_buffer_quantity__number %}
  {% endif %}

  {% if delta != 0 %}
    {% action "shopify" %}
      mutation {
        inventoryAdjustQuantity(
          input: {
            inventoryLevelId: {{ bundle_variant.inventoryItem.inventoryLevels.edges.first.node.id | json }}
            availableDelta: {{ delta | json }}
          }
        ) {
          inventoryLevel {
            id
            available
            item {
              variant {
                sku
              }
            }
          }
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.