Sync inventory levels to variant metafields, with Mechanic.

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

Sync inventory levels to variant metafields

Use this task to easily make your inventory levels available in your online storefront theme. This task monitors for changes to inventory, and copies inventory availability figures to metafields on the related variant.

Runs Occurs whenever an inventory level is connected, Occurs whenever an inventory level is updated, Occurs when a user manually triggers the task, and Occurs when a bulk operation is completed. Configuration includes metafield namespace and location ids and metafield keys.

15-day free trial – unlimited tasks

Documentation

Use this task to easily make your inventory levels available in your online storefront theme. This task monitors for changes to inventory, and copies inventory availability figures to metafields on the related variant.

This task runs automatically, whenever an inventory level is adjusted or whenever a variant is stocked for the first time at a new location.

Run this task manually to backfill metafields for all variants that are stocked in the locations you've configured in this task.

"Location IDs and metafield keys" is a keyval option, where the left-hand side (the key) should contain your location IDs, and the right-hand side (the value) should contain the "metafield key" that you want to associate with each location (e.g. "1234567890" <> "shop", "2345678901" <> "warehouse").

Learn how to find location IDs here.

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/inventory_levels/connect
shopify/inventory_levels/update
mechanic/user/trigger
mechanic/shopify/bulk_operation
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
metafield namespace (required), location ids and metafield keys (keyval, required)
Code
{% assign metafield_namespace = options.metafield_namespace__required | strip %}
{% assign location_ids_and_metafield_keys = options.location_ids_and_metafield_keys__keyval_required %}

{% if event.topic contains "shopify/inventory_levels/" %}
  {% if event.preview %}
    {% capture inventory_level_json %}
      {
        "location_id": {{ location_ids_and_metafield_keys.first.first }},
        "admin_graphql_api_id": "gid://shopify/InventoryLevel/1234567890?inventory_item_id=1234567890"
      }
    {% endcapture %}

    {% assign inventory_level = inventory_level_json | parse_json %}
  {% endif %}

  {% assign inventory_level_string = inventory_level.location_id | append: "" %}
  {% assign metafield_key = location_ids_and_metafield_keys[inventory_level_string] %}

  {% if metafield_key != blank %}
    {% capture query %}
      query {
        inventoryLevel(id: {{ inventory_level.admin_graphql_api_id | json }}) {
          id
          quantities(names: "available") {
            name
            quantity
          }
          item {
            variant {
              id
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "inventoryLevel": {
              "quantities": [
                {
                  "name": "available",
                  "quantity": 20
                }
              ],
              "item": {
                "variant": {
                  "id": "gid://shopify/ProductVariant/1234567890"
                }
              }
            }
          }
        }
      {% endcapture %}

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

    {% action "shopify" %}
      mutation {
        metafieldsSet(
          metafields: [
            {
              ownerId: {{ result.data.inventoryLevel.item.variant.id | json }}
              namespace: {{ metafield_namespace | json }}
              key: {{ metafield_key | json }}
              type: "number_integer"
              value: {{ result.data.inventoryLevel.quantities.first.quantity | append: "" | json }}
            }
          ]
        ) {
          metafields {
            id
            namespace
            key
            type
            value
            owner {
              ... on ProductVariant {
                id
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}

{% elsif event.topic == "mechanic/user/trigger" %}
  {% capture bulk_operation_query %}
    query {
      productVariants {
        edges {
          node {
            id
            inventoryItem {
              id
              inventoryLevels {
                edges {
                  node {
                    __typename
                    id
                    quantities(names: "available") {
                      name
                      quantity
                    }
                    location {
                      legacyResourceId
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% action "shopify" %}
    mutation {
      bulkOperationRunQuery(
        query: {{ bulk_operation_query | json }}
      ) {
        bulkOperation {
          id
          status
        }
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}

{% elsif event.topic == "mechanic/shopify/bulk_operation" %}
  {% if event.preview %}
    {% capture jsonl_string %}
      {"id":"gid:\/\/shopify\/ProductVariant\/1234567890"}
      {"__typename":"InventoryLevel","quantities":[{"name":"available","quantity":20}],"location":{"legacyResourceId":{{ location_ids_and_metafield_keys.first.first | json }}},"__parentId":"gid:\/\/shopify\/ProductVariant\/1234567890"}
    {% endcapture %}

    {% assign bulkOperation = hash %}
    {% assign bulkOperation["objects"] = jsonl_string | parse_jsonl %}
  {% endif %}

  {% assign inventory_levels = bulkOperation.objects | where: "__typename", "InventoryLevel" %}

  {% assign metafields = array %}

  {% for inventory_level in inventory_levels %}
    {% assign metafield_key = location_ids_and_metafield_keys[inventory_level.location.legacyResourceId] %}

    {% if metafield_key != blank and inventory_level.quantities.first.quantity != blank %}
      {% capture metafield %}
        {
          ownerId: {{ inventory_level.__parentId | json }}
          namespace: {{ metafield_namespace | json }}
          key: {{ metafield_key | json }}
          type: "number_integer"
          value: {{ inventory_level.quantities.first.quantity | append: "" | json }}
        }
      {% endcapture %}

      {% assign metafields = metafields | push: metafield %}
    {% endif %}
  {% endfor %}

  {% assign groups_of_metafields = metafields | in_groups_of: 25, fill_with: false %}

  {% for group_of_metafields in groups_of_metafields %}
    {% action "shopify" %}
      mutation {
        metafieldsSet(
          metafields: [
            {{ group_of_metafields | join: newline }}
          ]
        ) {
          metafields {
            id
            namespace
            key
            type
            value
            owner {
              ... on ProductVariant {
                id
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}
  {% endfor %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more