Sync inventory for shared SKUs, with Mechanic.

Mechanic is an automation development platform for Shopify. :)

Sync inventory for shared SKUs

by Isaac Bowen (team@usemechanic.com)

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

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

15-day free trial – unlimited tasks

Documentation

To set up this task, configure with the SKUs you'd like to monitor, manually synchronize all inventory quantities for those SKUs, then click the "Run task" button. This task will take a snapshot of the current inventory quantity for your SKUs. When the task automatically runs, every 10 minutes, it will check for changes to inventory, and ensure that the total change for a SKU is reflected across all product variants having that SKU.

Note: this task only works for Shopify stores that have a single location for inventory.

YouTube: How this task was made

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 a user triggers the task (mechanic/user/trigger)
every 10 minutes (mechanic/scheduler/10min)
Options
product skus to monitor (array, required)
Script
{% assign skus = options.product_skus_to_monitor__array_required %}

{% assign variants_by_sku = hash %}

{% assign cursor = nil %}

{% for n in (0..100) %}
  {% capture query %}
    query {
      productVariants(
        first: 250
        query: {{ skus | join: " OR sku:" | prepend: "sku:" | json }}
        after: {{ cursor | json }}
      ) {
        pageInfo {
          hasNextPage
        }
        edges {
          cursor
          node {
            id
            sku
            inventoryQuantity
            inventoryItem {
              id
            }
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "productVariants": {
            "edges": [
              {
                "node": {
                  "id": "gid://shopify/ProductVariant/1234567890",
                  "sku": "MEDIUM",
                  "inventoryQuantity": {% if event.topic == "mechanic/user/trigger" %}5{% else %}3{% endif %},
                  "inventoryItem": {
                    "id": "gid://shopify/InventoryItem/1234567890"
                  }
                }
              },
              {
                "node": {
                  "id": "gid://shopify/ProductVariant/2345678901",
                  "sku": "MEDIUM",
                  "inventoryQuantity": {% if event.topic == "mechanic/user/trigger" %}5{% else %}4{% endif %},
                  "inventoryItem": {
                    "id": "gid://shopify/InventoryItem/2345678901"
                  }
                }
              },
              {
                "node": {
                  "id": "gid://shopify/ProductVariant/3456789012",
                  "sku": "MEDIUM",
                  "inventoryQuantity": {% if event.topic == "mechanic/user/trigger" %}5{% else %}5{% endif %},
                  "inventoryItem": {
                    "id": "gid://shopify/InventoryItem/3456789012"
                  }
                }
              }
            ]
          }
        }
      }
    {% endcapture %}

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

  {% for productVariant_edge in result.data.productVariants.edges %}
    {% assign variant = productVariant_edge.node %}

    {% if variants_by_sku[variant.sku] == nil %}
      {% assign variants_by_sku[variant.sku] = array %}
    {% endif %}

    {% assign _count = variants_by_sku[variant.sku].size %}
    {% assign variants_by_sku[variant.sku][_count] = variant %}
  {% endfor %}

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

{% 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].inventoryQuantity %}
    {% for variant in variants %}
      {% if variant.inventoryQuantity != expected_inventory_quantity %}
        {% error %}
          {{ "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." | 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].inventoryQuantity %}
  {% endfor %}
{% elsif event.topic contains "mechanic/scheduler/" %}
  {% for sku in skus %}
    {% 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 %}
    {% assign adjustments = array %}

    {% for variant in variants_by_sku[sku] %}
      {% assign deltas[variant.id] = variant.inventoryQuantity | minus: cached_inventory_quantity %}
      {% assign total_delta = total_delta | plus: deltas[variant.id] %}
    {% endfor %}

    {% for variant in variants_by_sku[sku] %}
      {% assign delta_for_sync = total_delta | minus: deltas[variant.id] %}
      {% if delta_for_sync != 0 %}
        {% capture adjustment %}
          {
            inventoryItemId: {{ variant.inventoryItem.id | json }}
            availableDelta: {{ delta_for_sync | json }}
          }
        {% endcapture %}
        {% assign adjustments[adjustments.size] = adjustment %}
      {% endif %}
    {% endfor %}

    {% if adjustments != empty %}
      {% action "shopify" %}
        mutation {
          inventoryBulkAdjustQuantityAtLocation(
            inventoryItemAdjustments: [
              {{ adjustments | join: newline }}
            ]
            locationId: "gid://shopify/Location/{{ shop.primary_location_id }}"
          ) {
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}

    {% if total_delta != 0 %}
      {% assign current_inventory_quantity = cached_inventory_quantity | plus: total_delta %}
      {% action "cache", "set", cache_key, current_inventory_quantity %}
    {% endif %}
  {% endfor %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.