Sync inventory for shared SKUs, with Mechanic.

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

Sync inventory for shared SKUs

This task monitors all variants having a SKU that you configure, and ensures that changes to the available inventory quantity are reflected across all variants sharing that SKU.

Runs Occurs when a user manually triggers the task and Occurs every 10 minutes. Configuration includes product skus to monitor.

15-day free trial – unlimited tasks

Documentation

This task monitors all variants having a SKU that you configure, and ensures that changes to the available inventory quantity are reflected across all variants sharing that SKU.

First, manually set all available inventory quantities to be equal for each of the SKUs you'd like to monitor. Then manually run this task which will then take a snapshot of the current available inventory quantity for your SKUs. When the task automatically runs, every 10 minutes, it will check for changes to inventory, and ensure that the cumulative change for a SKU is reflected across all product variants sharing that SKU.

Note: This task only considers a store's default location when managing inventory.

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
mechanic/user/trigger
mechanic/scheduler/10min
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
product skus to monitor (array, required)
Code
{% assign skus_to_monitor = options.product_skus_to_monitor__array_required %}
{% assign primary_location = shop.locations[shop.primary_location_id] %}

{% assign query_components = array %}

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

{% capture search_query -%}
  location_id:{{ shop.primary_location_id }} AND ({{ query_components  | join: " OR " }})
{%- endcapture %}

{% log search_query: search_query %}

{% if event.preview %}
  {% assign skus_to_monitor = array | push: skus_to_monitor[0] %}
{% endif %}

{% assign variants_by_sku = hash %}
{% assign cursor = nil %}

{% 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",
                "sku": {{ skus_to_monitor[0] | json }},
                "inventoryItem": {
                  "id": "gid://shopify/InventoryItem/1234567890",
                  "inventoryLevel": {
                    "quantities": [
                      {
                        "name": "available",
                        "quantity": {% if event.topic == "mechanic/user/trigger" %}5{% else %}4{% endif %}
                      }
                    ]
                  }
                }
              },
              {
                "id": "gid://shopify/ProductVariant/2345678901",
                "sku": {{ skus_to_monitor[0] | json }},
                "inventoryItem": {
                  "id": "gid://shopify/InventoryItem/2345678901",
                  "inventoryLevel": {
                    "quantities": [
                      {
                        "name": "available",
                        "quantity": {% if event.topic == "mechanic/user/trigger" %}5{% else %}4{% endif %}
                      }
                    ]
                  }
                }
              }
            ]
          }
        }
      }
    {% 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 %}

{% assign unmatched_skus = array %}

{% for sku in skus_to_monitor %}
  {% if variants_by_sku[sku] == blank %}
    {% assign unmatched_skus = unmatched_skus | push: sku %}
  {% endif %}
{% endfor %}

{% if unmatched_skus != blank %}
  {% error
    message: "One or more configured SKUs were not matched in this shop. Please check the task configuration and try again.",
    unmatched_skus: unmatched_skus
  %}
{% endif %}

{% log variants_by_sku: variants_by_sku %}

{% if event.topic == "mechanic/user/trigger" %}
  {% 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 %}
        {% error %}
          {{ "Expected all '" | append: sku | append: "' variants to have an available 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." | json }}
        {% enderror %}
      {% endif %}
    {% endfor %}
  {% endfor %}

  {% for pair in variants_by_sku %}
    {% assign sku = pair[0] %}
    {% assign variants = pair[1] %}

    {% assign cache_key = task.id | append: "-" | append: sku | sha256 %}
    {% action "cache", "set", cache_key, variants[0].inventoryItem.inventoryLevel.quantities.first.quantity %}
  {% endfor %}

{% elsif event.topic contains "mechanic/scheduler/" %}
  {% assign inventory_adjustments = array %}

  {% for sku in skus_to_monitor %}
    {% assign cache_key = task.id | append: "-" | append: sku | sha256 %}
    {% assign cached_inventory_quantity = cache[cache_key] %}

    {% if event.preview %}
      {% assign cached_inventory_quantity = 5 %}
    {% endif %}

    {% if cached_inventory_quantity == nil %}
      {% error %}{{ "Missing a cached inventory quantity for SKU '" | append: sku | append: "'. Make sure all inventory is in sync across all of this task's monitored SKUs, then use the 'Run task' button to cache current inventory quantities." | json }}{% enderror %}
    {% endif %}

    {% assign total_delta = 0 %}
    {% assign deltas = hash %}

    {% for variant in variants_by_sku[sku] %}
      {% assign deltas[variant.id] = variant.inventoryItem.inventoryLevel.quantities.first.quantity | minus: cached_inventory_quantity %}
      {% assign total_delta = total_delta | plus: deltas[variant.id] %}
    {% endfor %}

    {% log sku: sku, total_delta: total_delta %}

    {% for variant in variants_by_sku[sku] %}
      {% assign delta_for_sync = total_delta | minus: deltas[variant.id] %}

      {% if delta_for_sync != 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"] = delta_for_sync %}
        {% assign inventory_adjustments = inventory_adjustments | push: inventory_adjustment %}
      {% endif %}
    {% endfor %}

    {% if total_delta != 0 %}
      {% assign current_inventory_quantity = cached_inventory_quantity | plus: total_delta %}
      {% action "cache", "set", cache_key, current_inventory_quantity %}
    {% endif %}
  {% endfor %}

  {% 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 %}
      {% action "shopify" %}
        mutation {
          inventoryAdjustQuantities(
            input: {
              reason: "correction"
              name: "available"
              changes: {{ group_of_inventory_adjustments | graphql_arguments }}
            }
          ) {
            inventoryAdjustmentGroup {
              reason
              changes {
                name
                delta
                quantityAfterChange
                item {
                  id
                  sku
                }
                location {
                  name
                }
              }
            }
            userErrors {
              code
              field
              message
            }
          }
        }
      {% endaction %}
    {% endfor %}
  {% endif %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more