Auto-tag customers by purchased SKUs, with Mechanic.

Mechanic is an automation development platform for Shopify. :)

Auto-tag customers by purchased SKUs

by Isaac Bowen (team@usemechanic.com)

Use this task to keep customers tagged with the SKUs of the products they've purchased, optionally ignoring product purchases that have been refunded. Add a tag prefix to make SKU tags easy to distinguish from your other customer tags.

Runs when an order is paid and when a refund is created. Configuration includes tag prefix, ignore refunded purchases, enable running manually, customer query when running manually, and use test mode when running manually.

15-day free trial – unlimited tasks

Documentation

Use this task to keep customers tagged with the SKUs of the products they've purchased, optionally ignoring product purchases that have been refunded. Add a tag prefix to make SKU tags easy to distinguish from your other customer tags.

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 paid (shopify/orders/paid)
when a refund is created (shopify/refunds/create)
Options
tag prefix, ignore refunded purchases (boolean), enable running manually (boolean), customer query when running manually, use test mode when running manually (boolean)
Script
{% comment %}
  An opinion about option order:

  {{ options.tag_prefix }}
  {{ options.ignore_refunded_purchases__boolean }}
  {{ options.enable_running_manually__boolean }}
  {{ options.customer_query_when_running_manually }}
  {{ options.use_test_mode_when_running_manually__boolean }}
{% endcomment %}

{% if event.topic contains "mechanic/" %}
  {% if event.topic == "mechanic/user/trigger" %}
    {% capture bulk_operation_query %}
      query {
        customers(query: {{ options.customer_query_when_running_manually | json }}) {
          edges {
            node {
              __typename
              id
              tags
              orders {
                edges {
                  node {
                    __typename
                    id
                    legacyResourceId
                    displayFinancialStatus
                    lineItems {
                      edges {
                        node {
                          __typename
                          id
                          sku
                          quantity
                        }
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    {% endcapture %}

    {% action "shopify" %}
      mutation {
        bulkOperationRunQuery(
          query: {{ bulk_operation_query | json }}
        ) {
          bulkOperation {
            id
            status
          }
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% elsif event.topic == "mechanic/shopify/bulk_operation" %}
    {% if event.preview %}
      {% comment %}
        Set up some test/preview data, enough to establish that we can both tag and untag
      {% endcomment %}

      {% assign customer = hash %}
      {% assign customer["id"] = "gid://shopify/Customer/1234567890" %}
      {% assign customer["__typename"] = "Customer" %}
      {% assign customer["tags"] = array %}
      {% assign customer["tags"][0] = "REFUNDED2" %}

      {% assign order1 = hash %}
      {% assign order1["id"] = "gid://shopify/Order/1234567890" %}
      {% assign order1["__typename"] = "Order" %}
      {% assign order1["__parentId"] = customer.id %}
      {% assign order1["__parent"] = customer %}
      {% assign order1["displayFinancialStatus"] = "PAID" %}

      {% assign lineItem1 = hash %}
      {% assign lineItem1["id"] = "gid://shopify/LineItem/1234567890" %}
      {% assign lineItem1["__typename"] = "LineItem" %}
      {% assign lineItem1["__parentId"] = order1.id %}
      {% assign lineItem1["__parent"] = order1 %}
      {% assign lineItem1["sku"] = "PURCHASED5" %}
      {% assign lineItem1["quantity"] = 5 %}

      {% assign lineItem2 = hash %}
      {% assign lineItem2["__typename"] = "LineItem" %}
      {% assign lineItem2["id"] = "gid://shopify/LineItem/2345678901" %}
      {% assign lineItem2["__parentId"] = order1.id %}
      {% assign lineItem2["__parent"] = order1 %}
      {% assign lineItem2["sku"] = "PURCHASED10" %}
      {% assign lineItem2["quantity"] = 10 %}

      {% assign order2 = hash %}
      {% assign order2["id"] = "gid://shopify/Order/2345678901" %}
      {% assign order2["__typename"] = "Order" %}
      {% assign order2["__parentId"] = customer.id %}
      {% assign order2["__parent"] = customer %}
      {% assign order2["legacyResourceId"] = "2345678901" %}
      {% assign order2["displayFinancialStatus"] = "REFUNDED" %}

      {% assign lineItem3 = hash %}
      {% assign lineItem3["__typename"] = "LineItem" %}
      {% assign lineItem3["id"] = "gid://shopify/LineItem/3456789012" %}
      {% assign lineItem3["__parentId"] = order2.id %}
      {% assign lineItem3["__parent"] = order2 %}
      {% assign lineItem3["sku"] = "REFUNDED2" %}
      {% assign lineItem3["quantity"] = 2 %}

      {% assign shop = hash %}
      {% assign shop["orders"] = hash %}
      {% assign shop["orders"]["2345678901"] = hash %}
      {% assign shop["orders"]["2345678901"]["refunds"] = array %}
      {% assign shop["orders"]["2345678901"]["refunds"][0] = hash %}
      {% assign shop["orders"]["2345678901"]["refunds"][0]["refund_line_items"] = array %}
      {% assign shop["orders"]["2345678901"]["refunds"][0]["refund_line_items"][0] = hash %}
      {% assign shop["orders"]["2345678901"]["refunds"][0]["refund_line_items"][0]["line_item"] = hash %}
      {% assign shop["orders"]["2345678901"]["refunds"][0]["refund_line_items"][0]["line_item"]["sku"] = "REFUNDED2" %}
      {% assign shop["orders"]["2345678901"]["refunds"][0]["refund_line_items"][0]["line_item"]["quantity"] = 2 %}

      {% assign objects = array %}
      {% assign objects[objects.size] = customer %}
      {% assign objects[objects.size] = order1 %}
      {% assign objects[objects.size] = order2 %}
      {% assign objects[objects.size] = lineItem1 %}
      {% assign objects[objects.size] = lineItem2 %}
      {% assign objects[objects.size] = lineItem3 %}

      {% assign bulkOperation = hash %}
      {% assign bulkOperation["objects"] = objects %}
    {% endif %}

    {% assign quantities_by_sku_and_customer_id = hash %}

    {% for object in bulkOperation.objects %}
      {% case object.__typename %}
      {% when "LineItem" %}
        {% if object.sku == blank %}
          {% continue %}
        {% endif %}

        {% assign customer_id = object.__parent.__parent.id %}

        {% if customer_id == blank %}
          {% continue %}
        {% endif %}

        {% assign sku = object.sku %}
        {% assign quantity = object.quantity %}

        {% if quantities_by_sku_and_customer_id[customer_id] == nil %}
          {% assign quantities_by_sku_and_customer_id[customer_id] = hash %}
        {% endif %}

        {% assign quantities_by_sku_and_customer_id[customer_id][sku] = quantities_by_sku_and_customer_id[customer_id][sku] | default: 0 | plus: quantity %}
      {% when "Order" %}
        {% unless options.ignore_refunded_purchases__boolean %}
          {% continue %}
        {% endunless %}

        {% unless object.displayFinancialStatus == "REFUNDED" or object.displayFinancialStatus == "PARTIALLY_REFUNDED" %}
          {% continue %}
        {% endunless %}

        {% assign customer_id = object.__parent.id %}

        {% if customer_id == blank %}
          {% continue %}
        {% endif %}

        {% assign refunds = shop.orders[object.legacyResourceId].refunds %}
        {% for refund in refunds %}
          {% for refund_line_item in refund.refund_line_items %}
            {% assign sku = refund_line_item.line_item.sku %}
            {% assign quantity = refund_line_item.line_item.quantity %}

            {% if sku == blank %}
              {% continue %}
            {% endif %}

            {% if quantities_by_sku_and_customer_id[customer_id] == nil %}
              {% assign quantities_by_sku_and_customer_id[customer_id] = hash %}
            {% endif %}

            {% assign quantities_by_sku_and_customer_id[customer_id][sku] = quantities_by_sku_and_customer_id[customer_id][sku] | default: 0 | minus: quantity %}
          {% endfor %}
        {% endfor %}
      {% endcase %}
    {% endfor %}

    {% for object in bulkOperation.objects %}
      {% case object.__typename %}
      {% when "Customer" %}
        {% assign customer_id = object.id %}
        {% assign tags_to_remove = array %}
        {% assign tags_to_add = array %}

        {% for quantities_by_sku in quantities_by_sku_and_customer_id[customer_id] %}
          {% assign sku = quantities_by_sku[0] %}
          {% assign sku_tag = options.tag_prefix | append: sku %}
          {% assign quantity = quantities_by_sku[1] %}

          {% if quantity > 0 %}
            {% unless object.tags contains sku_tag %}
              {% assign tags_to_add[tags_to_add.size] = sku_tag %}
            {% endunless %}
          {% else %}
            {% if object.tags contains sku_tag %}
              {% assign tags_to_remove[tags_to_remove.size] = sku_tag %}
            {% endif %}
          {% endif %}
        {% endfor %}

        {% if tags_to_add != empty or tags_to_remove != empty %}
          {% if options.use_test_mode_when_running_manually__boolean %}
            {% action "echo" %}
              {
                "customer_id": {{ customer_id | json }},
                "tags_to_add": {{ tags_to_add | json }},
                "tags_to_remove": {{ tags_to_remove | json }}
              }
            {% endaction %}
          {% else %}
            {% action "shopify" %}
              mutation {
                {% if tags_to_add != empty %}
                  tagsAdd(
                    id: {{ customer_id | json }}
                    tags: {{ tags_to_add | json }}
                  ) {
                    userErrors {
                      field
                      message
                    }
                  }
                {% endif %}

                {% if tags_to_remove != empty %}
                  tagsRemove(
                    id: {{ customer_id | json }}
                    tags: {{ tags_to_remove | json }}
                  ) {
                    userErrors {
                      field
                      message
                    }
                  }
                {% endif %}
              }
            {% endaction %}
          {% endif %}
        {% endif %}
      {% endcase %}
    {% endfor %}
  {% endif %}
{% elsif event.topic contains "shopify/" %}
  {% if event.topic contains "shopify/refunds/" %}
    {% assign customer = refund.order.customer %}
  {% elsif event.topic contains "shopify/orders/" %}
    {% assign customer = order.customer %}
  {% endif %}

  {% assign cursor = nil %}
  {% assign sku_quantities = hash %}

  {% for n in (0..250) %}
    {% capture query %}
      query {
        orders(
          first: 5
          after: {{ cursor | json }}
          query: {{ "customer_id:" | append: customer.id | json }}
        ) {
          pageInfo {
            hasNextPage
          }
          edges {
            cursor
            node {
              lineItems(first: 50) {
                edges {
                  node {
                    sku
                    quantity
                  }
                }
              }
              refunds {
                refundLineItems(first: 50) {
                  edges {
                    node {
                      quantity
                      lineItem {
                        sku
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% comment %}
        Set up some test/preview data, enough to establish that we can both tag and untag
      {% endcomment %}

      {% assign customer = hash %}
      {% assign customer["admin_graphql_api_id"] = "gid://shopify/Customer/1234567890" %}
      {% assign customer["tags"] = "REFUNDED" %}

      {% capture result_json %}
        {
          "data": {
            "orders": {
              "pageInfo": {
                "hasNextPage": false
              },
              "edges": [
                {
                  "node": {
                    "lineItems": {
                      "edges": [
                        {
                          "node": {
                            "sku": "REFUNDED",
                            "quantity": 1
                          }
                        }
                      ]
                    },
                    "refunds": [
                      {
                        "refundLineItems": {
                          "edges": [
                            {
                              "node": {
                                "quantity": 1,
                                "lineItem": {
                                  "sku": "REFUNDED"
                                }
                              }
                            }
                          ]
                        }
                      }
                    ]
                  }
                },
                {
                  "node": {
                    "lineItems": {
                      "edges": [
                        {
                          "node": {
                            "sku": "PURCHASED",
                            "quantity": 1
                          }
                        }
                      ]
                    },
                    "refunds": []
                  }
                }
              ]
            }
          }
        }
      {% endcapture %}

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

    {% for order_edge in result.data.orders.edges %}
      {% for lineItem_edge in order_edge.node.lineItems.edges %}
        {% assign sku = lineItem_edge.node.sku %}

        {% if sku == blank %}
          {% continue %}
        {% endif %}

        {% assign sku_quantities[sku] = sku_quantities[sku] | default: 0 | plus: lineItem_edge.node.quantity %}
      {% endfor %}

      {% if options.ignore_refunded_purchases__boolean %}
        {% for refund in order_edge.node.refunds %}
          {% for refundLineItem_edge in refund.refundLineItems.edges %}
            {% assign sku = refundLineItem_edge.node.lineItem.sku %}

            {% if sku == blank %}
              {% continue %}
            {% endif %}

            {% assign sku_quantities[sku] = sku_quantities[sku] | default: 0 | minus: refundLineItem_edge.node.quantity %}
          {% endfor %}
        {% endfor %}
      {% endif %}
    {% endfor %}

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

  {
    "log": {
      "customer_id": {{ customer.id | json }},
      "sku_quantities": {{ sku_quantities | json }}
    }
  }

  {% assign tags_to_remove = array %}
  {% assign tags_to_add = array %}
  {% assign customer_tags = customer.tags | split: ", " %}

  {% for sku_and_quantity in sku_quantities %}
    {% assign sku = sku_and_quantity[0] %}
    {% assign sku_tag = options.tag_prefix | append: sku %}
    {% assign quantity = sku_and_quantity[1] %}

    {% if quantity > 0 %}
      {% unless customer_tags contains sku_tag %}
        {% assign tags_to_add[tags_to_add.size] = sku_tag %}
      {% endunless %}
    {% else %}
      {% if customer_tags contains sku_tag %}
        {% assign tags_to_remove[tags_to_remove.size] = sku_tag %}
      {% endif %}
    {% endif %}
  {% endfor %}

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

        {% if tags_to_remove != empty %}
          tagsRemove(
            id: {{ customer.admin_graphql_api_id | json }}
            tags: {{ tags_to_remove | json }}
          ) {
            userErrors {
              field
              message
            }
          }
        {% endif %}
      }
    {% endaction %}
  {% endif %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.
Defaults
Ignore refunded purchases
true