Mechanic Get Mechanic
Task library

Unpublish products that have been out of stock for x days

This task watches for inventory updates. When a product's total inventory becomes 0 or less, the current time will be recorded for that product. Then, on an hourly basis, this task will unpublish any products with a recorded out-of-stock time of at least x days ago.

Try this task

When it runs

  • Occurs whenever an inventory level is updated
  • Occurs every hour
  • Occurs when a user manually triggers the task

What you choose

  • Number of days to wait before unpublishing
  • Sales channel names
  • Only include products matching this search query
  • Test mode

Documentation

This task watches for inventory updates. When a product's total inventory becomes 0 or less, the current time will be recorded for that product. Then, on an hourly basis, this task will unpublish any products with a recorded out-of-stock time of at least x days ago.

Notes:

  • The first time the hourly scan runs, it may encounter products that were already out of stock, before this task was installed. For those products, the current time will be recorded as their out-of-stock time. This means that these products will wait for another x days before being automatically unpublished.
  • If a product that this task unpublishes is manually published, and its total inventory is still 0 or less, this task will unpublish it again during its next hourly scan.
  • This task includes a test mode. Enable it to have the task report what it would do, if test mode was disabled.
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/update
mechanic/scheduler/hourly
mechanic/user/trigger
How task subscriptions work

Option types and flags

Task code

{% comment %}
  1. Watch for updates to inventory levels.
  2. Look up the associated product, when an update comes in.
  3. If the product's total inventory is <=0, record the current time in a metafield. If the
     total inventory is not 0, delete that metafield, if it exists.
  4. Scan all products, on a schedule, retrieving each product's out-of-stock time metafield.
     For products found with a total inventory of <=0, with a recorded time that's at least a
     configurable distance in days from the current time, unpublish the product.
{% endcomment %}

{% assign number_of_days_to_wait_before_unpublishing = options.number_of_days_to_wait_before_unpublishing__number_required %}
{% assign sales_channel_names = options.sales_channel_names__required_array %}
{% assign only_include_products_matching_this_search_query = options.only_include_products_matching_this_search_query %}
{% assign test_mode = options.test_mode__boolean %}

{% assign time_format = "%FT%T%z" %}

{% if event.topic == "shopify/inventory_levels/update" %}
  {% capture query %}
    query {
      inventoryLevel(
        id: {{ inventory_level.admin_graphql_api_id | json }}
      ) {
        id
        item {
          variant {
            product {
              id
              title
              totalInventory
              metafield(
                namespace: "mechanic"
                key: "out_of_stock_at"
              ) {
                id
                value
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "inventoryLevel": {
            "id": "gid://shopify/InventoryLevel/1234567890?inventory_item_id=1234567890",
            "item": {
              "variant": {
                "product": {
                  "id": "gid://shopify/Product/1234567890",
                  "title": "Short sleeve t-shirt",
                  "totalInventory": 0,
                  "metafield": null
                }
              }
            }
          }
        }
      }
    {% endcapture %}

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

  {% assign product = result.data.inventoryLevel.item.variant.product %}

  {% if product.totalInventory <= 0 and product.metafield == nil %}
    {% if test_mode %}
      {% log %}
        {% capture message %}Product {{ product.title | json }} ({{ product.id }}) is out of stock. Its out-of-stock time should be recorded.{% endcapture %}
        {{ message | json }}
      {% endlog %}

    {% else %}
      {% action "shopify" %}
        mutation {
          metafieldsSet(
            metafields: [
              {
                ownerId: {{ product.id | json }}
                namespace: "mechanic"
                key: "out_of_stock_at"
                type: "date_time"
                value: {{ "now" | date: time_format | json }}
              }
            ]
          ) {
            metafields {
              id
              namespace
              key
              type
              value
              owner {
                ... on Product {
                  id
                  title
                }
              }
            }
            userErrors {
              code
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}

  {% elsif product.totalInventory > 0 and product.metafield != nil %}
    {% if test_mode %}
      {% log %}
        {% capture message %}Product {{ product.title | json }} ({{ product.id }}) is back in stock. Its out-of-stock time should be cleared.{% endcapture %}
        {{ message | json }}
      {% endlog %}

    {% else %}
      {% action "shopify" %}
        mutation {
          metafieldsDelete(
            metafields: [
              {
                ownerId: {{ product.id | json }}
                namespace: "mechanic"
                key: "out_of_stock_at"
              }
            ]
          ) {
            deletedMetafields {
              ownerId
              namespace
              key
            }
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}
  {% endif %}

{% elsif event.topic contains "mechanic/scheduler/" or event.topic == "mechanic/user/trigger" %}
  {% assign now_s = "now" | date: "%s" | times: 1 %}
  {% assign minimum_out_of_stock_at_distance_s = number_of_days_to_wait_before_unpublishing | times: 24 | times: 60 | times: 60 %}

  {% capture query %}
    query {
      publications(first: 250) {
        nodes {
          id
          name
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% assign publications = array %}
  {% assign metafields_to_set = array %}

  {% for publication in result.data.publications.nodes %}
    {% if sales_channel_names contains publication.name %}
      {% assign publications[publications.size] = publication %}
    {% endif %}
  {% endfor%}

  {% if event.preview %}
    {% assign publications[0] = hash %}
    {% assign publications[0]["id"] = "gid://shopify/Publication/1234567890" %}

  {% elsif publications.size != sales_channel_names.size %}
    {% log
      publications_named: sales_channel_names,
      publications_available: result.data.publications.nodes,
      publications_matched: publications
    %}
    {% error "Unable to find all named publications. Double-check your task configuration." %}
  {% endif %}

  {% assign search_query = "inventory_total:<=0" %}

  {% if only_include_products_matching_this_search_query != blank %}
    {% capture search_query -%}
      {{ search_query }} AND ({{ only_include_products_matching_this_search_query }})
    {%- endcapture %}
    {% log search_query: search_query %}
  {% endif %}

  {% assign cursor = nil %}

  {% for n in (0..100) %}
    {% capture query %}
      query {
        products(
          first: 250
          query: {{ search_query | json }}
          after: {{ cursor | json }}
        ) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            id
            title
            totalInventory
            {% for publication in publications %}
              publishedOnPublication{{ forloop.index }}: publishedOnPublication(publicationId: {{ publication.id | json }})
            {% endfor %}
            metafield(
              namespace: "mechanic"
              key: "out_of_stock_at"
            ) {
              id
              value
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "products": {
              "nodes": [
                {
                  "id": "gid://shopify/Product/1234567890",
                  "title": "Short sleeve t-shirt",
                  "totalInventory": 0,
                  {% for publication in publications %}
                    {{ "publishedOnPublication" | append: forloop.index | json }}: true,
                  {% endfor %}
                  "metafield": {
                    "value": {{ now_s | minus: minimum_out_of_stock_at_distance_s | minus: 1 | append: "" | json }}
                  }
                }
              ]
            }
          }
        }
      {% endcapture %}

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

    {% for product in result.data.products.nodes %}
      {% if product.metafield == nil %}
        {% log %}
          {% capture message %}Product {{ product.id }} is out of stock, but its out-of-stock time was not recorded. This product will not be unpublished now, but its out-of-stock time will be set to the current time.{% endcapture %}
          {{ message | json }}
        {% endlog %}

        {% assign metafield_to_set = hash %}
        {% assign metafield_to_set["ownerId"] = product.id %}
        {% assign metafield_to_set["namespace"] = "mechanic" %}
        {% assign metafield_to_set["key"] = "out_of_stock_at" %}
        {% assign metafield_to_set["type"] = "date_time" %}
        {% assign metafield_to_set["value"] = "now" | date: time_format %}
        {% assign metafields_to_set = metafields_to_set | push: metafield_to_set %}

        {% continue %}
      {% endif %}

      {% assign out_of_stock_at_s = product.metafield.value | date: "%s" | times: 1 %}
      {% assign out_of_stock_at_distance_s = now_s | minus: out_of_stock_at_s %}

      {% assign unpublishings = array %}

      {% for publication in publications %}
        {% assign key = "publishedOnPublication" | append: forloop.index %}
        {% if product[key] %}
          {% assign unpublishing = array %}
          {% assign unpublishing[0] = product.id %}
          {% assign unpublishing[1] = publication.id %}
          {% assign unpublishings[unpublishings.size] = unpublishing %}
        {% endif %}
      {% endfor %}

      {% if unpublishings == empty %}
        {% log %}
          {% capture message %}Product {{ product.title | json }} ({{ product.id }}) has been out of stock for {{ out_of_stock_at_distance_s | divided_by: 60 | divided_by: 60 | divided_by: 24 | round: 2 }} day(s), but is not published - nothing to do.{% endcapture %}
          {{ message | json }}
        {% endlog %}
        {% continue %}
      {% endif %}

      {% if out_of_stock_at_distance_s < minimum_out_of_stock_at_distance_s %}
        {% log %}
          {% capture message %}Product {{ product.title | json }} ({{ product.id }}) is out of stock, and is published, but has only been out of stock for {{ out_of_stock_at_distance_s | divided_by: 60 | divided_by: 60 | divided_by: 24 | round: 2 }} day(s).{% endcapture %}
          {{ message | json }}
        {% endlog %}
        {% continue %}
      {% endif %}

      {% if test_mode %}
        {% log %}
          {% capture message %}Product {{ product.title | json }} ({{ product.id }}) is out of stock, and has been out of stock for {{ out_of_stock_at_distance_s | divided_by: 60 | divided_by: 60 | divided_by: 24 | round: 2 }} day(s). It should be unpublished.{% endcapture %}
          {{ message | json }}
        {% endlog %}

      {% else %}
        {% action "shopify" %}
          mutation {
            {% for unpublishing in unpublishings %}
              publishableUnpublish{{ forloop.index }}: publishableUnpublish(
                id: {{ unpublishing[0] | json }}
                input: {
                  publicationId: {{ unpublishing[1] | json }}
                }
              ) {
                userErrors {
                  field
                  message
                }
              }
            {% endfor %}
          }
        {% endaction %}
      {% endif %}
    {% endfor %}

    {% if result.data.products.pageInfo.hasNextPage %}
      {% assign cursor = result.data.products.pageInfo.endCursor %}
    {% else %}
      {% break %}
    {% endif %}
  {% endfor %}
{% endif %}

{% if metafields_to_set != blank %}
  {% if test_mode %}
    {% log %}
      "Found {{ metafields_to_set.size }} out of stock products which do not yet have their out of stock time recorded. This task has test mode enabled, so these metafields will not be set on this task run."
    {% endlog %}

    {% break %}
  {% endif %}

  {% assign groups_of_metafields_to_set = metafields_to_set | in_groups_of: 25, fill_with: false %}

  {% for group_of_metafields_to_set in groups_of_metafields_to_set %}
    {% action "shopify" %}
      mutation {
        metafieldsSet(
          metafields: {{ group_of_metafields_to_set | graphql_arguments }}
        ) {
          metafields {
            id
            namespace
            key
            type
            value
            owner {
              ... on Product {
                id
                title
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}
  {% endfor %}
{% endif %}
Mechanic Liquid reference

Default option values

Sales channel names
["Online Store"]
Test mode
true