Unpublish out-of-stock variants
This task monitors inventory updates, and unpublishes the variant from the configured sales channels whenever its inventory quantity is equal or lower than the configured "out of stock" threshold. Optionally, it'll send you an email when it does so. You may also choose whether to further refine the variants being considered by this task by configuring product inclusion or exclusion tags (note: exclusion tags will always take precedence over inclusion tags).
Try this taskWhen it runs
- 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
- Out of stock inventory quantity
- Sales channel names
- Only include products with any of these tags
Show 3 more
- Always exclude products with any of these tags
- Only include inventory from these location names
- Email recipients
Documentation
This task monitors inventory updates, and unpublishes the variant from the configured sales channels whenever its inventory quantity is equal or lower than the configured "out of stock" threshold. Optionally, it'll send you an email when it does so. You may also choose whether to further refine the variants being considered by this task by configuring product inclusion or exclusion tags (note: exclusion tags will always take precedence over inclusion tags).
If you'd like for the task to only count inventory from specific locations, then add the exact location names into the task configuration. This feature can be combined with the tag options for unique unpublishing scenarios.
This task can also be run manually, to scan all variants of active products in the shop, filtering by inclusion or exclusion tags as configured.
NOTE: Shopify variant publishing states are independent of product publishing states; however, a published variant will not appear on a sales channel unless its parent product is also published to the same sales channel. See the Shopify docs for additional details on how product and variant publishing work together.
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/user/trigger
mechanic/shopify/bulk_operation
How task subscriptions work
Option types and flags
- Out of stock inventory quantity (number, required)
- Sales channel names (required, array)
- Only include products with any of these tags (array)
- Always exclude products with any of these tags (array)
- Only include inventory from these location names (array)
- Email recipients (array)
Task code
{% assign out_of_stock_inventory_quantity = options.out_of_stock_inventory_quantity__number_required %}
{% assign sales_channel_names = options.sales_channel_names__required_array %}
{% assign inclusion_tags = options.only_include_products_with_any_of_these_tags__array %}
{% assign exclusion_tags = options.always_exclude_products_with_any_of_these_tags__array %}
{% assign location_names = options.only_include_inventory_from_these_location_names__array %}
{% assign email_recipients = options.email_recipients__array %}
{% comment %}
-- get all of the sales channel names (i.e. publications aka app catalogs) in the shop
{% endcomment %}
{% capture query %}
query {
publications(
first: 250
catalogType:APP
) {
nodes {
id
catalog {
... on AppCatalog {
apps(first: 1) {
nodes {
title
}
}
}
}
}
}
}
{% endcapture %}
{% assign result = query | shopify %}
{% if event.preview %}
{% capture result_json %}
{
"data": {
"publications": {
"nodes": [
{
"id": "gid://shopify/Publication/1234567890",
"catalog": {
"apps": {
"nodes": [
{
"title": {{ sales_channel_names.first | json }}
}
]
}
}
}
]
}
}
}
{% endcapture %}
{% assign result = result_json | parse_json %}
{% endif %}
{% comment %}
-- add the configured publication names into a hash for use in lookups
{% endcomment %}
{% assign publication_ids = array %}
{% assign publication_names_by_id = hash %}
{% assign available_sales_channel_names = array %}
{% for publication in result.data.publications.nodes %}
{% assign publication_name = publication.catalog.apps.nodes.first.title %}
{% assign available_sales_channel_names = available_sales_channel_names | push: publication_name %}
{% if sales_channel_names contains publication_name %}
{% assign publication_ids = publication_ids | push: publication.id %}
{% assign publication_names_by_id[publication.id] = publication_name %}
{% endif %}
{% endfor %}
{% comment %}
-- make sure the configured sales channel names match what is in the shop
{% endcomment %}
{% unless event.preview %}
{% if publication_ids.size != sales_channel_names.size %}
{% error
message: "Each sales channel configured in this task must exist in the shop. Check the list of available channels and verify each configured channel exists.",
configured_sales_channel_names: sales_channel_names,
available_sales_channel_names: available_sales_channel_names
%}
{% break %}
{% endif %}
{% endunless %}
{% if location_names != blank %}
{% comment %}
-- get all of the locations in the shop; Shopify supports 1000 as of July 2023
{% endcomment %}
{% assign cursor = nil %}
{% assign locations = array %}
{% for n in (1..10) %}
{% capture query %}
query {
locations(
first: 250
after: {{ cursor | json }}
sortKey: NAME
) {
pageInfo {
hasNextPage
endCursor
}
nodes {
id
name
}
}
}
{% endcapture %}
{% assign result = query | shopify %}
{% if event.preview %}
{% capture result_json %}
{
"data": {
"locations": {
"nodes": [
{
"id": "gid://shopify/Location/1234567890",
"name": {{ location_names.first | json }}
}
]
}
}
}
{% endcapture %}
{% assign result = result_json | parse_json %}
{% endif %}
{% assign locations = locations | concat: result.data.locations.nodes %}
{% if result.data.locations.pageInfo.hasNextPage %}
{% assign cursor = result.data.locations.pageInfo.endCursor %}
{% else %}
{% break %}
{% endif %}
{% endfor %}
{% assign location_ids = array %}
{% comment %}
-- save the location IDs that map to the configured location names
{% endcomment %}
{% for location in locations %}
{% if location_names contains location.name %}
{% assign location_ids[location_ids.size] = location.id %}
{% endif %}
{% endfor %}
{% comment %}
-- make sure the configured location names match what is in the shop
{% endcomment %}
{% unless event.preview %}
{% if location_ids.size != location_names.size %}
{% assign available_location_names = locations | map: "name" %}
{% error
message: "Each location name configured in this task must exactly match a location name in the shop. Check the list of available locations and verify each configured location exists.",
configured_location_names: location_names,
available_location_names: available_location_names
%}
{% break %}
{% endif %}
{% endunless %}
{% endif %}
{% if event.topic contains "shopify/inventory_levels/" %}
{% comment %}
-- query the inventory level to get the variant and product data needed for this task
{% endcomment %}
{% capture query %}
query {
inventoryLevel(
id: {{ inventory_level.admin_graphql_api_id | json }}
) {
item {
variants(first: 1) {
nodes {
id
legacyResourceId
displayName
product {
id
legacyResourceId
tags
}
inventoryQuantity
{% if location_names != blank %}
{% for location_id in location_ids %}
inventory_level_{{ forloop.index }}: inventoryLevel(locationId: {{ location_id | json }}) {
quantities(names: "available") {
quantity
}
}
{% endfor %}
{% endif %}
{% for publication_id in publication_ids %}
published{{ forloop.index }}: publishedOnPublication(publicationId: {{ publication_id | json }})
{% endfor %}
}
}
}
}
}
{% endcapture %}
{% assign result = query | shopify %}
{% if event.preview %}
{% capture result_json %}
{
"data": {
"inventoryLevel": {
"item": {
"variants": {
"nodes": [
{
"id": "gid://shopify/ProductVariant/1234567890",
"legacyResourceId": "1234567890",
"title": "Widget - Red",
"product": {
"id": "gid://shopify/Product/1234567890",
"legacyResourceId": "1234567890",
"tags": {{ inclusion_tags.first | json }}
},
"inventoryQuantity": 0,
"inventoryItem": {
"inventory_level_1": {
"quantities": [
{
"quantity": {{ out_of_stock_inventory_quantity }}
}
]
}
},
"published1": true
}
]
}
}
}
}
}
{% endcapture %}
{% assign result = result_json | parse_json %}
{% endif %}
{% assign variant = result.data.inventoryLevel.item.variants.nodes.first %}
{% assign product = variant.product %}
{% comment %}
-- check to see if product is included or excluded (i.e. whether to process) by any configured tags
{% endcomment %}
{% assign product_included_by_tag = nil %}
{% assign product_excluded_by_tag = nil %}
{% if inclusion_tags != blank %}
{% for inclusion_tag in inclusion_tags %}
{% if product.tags contains inclusion_tag %}
{% assign product_included_by_tag = true %}
{% endif %}
{% endfor %}
{% endif %}
{% if exclusion_tags != blank %}
{% for exclusion_tag in exclusion_tags %}
{% if product.tags contains exclusion_tag %}
{% assign product_excluded_by_tag = true %}
{% endif %}
{% endfor %}
{% endif %}
{% comment %}
-- check if a product has been excluded first, then only if there are inclusion tags configured check if it has been included
{% endcomment %}
{% if product_excluded_by_tag %}
{% log
message: "Variant's product was excluded by a configured tag and will not be processed by this task.",
exclusion_tags: exclusion_tags,
variant: variant
%}
{% break %}
{% elsif inclusion_tags != blank %}
{% unless product_included_by_tag %}
{% log
message: "Variant's product was not included by any configured tag and will not be processed by this task.",
inclusion_tags: inclusion_tags,
variant: variant
%}
{% break %}
{% endunless %}
{% endif %}
{% comment %}
-- variant qualifies to be processed in main variants loop
{% endcomment %}
{% assign variants = array | push: variant %}
{% elsif event.topic == "mechanic/user/trigger" %}
{% comment %}
-- use an inventory filter in the variants search query only if no location names have been configured in the task
{% endcomment %}
{% if location_names == blank %}
{% assign inventory_filter = out_of_stock_inventory_quantity | prepend: "inventory_quantity:<=" %}
{% endif %}
{% comment %}
-- if inclusion or exclusion tags are configured, use them to refine the search query in order to reduce the number of variants to be processed
-- note: tag filters apply to products, not variants directly
{% endcomment %}
{% if inclusion_tags != blank %}
{% assign inclusion_tag_filters = array %}
{% for inclusion_tag in inclusion_tags %}
{% assign inclusion_tag_filter
= inclusion_tag
| json
| prepend: "tag:"
%}
{% assign inclusion_tag_filters = inclusion_tag_filters | push: inclusion_tag_filter %}
{% endfor %}
{% if inclusion_tag_filters.size > 1 %}
{% capture inclusion_tag_filters -%}
({{ inclusion_tag_filters | join: " OR " }})
{%- endcapture %}
{% endif %}
{% endif %}
{% if exclusion_tags != blank %}
{% assign exclusion_tag_filters = array %}
{% for exclusion_tag in exclusion_tags %}
{% assign exclusion_tag_filter
= exclusion_tag
| json
| prepend: "tag_not:"
%}
{% assign exclusion_tag_filters = exclusion_tag_filters | push: exclusion_tag_filter %}
{% endfor %}
{% if exclusion_tag_filters.size > 1 %}
{% capture exclusion_tag_filters -%}
{{ exclusion_tag_filters | join: " AND " }}
{%- endcapture %}
{% endif %}
{% endif %}
{% comment %}
-- recombine any search filters for use in the variants query
{% endcomment %}
{% assign search_query
= array
| push: "product_status:active", inventory_filter, inclusion_tag_filters, exclusion_tag_filters
| compact
| join: " AND "
%}
{% log variants_search_query: search_query %}
{% comment %}
-- use bulk op query to get all variants in the shop that match the search filters
{% endcomment %}
{% capture bulk_operation_query %}
query {
productVariants(
query: {{ search_query | json }}
) {
edges {
node {
__typename
id
legacyResourceId
displayName
product {
id
legacyResourceId
}
inventoryQuantity
{% if location_names != blank %}
inventoryItem {
{% for location_id in location_ids %}
inventory_level_{{ forloop.index }}: inventoryLevel(locationId: {{ location_id | json }}) {
quantities(names: "available") {
quantity
}
}
{% endfor %}
}
{% endif %}
{% for publication_id in publication_ids %}
published{{ forloop.index }}: publishedOnPublication(publicationId: {{ publication_id | json }})
{% endfor %}
}
}
}
}
{% endcapture %}
{% action "shopify" %}
mutation {
bulkOperationRunQuery(
query: {{ bulk_operation_query | json }}
) {
bulkOperation {
id
status
}
userErrors {
field
message
}
}
}
{% endaction %}
{% break %}
{% elsif event.topic == "mechanic/shopify/bulk_operation" %}
{% if event.preview %}
{% capture jsonl_string %}
{"__typename":"ProductVariant","id":"gid://shopify/ProductVariant/1234567890","legacyResourceId":"1234567890","displayName":"Widget - Red","product":{"id":"gid://shopify/Product/1234567890","legacyResourceId":"1234567890"},"inventoryQuantity":{{ out_of_stock_inventory_quantity }},"inventoryItem": {"inventory_level_1":{"quantities":[{"quantity":{{ out_of_stock_inventory_quantity }}}]}},"published1": true}
{% endcapture %}
{% assign bulkOperation = hash %}
{% assign bulkOperation["objects"] = jsonl_string | parse_jsonl %}
{% endif %}
{% assign variants = bulkOperation.objects | where: "__typename", "ProductVariant" %}
{% endif %}
{% comment %}
-- process variants, marking to be unpublished as needed and saving links for optional email output
{% endcomment %}
{% assign variants_to_unpublish = hash %}
{% assign unpublished_variant_links = array %}
{% for variant in variants %}
{% assign product_id = variant.product.id %}
{% assign publication_names = array %}
{% if location_names == blank %}
{% assign available_inventory = variant.inventoryQuantity %}
{% else %}
{% assign available_inventory = 0 %}
{% for item in variant.inventoryItem %}
{% assign available_inventory = available_inventory | plus: item[1].quantities.first.quantity %}
{% endfor %}
{% endif %}
{% if available_inventory > out_of_stock_inventory_quantity %}
{% continue %}
{% endif %}
{% comment %}
-- variant is out of stock, add its id to each sales channel grouping where it is currently published
-- for publicationUpdate, "Variants in a single operation must belong to the same product."
-- also save publication names for use in optional email output
{% endcomment %}
{% for publication_id in publication_ids %}
{% assign key = "published" | append: forloop.index %}
{% if variant[key] == false %}
{% continue %}
{% endif %}
{% assign publication_names[publication_names.size] = publication_names_by_id[publication_id] %}
{% assign variants_to_unpublish[product_id] = variants_to_unpublish[product_id] | default: hash %}
{% assign variants_to_unpublish[product_id][publication_id]
= variants_to_unpublish[product_id][publication_id]
| default: array
| push: variant.id
%}
{% endfor %}
{% comment %}
-- if variant qualifies to be unpublished from any sales channels and there are email recipients configured, then send an immediate notification email (for inventory level events) or save a variant link to be sent later (for manually triggered task runs)
{% endcomment %}
{% if publication_names != blank and email_recipients != blank %}
{% if event.topic contains "shopify/inventory_levels/" %}
{%- capture email_subject -%}
Out of stock: {{ variant.displayName | remove: " - Default Title" }}
{%- endcapture -%}
{% capture email_body %}
Hi there,
Your variant is out of stock{% if location_names != blank %} at the configured locations{% else %} across all locations{% endif %}! This variant has been unpublished from: {{ publication_names | join: ", " }}.
<a href="{{ shop.admin_url }}products/{{ variant.product.legacyResourceId }}/variants/{{ variant.legacyResourceId }}">Manage this variant</a>
Thanks,
- Mechanic, for {{ shop.name }}
{% endcapture %}
{% action "email" %}
{
"to": {{ email_recipients | json }},
"subject": {{ email_subject | json }},
"body": {{ email_body | newline_to_br | json }},
"reply_to": {{ shop.customer_email | json }},
"from_display_name": {{ shop.name | json }}
}
{% endaction %}
{% else %}
{% capture link -%}
<li><a href="{{ shop.admin_url }}products/{{ variant.product.legacyResourceId }}/variants/{{ variant.legacyResourceId }}">{{ variant.displayName | remove: " - Default Title" }}</a> ({{ available_inventory }} - unpublished from {{ publication_names | join: ", " }})</li>
{%- endcapture %}
{% assign unpublished_variant_links[unpublished_variant_links.size] = link %}
{% endif %}
{% endif %}
{% endfor %}
{% if variants_to_unpublish == blank %}
{% unless event.topic contains "shopify/inventory_levels" %}
{% log "No variants qualified to be unpublished during this task run." %}
{% endunless %}
{% break %}
{% endif %}
{% comment %}
-- unpublish variants by product and publication
{% endcomment %}
{% for product_keyval in variants_to_unpublish %}
{% for publication_keyval in product_keyval.last %}
{% assign publication_id = publication_keyval[0] %}
{% assign variant_ids_to_unpublish = publication_keyval[1] %}
{% assign groups_of_variant_ids_to_unpublish = variant_ids_to_unpublish | in_groups_of: 50, fill_with: false %}
{% for group_of_variant_ids_to_unpublish in groups_of_variant_ids_to_unpublish %}
{% action "shopify" %}
mutation {
publicationUpdate(
id: {{ publication_id | json }}
input: {
publishablesToRemove: {{ group_of_variant_ids_to_unpublish | json }}
}
) {
userErrors {
field
message
}
}
}
{% endaction %}
{% endfor %}
{% endfor %}
{% endfor %}
{% comment %}
-- send summary email if there were any variants unpublished on a manual task run
{% endcomment %}
{% if unpublished_variant_links != blank %}
{%- capture email_subject -%}
Found {{ unpublished_variant_links.size }} {{ unpublished_variant_links.size | pluralize: "variant", "variants" }} out of stock
{%- endcapture -%}
{% capture email_body %}
Hi there,
<br><br>
These variants were found to be at or below your out of stock minimum quantity ({{ out_of_stock_inventory_quantity }}), when adding up the inventory {% if location_names != blank %} at the configured locations{% else %} across all locations{% endif %}.
<br>
<ul>{{ unpublished_variant_links | join: "" }}</ul>
<br>
Thanks,
<br>
- Mechanic, for {{ shop.name }}
{% endcapture %}
{% action "email" %}
{
"to": {{ email_recipients | json }},
"subject": {{ email_subject | json }},
"body": {{ email_body | newline_to_br | json }},
"reply_to": {{ shop.customer_email | json }},
"from_display_name": {{ shop.name | json }}
}
{% endaction %}
{% endif %}
Mechanic Liquid reference
Default option values
- Out of stock inventory quantity
0- Sales channel names
["Online Store"]