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 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 options.base_sort_order__required %}
  {% error %}
    {{ allowed_base_sort_orders | join: ", " | prepend: "Base sort order must be one of: " | json }}
  {% enderror %}
{% endunless %}

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

{% assign product_sort_order = options.base_sort_order__required %}
{% 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 %}

{% 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 collections = shop.collections %}

{% if event.preview %}
  {% capture collections_json %}
    [
      {
        "id": {{ collection_handles_or_ids_to_include.first | default: "1234567890" | json }},
        "admin_graphql_api_id": "gid://shopify/Collection/1234567890"
      }
    ]
  {% endcapture %}

  {% assign collections = collections_json | parse_json %}
{% endif %}

{% for collection in collections %}
  {% assign collection_id_string = "" | append: collection.id %}

  {% if collection_handles_or_ids_to_include != blank  %}
    {% unless collection_handles_or_ids_to_include contains collection_id_string
      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_id_string
      or collection_handles_or_ids_to_exclude contains collection.handle %}
      {% continue %}
    {% endif %}
  {% endif %}

  {% if collection.sort_order != "manual" %}
    {% if force_manual_sorting_on_collections or event.preview %}
      {% action "shopify" %}
        mutation {
          collectionUpdate(
            input: {
              id: {{ collection.admin_graphql_api_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 %}

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

  {% for n in (0..100) %}
    {% capture query %}
      query {
        collection(id: {{ collection.admin_graphql_api_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 %}

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

  {% for n in (0..3000) %}
    {% capture query %}
      query {
        collection(id: {{ collection.admin_graphql_api_id | json }}) {
          products(
            sortKey: {{ product_sort_order }}
            reverse: {{ reverse_sort | json }}
            first: 9
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              id
              tracksInventory
              variants(first: 100) {
                nodes {
                  inventoryPolicy
                  inventoryQuantity
                }
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% capture result_json %}
        {
          "data": {
            "collection": {
              "products": {
                "nodes": [
                  {
                    "id": "gid://shopify/Product/1234567890",
                    "tracksInventory": true,
                    "variants": {
                      "nodes": [
                        {
                          "inventoryPolicy": "DENY",
                          "inventoryQuantity": 0
                        }
                      ]
                    }
                  },
                  {
                    "id": "gid://shopify/Product/2345678901",
                    "tracksInventory": true,
                    "variants": {
                      "nodes": [
                        {
                          "inventoryPolicy": "CONTINUE",
                          "inventoryQuantity": 0
                        }
                      ]
                    }
                  },
                  {
                    "id": "gid://shopify/Product/3456789012",
                    "tracksInventory": false
                  },
                  {
                    "id": "gid://shopify/Product/4567890123",
                    "tracksInventory": true,
                    "variants": {
                      "nodes": [
                        {
                          "inventoryPolicy": "DENY",
                          "inventoryQuantity": 0
                        },
                        {
                          "inventoryPolicy": "CONTINUE",
                          "inventoryQuantity": 0
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        }
      {% endcapture %}

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

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

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

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

      {% if has_in_stock_variant %}
        {% assign in_stock_product_ids[in_stock_product_ids.size] = product.id %}
      {% else %}
        {% assign out_of_stock_product_ids[out_of_stock_product_ids.size] = product.id %}
      {% endif %}
    {% endfor %}

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

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

  {% 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.size] = move %}
    {% endif %}
  {% endfor %}

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

  {% for move_group in move_groups %}
    {% action "shopify" %}
      mutation {
        collectionReorderProducts(
          id: {{ collection.admin_graphql_api_id | json }}
          moves: {{ move_group | graphql_arguments }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}

  {% else %}
    {% log
      message: "No position moves necessary for this collection, everything is already in its appropriate sort order.",
      collection: collection.title
    %}
  {% 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