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

Mechanic is an automation development platform for Shopify. :)

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

by Isaac Bowen (team@usemechanic.com)

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 when a user triggers the task, when user/reorder_collection/stage_2 is triggered, and when user/reorder_collection/stage_3 is triggered. Configuration includes base sort order, collection titles or ids, run hourly, and run daily.

15-day free trial – unlimited tasks

Documentation

This task re-sorts your chosen collections, beginning with the sort order of your choice, 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.

Configure this task for certain collections using each collection's title, or its ID. Learn how to find the collection IDs.

The collections used with this task must be configured for manual sorting. Learn how to change the sort order of your collections.

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

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

Developer details

Mechanic is designed to benefit everybody: merchants, customers, developers, agencies, Gurus, 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.

Events
when a user triggers the task (mechanic/user/trigger)
when user/reorder_collection/stage_2 is triggered (user/reorder_collection/stage_2)
when user/reorder_collection/stage_3 is triggered (user/reorder_collection/stage_3)
Options
base sort order (required), collection titles or ids (array, required), run hourly (boolean), run daily (boolean)
Script
{% 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 }}}
{% endunless %}

{% if event.topic contains "mechanic/" %}
  {% if event.preview %}
    {% assign collections = '[{"admin_graphql_api_id": "gid://shopify/Collection/1234567890", "sort_order": "manual"}]' | parse_json %}
  {% else %}
    {% assign collections = array %}

    {% for some_collection in shop.collections %}
      {% assign some_collection_id_string = "" | append: some_collection.id %}
      {% if options.collection_titles_or_ids__array_required contains some_collection_id_string or options.collection_titles_or_ids__array_required contains some_collection.title %}
        {% assign collections[collections.size] = some_collection %}
      {% endif %}
    {% endfor %}
  {% endif %}

  {% for collection in collections %}
    {% if collection.sort_order != "manual" %}
      {"error": {{ collection.title | json | prepend: " is not configured for manual sorting. Set this collection to be manually sorted, and try again." | json }}}
      {% assign collections = array %}
    {% endif %}
  {% endfor %}

  {% for collection in collections %}
    {% action "shopify" %}
      mutation {
        collectionUpdate(
          input: {
            id: {{ collection.admin_graphql_api_id | json }}
            sortOrder: {{ options.base_sort_order__required }}
          }
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}

    {% action "event" %}
      {
        "topic": "user/reorder_collection/stage_2",
        "data": {
          "collection_id": {{ collection.admin_graphql_api_id | json }}
        }
      }
    {% endaction %}
  {% endfor %}
{% elsif event.topic == "user/reorder_collection/stage_2" %}
  {% if event.preview %}
    {% assign event = '{"data": {"collection_id": "gid://shopify/Collection/1234567890"}}' | parse_json %}
  {% endif %}

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

  {% assign cursor = nil %}
  {% for n in (0..100) %}
    {% capture query %}
      query {
        collection(id: {{ event.data.collection_id | json }}) {
          products(
            sortKey: COLLECTION_DEFAULT
            first: 250
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
            }
            edges {
              cursor
              node {
                id
                tracksInventory
                totalInventory
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% for product_edge in result.data.collection.products.edges %}
      {% if product_edge.node.tracksInventory and product_edge.node.totalInventory <= 0 %}
        {% assign out_of_stock_product_ids[out_of_stock_product_ids.size] = product_edge.node.id %}
      {% else %}
        {% assign in_stock_product_ids[in_stock_product_ids.size] = product_edge.node.id %}
      {% endif %}
    {% endfor %}

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

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

  {% action "shopify" %}
    mutation {
      collectionUpdate(
        input: {
          id: {{ event.data.collection_id | json }}
          sortOrder: MANUAL
        }
      ) {
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}

  {% action "event" %}
    {
      "topic": "user/reorder_collection/stage_3",
      "data": {
        "collection_id": {{ event.data.collection_id | json }},
        "ordered_product_ids": {{ all_product_ids | json }}
      }
    }
  {% endaction %}
{% elsif event.topic == "user/reorder_collection/stage_3" %}
  {% if event.preview %}
    {% assign event = '{"data": {"collection_id": "gid://shopify/Collection/1234567890", "ordered_product_ids": []}}' | parse_json %}
  {% endif %}

  {% action "shopify" %}
    mutation {
      collectionReorderProducts(
        id: {{ event.data.collection_id | json }}
        moves: [
          {% for product_id in event.data.ordered_product_ids %}
            {
              id: {{ product_id | json }}
              newPosition: {{ forloop.index0 | append: "" | json }}
            }
          {% endfor %}
        ]
      ) {
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.
Defaults
Base sort order
ALPHA_DESC