Auto-tag new online orders by web browser, with Mechanic.

Mechanic is an automation development platform for Shopify. :)

Auto-tag new online orders by web browser

by Isaac Bowen (team@usemechanic.com)

This task monitors incoming orders, and tags them with information about the customer's web browser.

Runs when an order is created and when a user triggers the task. Configuration includes include browser version.

15-day free trial – unlimited tasks

Documentation

This task will monitor incoming orders, and tag them if the browser name can be derived from the order information.

Run this task manually to scan your existing orders, and tag them as appropriate.

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 created (shopify/orders/create)
when a user triggers the task (mechanic/user/trigger)
Options
include browser version (boolean)
Script
{% assign orders = array %}
{% if event.preview %}
  {% assign orders[0] = '{"admin_graphql_api_id":"gid://shopify/Order/1234567890"}' | parse_json %}
{% elsif event.topic contains "shopify/orders/" %}
  {% assign orders[0] = order %}
{% elsif event.topic == "mechanic/user/trigger" %}
  {% assign orders = shop.orders.any %}
{% endif %}

{% for order in orders %}
  {% assign user_agent = order.client_details.user_agent %}

  {% if event.preview and user_agent == blank %}
    {% assign user_agent = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.100 Safari/537.36" %}
  {% elsif user_agent == blank %}
    {% continue %}
  {% endif %}

  {% assign browser = user_agent | browser %}
  {% assign order_tags = order.tags | split: ", " %}
  {% assign tag_to_add = browser.name %}
  {% if options.include_browser_version__boolean %}
    {% assign tag_to_add = tag_to_add | append: " " | append: browser.version | strip %}
  {% endif %}

  {% unless order_tags contains tag_to_add %}
    {% action "shopify" %}
      mutation {
        tagsAdd(
          id: {{ order.admin_graphql_api_id | json }}
          tags: {{ tag_to_add | json }}
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endunless %}
{% endfor %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.