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 test mode.

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, test mode (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.test_mode__boolean }}
{% endcomment %}

{% assign metafield_namespace = "mechanic" %}
{% assign metafield_key = "purchased_skus" %}

{% assign jobs = array %}

{% 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
              metafield(
                namespace: {{ metafield_namespace | json }}
                key: {{ metafield_key | json }}
              ) {
                id
                value
              }
              orders(sortKey: PROCESSED_AT, reverse: true) {
                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 customer["metafield"] = nil %}
      {% comment %}
        {% assign customer["metafield"] = hash %}
        {% assign customer["metafield"]["id"] = "gid://shopify/Metafield/1234567890" %}
        {% assign customer["metafield"]["value"] = '["PURCHASED10","PURCHASED5"]' %}
      {% endcomment %}

      {% 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 job = hash %}

        {% assign job["customer_id"] = object.id %}
        {% assign job["tags_to_remove"] = array %}
        {% assign job["tags_to_add"] = array %}

        {% assign job["metafield_id"] = object.metafield.id %}
        {% assign job["skus_in_metafield"] = object.metafield.value | default: "[]" | parse_json | sort %}
        {% assign job["skus_for_metafield"] = array %}

        {% for quantities_by_sku in quantities_by_sku_and_customer_id[job.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 job["tags_to_add"][job.tags_to_add.size] = sku_tag %}
            {% endunless %}
            {% assign job["skus_for_metafield"][job.skus_for_metafield.size] = sku_tag %}
          {% else %}
            {% if object.tags contains sku_tag %}
              {% assign job["tags_to_remove"][job.tags_to_remove.size] = sku_tag %}
            {% endif %}
          {% endif %}
        {% endfor %}

        {% assign job["skus_for_metafield"] = job.skus_for_metafield | sort %}

        {% assign jobs[jobs.size] = job %}
      {% 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 }}
          sortKey: PROCESSED_AT
          reverse: true
        ) {
          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" %}
      {% comment %}
        {% assign customer["metafields"] = hash %}
        {% assign customer["metafields"]["mechanic"] = array %}
        {% assign customer["metafields"][metafield_namespace] = array %}
        {% assign customer["metafields"][metafield_namespace][0] = hash %}
        {% assign customer["metafields"][metafield_namespace][0]["key"] = metafield_key %}
        {% assign customer["metafields"][metafield_namespace][0]["admin_graphql_api_id"] = "gid://shopify/Metafield/1234567890" %}
        {% assign customer["metafields"][metafield_namespace][0]["value"] = '["PURTCHASED"]' %}
      {% endcomment %}

      {% 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 %}

  {% assign job = hash %}

  {% assign job["customer_id"] = customer.admin_graphql_api_id %}
  {% assign job["tags_to_remove"] = array %}
  {% assign job["tags_to_add"] = array %}

  {% assign metafield = customer.metafields[metafield_namespace] | where: "key", metafield_key | first %}
  {% assign job["metafield_id"] = metafield.admin_graphql_api_id %}
  {% assign job["skus_in_metafield"] = metafield.value | default: "[]" | parse_json | sort %}
  {% assign job["skus_for_metafield"] = 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 job["tags_to_add"][job.tags_to_add.size] = sku_tag %}
      {% endunless %}
      {% assign job["skus_for_metafield"][job.skus_for_metafield.size] = sku_tag %}
    {% else %}
      {% if customer_tags contains sku_tag %}
        {% assign job["tags_to_remove"][job.tags_to_remove.size] = sku_tag %}
      {% endif %}
    {% endif %}
  {% endfor %}

  {% assign job["skus_for_metafield"] = job.skus_for_metafield | sort %}

  {% assign jobs[jobs.size] = job %}
{% endif %}

{% for job in jobs %}
  {% if options.test_mode__boolean %}
    {% action "echo" job %}
    {% continue %}
  {% endif %}

  {% assign mutations = array %}

  {% if job.skus_in_metafield != job.skus_for_metafield %}
    {% capture mutation %}
      customerUpdate(
        input: {
          id: {{ job.customer_id | json }}
          metafields: [
            {
              {% if job.metafield_id %}
                id: {{ job.metafield_id | json }}
              {% endif %}
              namespace: {{ metafield_namespace | json }}
              key: {{ metafield_key | json }}
              value: {{ job.skus_for_metafield | json | json }}
              valueType: JSON_STRING
            }
          ]
        }
      ) {
        userErrors {
          field
          message
        }
      }
    {% endcapture %}

    {% assign mutations[mutations.size] = mutation %}
  {% endif %}

  {% assign tags_net_count = object.tags.size | plus: job.tags_to_add.size | minus: job.tags_to_remove.size %}
  {% if tags_net_count > 250 %}
    {% assign tag_count_to_drop = tags_net_count | minus: 250 %}
    {% for i in (1..tag_count_to_drop) %}
      {% assign job["tags_to_add"] = job.tags_to_add | remove_tag: job.tags_to_add.last %}
    {% endfor %}

    {% log %}
      "Had to drop {{ tag_count_to_drop }} tag(s) in order to meet the 250-tag cap"
    {% endlog %}
  {% endif %}

  {% if job.tags_to_remove != empty %}
    {% capture mutation %}
      tagsRemove(
        id: {{ job.customer_id | json }}
        tags: {{ job.tags_to_remove | json }}
      ) {
        userErrors {
          field
          message
        }
      }
    {% endcapture %}
    {% assign mutations[mutations.size] = mutation %}
  {% endif %}

  {% if job.tags_to_add != empty %}
    {% capture mutation %}
      tagsAdd(
        id: {{ job.customer_id | json }}
        tags: {{ job.tags_to_add | json }}
      ) {
        userErrors {
          field
          message
        }
      }
    {% endcapture %}
    {% assign mutations[mutations.size] = mutation %}
  {% endif %}

  {% if mutations != empty %}
    {% action "shopify" %}
      mutation {
        {{ mutations | join: newline }}
      }
    {% 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
Ignore refunded purchases
true
Test mode
true