Mechanic Get Mechanic
Task library

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.

Try this task

When it runs

  • Occurs whenever an inventory level is connected
  • Occurs whenever an inventory level is updated
  • Occurs when a user manually triggers the task
  • Occurs when a bulk operation is completed

What you choose

  • Metafield namespace
  • Location IDs and metafield keys

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.

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

shopify/inventory_levels/connect
shopify/inventory_levels/update
mechanic/user/trigger
mechanic/shopify/bulk_operation
How task subscriptions work

Option types and flags

Task 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 %}
Mechanic Liquid reference