Maintain inventory for a product bundle, with Mechanic.

Mechanic is a development and ecommerce automation platform for Shopify. :)

Maintain inventory for a product bundle

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, and with quantities needed from each component for each bundle unit, this task keeps the bundle inventory set to the greatest possible value, given the quantities of its components. It also appropriately subtracts from component inventory whenever the bundle is ordered, and appropriately raises component inventory when a bundle order is refunded.

Runs Occurs whenever an order is created, Occurs whenever a new refund is created without errors on an order, independent from the movement of money, Occurs whenever an inventory level is updated, and Occurs when a user manually triggers the task. Configuration includes bundle product sku, component product skus and quantities per bundle, and inventory buffer quantity.

15-day free trial – unlimited tasks

Documentation

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, and with quantities needed from each component for each bundle unit, this task keeps the bundle inventory set to the greatest possible value, given the quantities of its components. It also appropriately subtracts from component inventory whenever the bundle is ordered, and appropriately raises component inventory when a bundle order is refunded.

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 only considers inventory from the default location configured in the shop.
  • Configure this task with a unique SKU for the bundle product. The bundle product SKU must not be re-used by any other products.
  • This task can sync inventory across multiple product variants sharing the same component SKU. But, if a single SKU is used for multiple variants in the same store, all such variants must start with and maintain equal inventory levels.
  • Use the right-hand side of the "Component product SKUs and quantities per bundle" option to control how many units of each component SKU is required for each single bundle unit. If your bundle requires one wrench and two sprockets, for example, make sure to add "1" and "2" on the right-hand side, each number associated with the right SKU.

Notes:

  • Whenever this task runs, any inventory updates to the bundle product will be overwritten. For the purposes of this task, the bundle's inventory is exclusively derived from the inventory of its components. (This also means that this task does not support "nested" bundles, in which a bundle component product is itself a bundle managed by another copy of this task.)
  • Feel free to manually adjust inventory for component products, keeping in mind that components with shared SKUs must be kept equal to each other. The bundle product's inventory will be synced appropriately.
  • Use the "Inventory buffer quantity" option to artificially keep the bundle product's inventory lower than the actual available quantity.

Developer details

Mechanic is designed to benefit everybody: merchants, customers, developers, agencies, Shopifolks, 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.

(By the way, have you seen our documentation? Have you joined the Slack community?)

Open source
View on GitHub to contribute to this task
Subscriptions
shopify/orders/create
shopify/refunds/create
shopify/inventory_levels/update
mechanic/user/trigger
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
bundle product sku (required), component product skus and quantities per bundle (keyval, number, required), inventory buffer quantity (number)
Code
{% assign bundle_sku = options.bundle_product_sku__required %}
{% assign component_skus_and_quantities = options.component_product_skus_and_quantities_per_bundle__keyval_number_required %}
{% assign component_skus = component_skus_and_quantities | keys %}
{% assign all_skus = array | push: bundle_sku | concat: component_skus %}

{% assign variants_by_sku = hash %}

{% assign primary_location = shop.locations[shop.primary_location_id] %}

{% log
  primary_location: primary_location,
  bundle_sku: bundle_sku,
  component_skus_and_quantities: component_skus_and_quantities,
  inventory_buffer_quantity: options.inventory_buffer_quantity__number
%}

{% assign do_full_sync = false %}
{% assign do_component_adjustment = false %}
{% assign component_adjustment_bundle_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_bundle_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_bundle_quantity = bundle_restock_quantity %}
{% endif %}

{% if event.topic contains "shopify/inventory_levels/" %}
  {% 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 %}
    {% assign log_message = updated_sku | json | prepend: "Inventory was updated for SKU " | append: ", which is not related to this bundle." %}
    {% log log_message %}
  {% endif %}
{% endif %}

{% if do_component_adjustment or do_full_sync %}
  {% assign query_components = array %}

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

  {% for n in (0..500) %}
    {% assign cursor = nil %}

    {% capture query %}
      query {
        productVariants(
          first: 150
          query: {{ query_components | join: " OR " | json }}
          after: {{ cursor | json }}
        ) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            sku
            inventoryItem {
              id
              inventoryLevel(locationId: {{ primary_location.admin_graphql_api_id | json }}) {
                id
                quantities(names: "available") {
                  name
                  quantity
                }
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "productVariants": {
              "nodes": [
                {
                  "sku": {{ bundle_sku | json }},
                  "inventoryItem": {
                    "id": "gid://shopify/InventoryItem/1234567890",
                    "inventoryLevel": {
                      "id": "gid://shopify/InventoryLevel/1234567890?x=bundle&sku={{ bundle_sku }}&inventory_item_id=1234567890",
                      "quantities": [
                        {
                          "name": "available",
                          "quantity": 2
                        }
                      ]
                    }
                  }
                },
                {% for component_sku in component_skus %}
                  {
                    "sku": {{ component_sku | json }},
                    "inventoryItem": {
                      "id": "gid://shopify/InventoryItem/2345678901",
                      "inventoryLevel": {
                        "id": "gid://shopify/InventoryLevel/2345678901?x=component&sku={{ component_sku }}&inventory_item_id=2345678901",
                        "quantities": [
                          {
                            "name": "available",
                            "quantity": 1
                          }
                        ]
                      }
                    }
                  }
                  {% unless forloop.last %},{% endunless %}
                {% endfor %}
              ]
            }
          }
        }
      {% endcapture %}

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

    {% for variant in result.data.productVariants.nodes %}
      {% assign variants_by_sku[variant.sku]
        = variants_by_sku[variant.sku]
        | default: array
        | push: variant
      %}
    {% endfor %}

    {% if result.data.productVariants.pageInfo.hasNextPage %}
      {% assign cursor = result.data.productVariants.pageInfo.endCursor %}
    {% else %}
      {% break %}
    {% endif %}
  {% endfor %}

  {% if variants_by_sku[bundle_sku].size != 1 %}
    {% error
      message: "Did not find exactly one variant for the provided bundle SKU. This task does not support re-use of the bundle SKU across multiple variants.",
      bundle_sku: bundle_sku,
      bundle_variants: variants_by_sku[bundle_sku]
    %}
  {% endif %}

  {% for component_sku in component_skus %}
    {% if variants_by_sku[component_sku] == blank %}
      {% error
        message: "Didn't find any variants for a component SKU. Each component SKU must have at least one variant.",
        component_sku: component_sku
      %}
    {% endif %}
  {% endfor %}

  {% log bundle_variant: variants_by_sku[bundle_sku][0], all_variants_by_sku: variants_by_sku %}
{% endif %}

{% if do_component_adjustment %}
  {% assign inventory_adjustments = array %}

  {% for keyval in variants_by_sku %}
    {% assign sku = keyval[0] %}
    {% assign variants = keyval[1] %}
    {% assign expected_inventory_quantity = variants[0].inventoryItem.inventoryLevel.quantities.first.quantity %}

    {% for variant in variants %}
      {% if variant.inventoryItem.inventoryLevel.quantities.first.quantity != expected_inventory_quantity %}
        {% error
          message: "Expected all variants for a single SKU to have matching inventory levels, but they did not - can't continue. Please manually sync inventory for all variants sharing this SKU, and try again.",
          sku: sku,
          variants: variants
        %}
      {% endif %}

      {% assign variant_delta = component_adjustment_bundle_quantity | times: component_skus_and_quantities[variant.sku] %}

      {% if variant_delta != 0 %}
        {% assign inventory_adjustment = hash %}
        {% assign inventory_adjustment["inventoryItemId"] = variant.inventoryItem.id %}
        {% assign inventory_adjustment["locationId"] = primary_location.admin_graphql_api_id %}
        {% assign inventory_adjustment["delta"] = variant_delta %}
        {% assign inventory_adjustments = inventory_adjustments | push: inventory_adjustment %}
      {% endif %}
    {% endfor %}
  {% endfor %}

  {% if inventory_adjustments != blank %}
    {% action "shopify" %}
      mutation {
        inventoryAdjustQuantities(
          input: {
            reason: "correction"
            name: "available"
            changes: {{ inventory_adjustments | graphql_arguments }}
          }
        ) {
          inventoryAdjustmentGroup {
            reason
            changes {
              name
              delta
              quantityAfterChange
              item {
                id
                sku
              }
              location {
                name
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}
{% endif %}

{% if do_full_sync %}
  {% comment %}
    Initialize some variables:
    * minimum_inventory_component_variant: the single component variant that, when its bundle quantity
        multiplier is factored in, represents the smallest number of bundles that can be constructed
        with the variant inventory on hand. (for example, given 3 widgets per bundle, if we find a widget
        variant with an inventory of 5 and another one with inventory 6, the *first* one is the minimum
        inventory component variant, because it pulls down the max number of bundles from 2 to 1.)
    * minimum_inventory_component_variant_bundle_quantity: the number of bundles that can be safely
        constructed, given the smallest proportionate inventory value found across all component variants.
    * bundle_variant: the bundle variant (remember, we only support one - no SKU sharing for bundles). we'll
        use this variant to perform any inventory updates needed to the bundle itself.
  {% endcomment %}
  {% assign minimum_inventory_component_variant = nil %}
  {% assign minimum_inventory_component_variant_bundle_quantity = nil %}
  {% assign bundle_variant = nil %}

  {% for pair in variants_by_sku %}
    {% assign sku = pair[0] %}
    {% assign variants = pair[1] %}
    {% assign expected_inventory_quantity = variants[0].inventoryItem.inventoryLevel.quantities.first.quantity %}

    {% for variant in variants %}
      {% if variant.inventoryItem.inventoryLevel.quantities.first.quantity != expected_inventory_quantity %}
        {% assign error_message = "Expected all " | append: sku | append: " variants to have an inventory quantity of " | append: expected_inventory_quantity | append: ", but not every variant is at this level. Ensure every variant is in sync, and try again." %}
        {% error error_message %}
      {% endif %}

      {% if variant.sku == bundle_sku %}
        {% assign bundle_variant = variant %}

      {% elsif component_skus contains variant.sku %}
        {% assign variant_bundle_quantity
          = variant.inventoryItem.inventoryLevel.quantities.first.quantity
          | times: 1.0
          | divided_by: component_skus_and_quantities[variant.sku]
        %}

        {% if minimum_inventory_component_variant == nil or minimum_inventory_component_variant_bundle_quantity > variant_bundle_quantity %}
          {% assign minimum_inventory_component_variant = variant %}
          {% assign minimum_inventory_component_variant_bundle_quantity = variant_bundle_quantity %}
        {% endif %}
      {% endif %}
    {% endfor %}
  {% endfor %}

  {% assign bundle_delta
    = minimum_inventory_component_variant_bundle_quantity
    | floor
    | minus: bundle_variant.inventoryItem.inventoryLevel.quantities.first.quantity
  %}

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

  {% log
    bundle_variant: bundle_variant,
    minimum_inventory_component_variant_sku: minimum_inventory_component_variant.sku,
    minimum_inventory_component_variant_quantity: minimum_inventory_component_variant.inventoryItem.inventoryLevel.quantities.first.quantity, minimum_inventory_component_variant_bundle_quantity: minimum_inventory_component_variant_bundle_quantity,
    inventory_buffer_quantity: options.inventory_buffer_quantity__number,
    available_delta: bundle_delta
  %}

  {% if bundle_delta == 0 %}
    {% log "Lowest quantity component SKU had an inventory that was appropriate for the bundle's current inventory. No change needed." %}

  {% else %}
    {% action "shopify" %}
      mutation {
        inventoryAdjustQuantities(
          input: {
            reason: "correction"
            name: "available"
            changes: [
              {
                inventoryItemId: {{ bundle_variant.inventoryItem.id | json }}
                locationId: {{ primary_location.admin_graphql_api_id | json }}
                delta: {{ bundle_delta }}
              }
            ]
          }
        ) {
          inventoryAdjustmentGroup {
            reason
            changes {
              name
              delta
              quantityAfterChange
              item {
                id
                sku
              }
              location {
                name
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Bundle product SKU
BUNDLE
Component product SKUs and quantities per bundle
{"BUNDLE-A"=>1, "BUNDLE-B"=>2, "BUNDLE-C"=>3}
Inventory buffer quantity
1