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 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 inventory quantity are reflected across all variants sharing that SKU.

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 considers a store's default location when managing 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.

Open source
View on GitHub to contribute to this task
Events
Occurs when a user manually triggers the task (mechanic/user/trigger)
Occurs every 10 minutes (mechanic/scheduler/10min)
Options
product skus to monitor (array, required)
Script
{% assign primary_location = shop.locations[shop.primary_location_id] %}
{% assign skus = options.product_skus_to_monitor__array_required %}
{% assign variants_by_sku = hash %}
{% assign skus_quoted = array %}

{% for sku in skus %}
  {% assign skus_quoted[forloop.index0] = sku | json %}
{% endfor %}

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

{% assign cursor = nil %}

{% for n in (0..100) %}
  {% capture query %}
    query {
      productVariants(
        first: 250
        query: {{ search_query | strip_newlines | json }}
        after: {{ cursor | json }}
      ) {
        pageInfo {
          hasNextPage
        }
        edges {
          cursor
          node {
            id
            sku
            inventoryItem {
              id
              inventoryLevel(locationId: {{ primary_location.admin_graphql_api_id | json }}) {
                available
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "productVariants": {
            "edges": [
              {
                "node": {
                  "id": "gid://shopify/ProductVariant/1234567890",
                  "sku": {{ skus[0] | json }},
                  "inventoryItem": {
                    "id": "gid://shopify/InventoryItem/1234567890",
                    "inventoryLevel": {
                      "available": {% if event.topic == "mechanic/user/trigger" %}5{% else %}4{% endif %}
                    }
                  }
                }
              },
              {
                "node": {
                  "id": "gid://shopify/ProductVariant/2345678901",
                  "sku": {{ skus[0] | json }},
                  "inventoryItem": {
                    "id": "gid://shopify/InventoryItem/2345678901",
                    "inventoryLevel": {
                      "available": {% if event.topic == "mechanic/user/trigger" %}5{% else %}4{% endif %}
                    }
                  }
                }
              }
            ]
          }
        }
      }
    {% 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 %}

{% 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.available %}
    {% for variant in variants %}
      {% if variant.inventoryItem.inventoryLevel.available != 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].inventoryItem.inventoryLevel.available %}
  {% 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.inventoryItem.inventoryLevel.available | 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 %}
        {% capture adjustment %}
          {
            inventoryItemId: {{ variant.inventoryItem.id | json }}
            availableDelta: {{ delta_for_sync | json }}
          }
        {% endcapture %}
        {% assign adjustments[adjustments.size] = adjustment %}
      {% endif %}
    {% endfor %}

    {% if adjustments != empty %}
      {% assign groups_of_adjustments = adjustments | in_groups_of: 100, fill_with: false %}

      {% for group_of_adjustments in groups_of_adjustments %}
        {% action "shopify" %}
          mutation {
            inventoryBulkAdjustQuantityAtLocation(
              inventoryItemAdjustments: [
                {{ group_of_adjustments | join: newline }}
              ]
              locationId: {{ primary_location.admin_graphql_api_id | json }}
            ) {
              userErrors {
                field
                message
              }
            }
          }
        {% endaction %}
      {% endfor %}
    {% 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.