Mechanic Get Mechanic
Task library

Sync inventory across a product type

Useful for custom orders, this task lets you offer multiple product and variant listings for what is ultimately the same stock. A purchase for a single product leads to the inventory for all other listings, of the same product type, being lowered by the amount ordered.

Try this task

When it runs

  • Occurs when a user manually triggers the task
  • Occurs every 10 minutes

What you choose

  • Product types to monitor
  • Only sync active products

Documentation

Useful for custom orders, this task lets you offer multiple product and variant listings for what is ultimately the same stock. A purchase for a single product leads to the inventory for all other listings, of the same product type, being lowered by the amount ordered.

Getting started

  1. Populate the list of product types that you'd like this task to monitor.
  2. In the Shopify admin, navigate to the Products > Inventory area. For the first product type that you've chosen, search for all inventory items with that specific type, and ensure that all inventory items have the same "available" level. Repeat for each additional product type you're using.
  3. Back in Mechanic, click the "Run task" button. Mechanic will scan your product types, and cache the current available inventory for each one.
  4. Wait! :) Every ten minutes, Mechanic will check your inventory, and make any adjustments necessary to keep everything in sync. For example, if three different inventory items - within the same product type - are each sold three different times, Mechanic will ensure that each of those items are lowered by a further 6, and that all others are lowered by 9.

Notes

  • This task only counts and adjusts available inventory at the default location configured in Shopify.
  • By default, Mechanic will check your inventory every 10 minutes. Feel free to change that subscription to "mechanic/scheduler/hourly", or something else that suits your needs.
Task code and subscriptions

You can edit the Liquid code after installing this task. View on GitHub or ask a question in the Mechanic Slack community.

Subscriptions

mechanic/user/trigger
mechanic/scheduler/10min
How task subscriptions work

Option types and flags

Task code

{% assign product_types = options.product_types_to_monitor__array_required %}
{% assign only_sync_active_products = options.only_sync_active_products__boolean %}

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

{% if event.topic == "mechanic/user/trigger" %}
  {% for product_type in product_types %}
    {% assign available_quantites = array %}
    {% assign cursor = nil %}

    {% capture search_query -%}
      location_id:{{ shop.primary_location_id }} product_type:{{ product_type | json }} managed:true
    {%- endcapture %}

    {% if only_sync_active_products %}
      {% assign search_query = search_query | append: " product_status:active" %}
    {% endif %}

    {% for n in (0..200) %}
      {% capture query %}
        query {
          productVariants(
            first: 200
            query: {{ search_query | json }}
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              inventoryItem {
                id
                inventoryLevel(locationId: {{ primary_location.admin_graphql_api_id | json }}) {
                  quantities(names: "available") {
                    name
                    quantity
                  }
                }
              }
            }
          }
        }
      {% endcapture %}

      {% assign result = query | shopify %}

      {% if event.preview %}
        {% capture result_json %}
          {
            "data": {
              "productVariants": {
                "nodes": [
                  {
                    "id": "gid://shopify/ProductVariant/1234567890",
                    "inventoryItem": {
                      "inventoryLevel": {
                        "quantities": [
                          {
                            "name": "available",
                            "quantity": 30
                          }
                        ]
                      }
                    }
                  },
                  {
                    "id": "gid://shopify/ProductVariant/2345678901",
                    "inventoryItem": {
                      "inventoryLevel": {
                        "quantities": [
                          {
                            "name": "available",
                            "quantity": 30
                          }
                        ]
                      }
                    }
                  }
                ]
              }
            }
          }
        {% endcapture %}

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

      {% for variant in result.data.productVariants.nodes %}
        {% assign available_quantites = available_quantites | push: variant.inventoryItem.inventoryLevel.quantities.first.quantity %}
      {% endfor %}

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

    {% assign inventory_total = available_quantites | sum %}
    {% assign expected_inventory_total = available_quantites.first | times: available_quantites.size %}

    {% if inventory_total != expected_inventory_total %}
      {% error
        message: "Not all inventory levels are in sync. Manually ensure everything is at the same level, then try again.",
        product_type: product_type,
        expected_inventory_total: expected_inventory_total,
        inventory_total: inventory_total,
        available_quantites: available_quantites
      %}

    {% else %}
      {% assign cache_key = "inventory_by_product_type:" | append: product_type | sha256 %}
      {% action "cache", "set", cache_key, available_quantites.first %}
    {% endif %}
  {% endfor %}

{% elsif event.topic contains "mechanic/scheduler/" %}
  {% for product_type in product_types %}
    {% assign cache_key = "inventory_by_product_type:" | append: product_type | sha256 %}
    {% assign inventory_old = cache[cache_key] %}

    {% if event.preview %}
      {% assign inventory_old = 30 %}
    {% endif %}

    {% if inventory_old == blank %}
      {% error
        message: "The inventory for this product type has not yet been cached. Manually synchronize the inventory for this product type and run this task manually per steps 2 and 3 in the task instructions.",
        product_type: product_type
      %}
    {% endif %}

    {% assign variants = array %}
    {% assign available_quantites = array %}
    {% assign cursor = nil %}

    {% capture search_query -%}
      location_id:{{ shop.primary_location_id }} product_type:{{ product_type | json }} managed:true
    {%- endcapture %}

    {% if only_sync_active_products %}
      {% assign search_query = search_query | append: " product_status:active" %}
    {% endif %}

    {% for n in (0..200) %}
      {% capture query %}
        query {
          productVariants(
            first: 200
            query: {{ search_query | json }}
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              id
              sku
              inventoryItem {
                id
                inventoryLevel(locationId: {{ primary_location.admin_graphql_api_id | json }}) {
                  quantities(names: "available") {
                    name
                    quantity
                  }
                }
              }
            }
          }
        }
      {% endcapture %}

      {% assign result = query | shopify %}

      {% if event.preview %}
        {% capture result_json %}
          {
            "data": {
              "productVariants": {
                "nodes": [
                  {
                    "id": "gid://shopify/ProductVariant/1234567890",
                    "inventoryItem": {
                      "id": "gid://shopify/InventoryItem/1234567890",
                      "inventoryLevel": {
                        "quantities": [
                          {
                            "name": "available",
                            "quantity": 25
                          }
                        ]
                      }
                    }
                  },
                  {
                    "id": "gid://shopify/ProductVariant/2345678901",
                    "inventoryItem": {
                      "id": "gid://shopify/InventoryItem/2345678901",
                      "inventoryLevel": {
                        "quantities": [
                          {
                            "name": "available",
                            "quantity": 31
                          }
                        ]
                      }
                    }
                  }
                ]
              }
            }
          }
        {% endcapture %}

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

      {% assign variants = result.data.productVariants.nodes | concat: variants %}

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

    {% for variant in variants %}
      {% assign available_quantites = available_quantites | push: variant.inventoryItem.inventoryLevel.quantities.first.quantity %}
    {% endfor %}

    {% assign inventory_total_old = inventory_old | times: available_quantites.size %}
    {% assign inventory_total_new = available_quantites | sum %}
    {% assign inventory_total_diff = inventory_total_new | minus: inventory_total_old %}
    {% assign inventory_new = inventory_old | plus: inventory_total_diff %}

    {% log
      inventory_old: inventory_old,
      inventory_total_old: inventory_total_old,
      inventory_total_new: inventory_total_new,
      inventory_total_diff: inventory_total_diff,
      inventory_new: inventory_new,
      product_type: product_type,
      variants_count: variants.size,
      variants: variants
    %}

    {% if inventory_new == inventory_old %}
      {% log "No inventory adjustments needed for this product type." %}
      {% continue %}
    {% endif %}

    {% action "cache", "set", cache_key, inventory_new %}

    {% assign inventory_adjustments = array %}

    {% for variant in variants %}
      {% 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"] = inventory_new | minus: variant.inventoryItem.inventoryLevel.quantities.first.quantity %}
      {% assign inventory_adjustment["changeFromQuantity"] = variant.inventoryItem.inventoryLevel.quantities.first.quantity %}
      {% assign inventory_adjustments = inventory_adjustments | push: inventory_adjustment %}
    {% endfor %}

    {% comment %}
      -- changeFromQuantity field is required as of 2026-04
      https://shopify.dev/changelog/making-changefromquantity-field-required
      -- Shopify will enforce idempotency for several mutations as of 2026-04
      https://shopify.dev/changelog/making-idempotency-mandatory-for-inventory-adjustments-and-refund-mutations
    {% endcomment %}

    {% if inventory_adjustments != blank %}
      {% assign groups_of_inventory_adjustments = inventory_adjustments | in_groups_of: 250, fill_with: false %}

      {% for group_of_inventory_adjustments in groups_of_inventory_adjustments %}
        {% capture idempotent_key %}
          {
            "task_id": {{ task.id | json }},
            "event_id": {{ event.id | json }},
            "data": {{ group_of_inventory_adjustments | json }}
          }
        {% endcapture %}

        {% action "shopify" %}
          mutation {
            inventoryAdjustQuantities(
              input: {
                reason: "correction"
                name: "available"
                changes: {{ group_of_inventory_adjustments | graphql_arguments }}
              }
            ) @idempotent(key: {{ idempotent_key | json | md5 | json }}) {
              inventoryAdjustmentGroup {
                reason
                changes(quantityNames: "available") {
                  name
                  delta
                  item {
                    id
                    sku
                  }
                  location {
                    name
                  }
                }
              }
              userErrors {
                code
                field
                message
              }
            }
          }
        {% endaction %}
      {% endfor %}
    {% endif %}
  {% endfor %}
{% endif %}
Mechanic Liquid reference

Default option values

Only sync active products
true