Auto-tag cancelled orders with Mechanic.

Mechanic is the one-tool-does-it-all automation app for Shopify. :)

Auto-tag cancelled orders

by Isaac Bowen (team@usemechanic.com)

This task watches for order cancellations, and adds or removes tags according to your preference.

Runs when an order is updated and when a user triggers the task. Configuration includes tags to add and tags to remove.

15-day free trial – unlimited tasks

Documentation

This task watches for order cancellations, and adds or removes tags according to your preference. Run this task manually to update tags for existing cancelled orders.

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 an order is updated (shopify/orders/updated)
when a user triggers the task (mechanic/user/trigger)
Options
tags to add (array), tags to remove (array)
Script
{% assign orders = array %}

{% if event.preview %}
  {% assign orders[0] = '{"admin_graphql_api_id": "gid://shopify/Order/1234567890", "tags": ""}' | parse_json %}
{% elsif event.topic contains "shopify/orders" %}
  {% if order.cancelled_at != blank %}
    {% assign orders[0] = order %}
  {% endif %}
{% elsif event.topic == "mechanic/user/trigger" %}
  {% assign orders = shop.orders.any.cancelled %}
{% endif %}

{% for order in orders %}
  {% assign order_tags = order.tags | split: ", " %}

  {% assign tags_to_add = array %}
  {% assign tags_to_remove = array %}

  {% for tag in options.tags_to_add__array %}
    {% unless order_tags contains tag %}
      {% assign tags_to_add[tags_to_add.size] = tag %}
    {% endunless %}
  {% endfor %}

  {% for tag in options.tags_to_remove__array %}
    {% if order_tags contains tag %}
      {% assign tags_to_remove[tags_to_remove.size] = tag %}
    {% endif %}
  {% endfor %}

  {% if tags_to_add != empty or tags_to_remove != empty %}
    {% action "shopify" %}
      mutation {
        {% if tags_to_add != empty %}
          tagsAdd(
            id: {{ order.admin_graphql_api_id | json }}
            tags: {{ tags_to_add | json }}
          ) {
            userErrors {
              field
              message
            }
          }
        {% endif %}

        {% if tags_to_remove != empty %}
          tagsRemove(
            id: {{ order.admin_graphql_api_id | json }}
            tags: {{ tags_to_remove | json }}
          ) {
            userErrors {
              field
              message
            }
          }
        {% endif %}
      }
    {% endaction %}
  {% endif %}
{% endfor %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.
Defaults
Tags to add
["cancelled"]