Move out-of-stock products to the end of a collection, with Mechanic.

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

Move out-of-stock products to the end of a collection

This task re-sorts your collections, beginning with the sort order of your choice (alphabetically, best selling first, etc), and then moving all out-of-stock products to the very end of the collection.

Runs Occurs when a user manually triggers the task. Configuration includes base sort order, collection handles or ids to include, collection handles or ids to exclude, force manual sorting on collections, run hourly, and run daily.

15-day free trial – unlimited tasks

Documentation

This task re-sorts your collections, beginning with the sort order of your choice (alphabetically, best selling first, etc), and then moving all out-of-stock products to the very end of the collection.

Run this task manually to re-sort your collections on demand. Optionally, configure this task to run hourly or nightly as well.

By default, this task will run against ALL of your collections. Alternatively, you may configure this task to only include certain collections using each collection's handle, or its ID. Learn how to find the collection IDs.

Conversely, you may configure this task to exclude certain collections using each collection's handle, or its ID, in which case it will run against all collections except the ones in this list. [Note: if there are any collections entered into the inclusion list, then the exclusion list will be ignored.]

The combination of inclusion and exclusion options can allow multiple copies of this task to run (to use different base sorting for instance), provided they are configured properly.

This task will skip any collections it encounters if the collection sorting is not already set to manual. Check the "Force manual sorting on collections" option to have the task update those collections to the manual sorting required by this task.

You may use any of these options for the base sort order:

  • MANUAL
  • ALPHA_ASC
  • ALPHA_DESC
  • BEST_SELLING
  • CREATED
  • CREATED_DESC
  • PRICE_ASC
  • PRICE_DESC

Note: To function correctly, the "Perform action runs in sequence" option should stay enabled in the task's advanced settings.

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
mechanic/user/trigger
{% if options.run_hourly__boolean %}
  mechanic/scheduler/hourly
{% elsif options.run_daily__boolean %}
  mechanic/scheduler/daily
{% endif %}
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
base sort order (required), collection handles or ids to include (array), collection handles or ids to exclude (array), force manual sorting on collections (boolean), run hourly (boolean), run daily (boolean)
Code
{% assign base_sort_order = options.base_sort_order__required %}
{% assign collection_handles_or_ids_to_include = options.collection_handles_or_ids_to_include__array %}
{% assign collection_handles_or_ids_to_exclude = options.collection_handles_or_ids_to_exclude__array %}
{% assign force_manual_sorting_on_collections = options.force_manual_sorting_on_collections__boolean %}

{% assign allowed_base_sort_orders = "MANUAL,BEST_SELLING,ALPHA_ASC,ALPHA_DESC,PRICE_DESC,PRICE_ASC,CREATED_DESC,CREATED" | split: "," %}

{% unless allowed_base_sort_orders contains base_sort_order %}
  {% error %}
    {{ allowed_base_sort_orders | join: ", " | prepend: "Base sort order must be one of: " | json }}
  {% enderror %}
{% endunless %}

{% log %}
  {{ base_sort_order | prepend: "Base sort order for this task run: " | json }}
{% endlog %}

{% assign product_sort_order = base_sort_order %}
{% assign reverse_sort = nil %}

{% case product_sort_order %}
  {% when "ALPHA_ASC" %}
    {% assign product_sort_order = "TITLE" %}

  {% when "ALPHA_DESC" %}
    {% assign product_sort_order = "TITLE" %}
    {% assign reverse_sort = true %}

  {% when "CREATED_DESC" %}
    {% assign product_sort_order = "CREATED" %}
    {% assign reverse_sort = true %}

  {% when "PRICE_ASC" %}
    {% assign product_sort_order = "PRICE" %}

  {% when "PRICE_DESC" %}
    {% assign product_sort_order = "PRICE" %}
    {% assign reverse_sort = true %}
{% endcase %}

{% comment %}
  -- query all collections in the shop; do not use a query filter for IDs or handles here since those configuration fields are optional
{% endcomment %}

{% assign cursor = nil %}
{% assign collections = array %}

{% for n in (1..100) %}
  {% capture query %}
    query {
      collections(
        first: 250
        after: {{ cursor | json }}
      ) {
        pageInfo {
          hasNextPage
          endCursor
        }
        nodes {
          id
          legacyResourceId
          title
          handle
          sortOrder
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "collections": {
            "nodes": [
              {
                "id": "gid://shopify/Collection/1234567890",
                "legacyResourceId": {{ collection_handles_or_ids_to_include.first | default: "1234567890" | json }},
                "title": "Samples",
                "handle": {{ collection_handles_or_ids_to_include.first | json }},
                "sortOrder": "MANUAL"
              }
            ]
          }
        }
      }
    {% endcapture %}

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

  {% assign collections = collections | concat: result.data.collections.nodes %}

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

{% comment %}
  -- loop through collections and filter by ID and/or handle as configured
{% endcomment %}

{% for collection in collections %}
  {% if collection_handles_or_ids_to_include != blank  %}
    {% unless collection_handles_or_ids_to_include contains collection.legacyResourceId
      or collection_handles_or_ids_to_include contains collection.handle %}
      {% continue %}
    {% endunless %}

  {% elsif collection_handles_or_ids_to_exclude != blank  %}
    {% if collection_handles_or_ids_to_exclude contains collection.legacyResourceId
      or collection_handles_or_ids_to_exclude contains collection.handle %}
      {% continue %}
    {% endif %}
  {% endif %}

  {% comment %}
    -- make sure collection is configured for manual sorting, and optionally update it if not
  {% endcomment %}

  {% if collection.sortOrder != "MANUAL" %}
    {% if force_manual_sorting_on_collections %}
      {% action "shopify" %}
        mutation {
          collectionUpdate(
            input: {
              id: {{ collection.id | json }}
              sortOrder: MANUAL
            }
          ) {
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}

    {% else %}
      {% log %}
        {{ collection.title | json | append: " is not configured for manual sorting; skipping." | json }}
      {% endlog %}

      {% continue %}
    {% endif %}
  {% endif %}

  {% comment %}
    -- get all product IDs in this collection using the current sort order
  {% endcomment %}

  {% assign all_product_ids_current_sort = array %}
  {% assign cursor = nil %}

  {% for n in (1..100) %}
    {% capture query %}
      query {
        collection(id: {{ collection.id | json }}) {
          products(
            sortKey: COLLECTION_DEFAULT
            first: 250
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              id
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% assign product_ids_batch = result.data.collection.products.nodes | map: "id" %}
    {% assign all_product_ids_current_sort = all_product_ids_current_sort | concat: product_ids_batch %}

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

  {% comment %}
    -- get all products in this collection using the configured sort order; get variants later if needed in order to support 2K variant limit
  {% endcomment %}

  {% assign in_stock_product_ids = array %}
  {% assign out_of_stock_product_ids = array %}
  {% assign cursor = nil %}

  {% for n in (1..100) %}
    {% capture query %}
      query {
        collection(id: {{ collection.id | json }}) {
          products(
            sortKey: {{ product_sort_order }}
            reverse: {{ reverse_sort | json }}
            first: 250
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              id
              tracksInventory
              hasOutOfStockVariants
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "collection": {
              "products": {
                "nodes": [
                  {
                    "id": "gid://shopify/Product/1234567890",
                    "tracksInventory": true,
                    "hasOutOfStockVariants": true
                  },
                  {
                    "id": "gid://shopify/Product/2345678901",
                    "tracksInventory": true,
                    "hasOutOfStockVariants": false
                  },
                  {
                    "id": "gid://shopify/Product/3456789012",
                    "tracksInventory": false
                  }
                ]
              }
            }
          }
        }
      {% endcapture %}

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

    {% comment %}
      -- split products into in-stock and out-of-stock buckets, keeping the configured sort order
    {% endcomment %}

    {% for product in result.data.collection.products.nodes %}
      {% assign has_in_stock_variant = nil %}

      {% unless product.tracksInventory and product.hasOutOfStockVariants %}
        {% assign has_in_stock_variant = true %}

      {% else %}
        {% comment %}
          -- query up to 2K variants to see if any of them are in stock; can break as soon as one is found
        {% endcomment %}

        {% assign variants_cursor = nil %}

        {% for n in (1..8) %}
          {% capture query %}
            query {
              product(id: {{ product.id | json }}) {
                variants(
                  first: 250
                  after: {{ variants_cursor | json }}
                ) {
                  pageInfo {
                    hasNextPage
                    endCursor
                  }
                  nodes {
                    id
                    inventoryPolicy
                    inventoryQuantity
                  }
                }
              }
            }
          {% endcapture %}

          {% assign variants_result = query | shopify %}

          {% if event.preview %}
            {% capture variants_result_json %}
              {
                "data": {
                  "product": {
                    "variants": {
                      "nodes": [
                        {
                          "id": "gid://shopify/ProductVariant/1234567890",
                          "inventoryPolicy": "DENY",
                          "inventoryQuantity": 0
                        }
                      ]
                    }
                  }
                }
              }
            {% endcapture %}

            {% assign variants_result = variants_result_json | parse_json %}
          {% endif %}

          {% for variant in variants_result.data.product.variants.nodes %}
            {% if variant.inventoryPolicy == "CONTINUE" or variant.inventoryQuantity > 0 %}
              {% assign has_in_stock_variant = true %}
              {% break %}
            {% endif %}
          {% endfor %}

          {% if variants_result.data.product.variants.pageInfo.hasNextPage and has_in_stock_variant != true %}
            {% assign variants_cursor = variants_result.data.product.variants.pageInfo.endCursor %}
          {% else %}
            {% break %}
          {% endif %}
        {% endfor %}
      {% endunless %}

      {% if has_in_stock_variant %}
        {% assign in_stock_product_ids = in_stock_product_ids | push: product.id %}
      {% else %}
        {% assign out_of_stock_product_ids = out_of_stock_product_ids | push: product.id %}
      {% endif %}
    {% endfor %}

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

  {% comment %}
    -- combine product IDs back into single array with all out of stock variants following the in stock ones, but otherwise keeping the configured sort order
  {% endcomment %}

  {% assign all_product_ids = in_stock_product_ids | concat: out_of_stock_product_ids %}

  {% comment %}
    -- determine which product IDs need to be moved by comparing to original sort order
  {% endcomment %}

  {% assign moves = array %}

  {% for product_id in all_product_ids %}
    {% if all_product_ids_current_sort[forloop.index0] != product_id %}
      {% assign move = hash %}
      {% assign move["id"] = product_id %}
      {% assign move["newPosition"] = "" | append: forloop.index0 %}
      {% assign moves = moves | push: move %}
    {% endif %}
  {% endfor %}

  {% comment %}
    -- move to next collection if no moves are necessary
  {% endcomment %}

  {% if moves == blank %}
    {% log
      message: "No position moves necessary for this collection, everything is already in its appropriate sort order.",
      collection: collection.title
    %}
    {% continue %}
  {% endif %}

  {% log
    message: "Scheduling job(s) to reorder products for this collection.",
    collection: collection.title,
    moves_count: moves.size
  %}

  {% comment %}
    -- using reverse filter below due to a bug in the collectionReorderProducts mutation
    -- this filter will NOT affect the sort order determined above
  {% endcomment %}

  {% assign move_groups = moves | reverse | in_groups_of: 250, fill_with: false %}

  {% for move_group in move_groups %}
    {% action "shopify" %}
      mutation {
        collectionReorderProducts(
          id: {{ collection.id | json }}
          moves: {{ move_group | graphql_arguments }}
        ) {
          job {
            id
          }
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endfor %}
{% endfor %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Base sort order
ALPHA_ASC