Auto-tag customers having a rolling minimum total spend, with Mechanic.

Mechanic is a development and ecommerce automation platform for Shopify. :)

Auto-tag customers having a rolling minimum total spend

Use this task to tag customers who reach a certain spending threshold, by scanning a rolling period of order history. Useful for rewarding customers who keep a consistent spend total.

Runs Occurs when a user manually triggers the task, Occurs every day at midnight (in local time), Occurs when a bulk operation is completed, Occurs whenever an order is created, and Occurs whenever an order is updated. Configuration includes minimum total spent, customer tag to apply, days of order history to consider, and only monitor customers having this tag.

15-day free trial – unlimited tasks

Documentation

Use this task to tag customers who reach a certain spending threshold, by scanning a rolling period of order history. Useful for rewarding customers who keep a consistent spend total.

Run this task manually to scan all of your customers. This may take some time!

This task will also scan all customers on a nightly basis, and will run for a single customer every time a customer's order is paid or cancelled.

Note: By default, Mechanic only scans the last 60 days of order history. To change this, enable the option in Mehanic's 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
mechanic/scheduler/daily
mechanic/shopify/bulk_operation
shopify/orders/create
shopify/orders/updated
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
minimum total spent (number, required), customer tag to apply (required), days of order history to consider (number, required), only monitor customers having this tag
Code
{% assign minimum_total_spent = options.minimum_total_spent__number_required %}
{% assign customer_tag_to_apply = options.customer_tag_to_apply__required %}
{% assign days_of_order_history = options.days_of_order_history_to_consider__number_required %}
{% assign monitor_customer_tag = options.only_monitor_customers_having_this_tag %}

{% assign days_in_seconds = days_of_order_history | times: 24 | times: 60 | times: 60 %}
{% assign min_created_at = "now" | date: "%s" | times: 1 | minus: days_in_seconds %}
{% assign min_date_created_at = min_created_at | date: "%F" %}

{% if monitor_customer_tag == customer_tag_to_apply %}
  {% error "The two customer tag values must be different. Please change either 'Customer tag to apply' or 'Only monitor customers having this tag'." %}
{% endif %}

{% capture orders_search_query -%}
  created_at:>{{ min_date_created_at }} financial_status:paid,partially_paid,partially_refunded
{%- endcapture %}

{% if event.topic == "shopify/orders/create" or event.topic == "shopify/orders/updated" %}
  {% assign customer_tags = order.customer.tags | split: ", " %}

  {% if monitor_customer_tag != blank %}
    {% unless customer_tags contains monitor_customer_tag %}
      {% log "Customer does not have the required tag for monitoring; skipping." %}
      {% break %}
    {% endunless %}
  {% endif %}

  {% log orders_search_query: orders_search_query %}

  {% assign customer = hash %}
  {% assign customer["id"] = order.customer.admin_graphql_api_id %}
  {% assign customer["email"] = order.customer.email %}
  {% assign customer["tags"] = customer_tags %}
  {% assign customer["orders"] = array %}

  {% assign cursor = nil %}

  {% for n in (1..10) %}
    {% capture query %}
      query {
        customer(id: {{ order.customer.admin_graphql_api_id | json }}) {
          orders(
            first: 250
            after: {{ cursor | json }}
            query: {{ orders_search_query | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              id
              name
              createdAt
              displayFinancialStatus
              transactions {
                status
                kind
                amountSet {
                  shopMoney {
                    amount
                  }
                }
              }
            }
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% assign customer["orders"]
      = result.data.customer.orders.nodes
      | default: array
      | concat: customer["orders"]
    %}

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

  {% assign customers = array | push: customer %}

{% elsif event.topic == "mechanic/user/trigger" or event.topic == "mechanic/scheduler/daily" %}
  {% assign customers_search_query = "orders_count:>0" %}

  {% if monitor_customer_tag != blank %}
    {% capture customers_search_query -%}
      {{ customers_search_query }} AND tag:{{ monitor_customer_tag | json }}
    {%- endcapture %}
  {% endif %}

  {% log
    customers_search_query: customers_search_query,
    orders_search_query: orders_search_query
  %}

  {% capture bulk_operation_query %}
    query {
      customers(
        query: {{ customers_search_query | json }}
      ) {
        edges {
          node {
            __typename
            id
            displayName
            email
            tags
            orders(
              query: {{ orders_search_query | json }}
            ) {
              edges {
                node {
                  __typename
                  id
                  name
                  createdAt
                  displayFinancialStatus
                  transactions {
                    status
                    kind
                    amountSet {
                      shopMoney {
                        amount
                      }
                    }
                  }
                }
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% action "shopify" %}
    mutation {
      bulkOperationRunQuery(
        query: {{ bulk_operation_query | json }}
      ) {
        bulkOperation {
          id
          status
        }
        userErrors {
          field
          message
        }
      }
    }
  {% endaction %}

  {% break %}

{% elsif event.topic == "mechanic/shopify/bulk_operation" %}
  {% assign bulk_customers = bulkOperation.objects | where: "__typename", "Customer" %}
  {% assign bulk_orders = bulkOperation.objects | where: "__typename", "Order" %}

  {% assign customers = array %}

  {% for bulk_customer in bulk_customers %}
    {% assign customer = hash %}
    {% assign customer["id"] = bulk_customer.id %}
    {% assign customer["email"] = bulk_customer.email %}
    {% assign customer["tags"] = bulk_customer.tags %}
    {% assign customer["orders"]
      = bulk_orders
      | where: "__parentId", bulk_customer.id
      | default: array
    %}
    {% assign customers = customers | push: customer %}
  {% endfor %}
{% endif %}

{% if event.preview %}
  {% capture customers_json %}
    [
      {
        "id": "gid://shopify/Customer/1234567890",
        "email": "customer@example.com",
        "orders": [
          {
            "id": "gid://shopify/Order/1234567890",
            "transactions": [
              {
                "status": "SUCCESS",
                "kind": "SALE",
                "amountSet": {
                  "shopMoney": {
                    "amount": {{ minimum_total_spent | plus: 100.0 | json }}
                  }
                }
              },
              {
                "status": "SUCCESS",
                "kind": "REFUND",
                "amountSet": {
                  "shopMoney": {
                    "amount": "99.00"
                  }
                }
              }
            ]
          }
        ]
      }
    ]
  {% endcapture %}

  {% assign customers = customers_json | parse_json %}
{% endif %}

{% for customer in customers %}
  {% assign customer_total = 0.0 %}
  {% assign customer_orders_count = 0 %}

  {% for order in customer.orders %}
    {% for transaction in order.transactions %}
      {% if transaction.status != "SUCCESS" %}
        {% continue %}
      {% endif %}

      {% if transaction.kind == "REFUND" %}
        {% assign customer_total = customer_total | minus: transaction.amountSet.shopMoney.amount %}

      {% elsif transaction.kind == "SALE" or transaction.kind == "CAPTURE" %}
        {% assign customer_total = customer_total | plus: transaction.amountSet.shopMoney.amount %}
      {% endif %}
    {% endfor %}

    {% assign customer_orders_count = customer_orders_count | plus: 1 %}
  {% endfor %}

  {% assign add_tag = false %}
  {% assign remove_tag = false %}

  {% capture log_line_prefix %}{{ customer.email | default: customer.id }} spent {{ customer_total }} across {{ customer_orders_count }} orders, {% endcapture %}

  {% if customer_total >= minimum_total_spent %}
    {% if customer.tags contains customer_tag_to_apply %}
      {% log %}{{ log_line_prefix | append: "qualifying them for the tag. They were already tagged, so there's nothing to do." | json }}{% endlog %}

    {% else %}
      {% log %}{{ log_line_prefix | append: "qualifying them for the tag" | json }}{% endlog %}
      {% assign add_tag = true %}
    {% endif %}

  {% else %}
    {% if customer.tags contains customer_tag_to_apply %}
      {% log %}{{ log_line_prefix | append: "and did not qualify for the tag" | json }}{% endlog %}
      {% assign remove_tag = true %}

    {% else %}
      {% log %}{{ log_line_prefix | append: "and did not qualify for the tag. They were not previously tagged, so there's nothing to do." | json }}{% endlog %}
    {% endif %}
  {% endif %}

  {% if add_tag or remove_tag %}
    {% action "shopify" %}
      mutation {
      {% if add_tag %}tagsAdd{% elsif remove_tag %}tagsRemove{% endif %}(
          id: {{ customer.id | json }}
          tags: {{ customer_tag_to_apply | json }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endif %}
{% endfor %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Days of order history to consider
30