Cancel and close unpaid orders after x hours/days, with Mechanic.

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

Cancel and close unpaid orders after x hours/days

This task scans for orders that are more than X days or hours old that have a financial status of "pending", and ensures that they are all closed/archived and cancelled. Pending orders that are already closed will be cancelled, and pending orders that are already cancelled will be closed. Optionally, choose to add a tag to such orders, and whether to restock line items.

Runs Occurs every day at midnight (in local time) and Occurs when a user manually triggers the task. Configuration includes only process orders having this tag, ignore orders having this tag, period to wait before checking each order, period to wait is in hours, period to wait is in days, tag to add to the order, cancellation reason to set, restock line items, send cancellation email to customer, and test mode.

15-day free trial – unlimited tasks

Documentation

This task scans for orders that are more than X days or hours old that have a financial status of "pending", and ensures that they are all closed/archived and cancelled. Pending orders that are already closed will be cancelled, and pending orders that are already cancelled will be closed. Optionally, choose to add a tag to such orders, and whether to restock line items.

If configured with an interval in hours, this task will run hourly. If configured with an interval in days, the task will run every night at midnight, in your store's local timezone. Run this task manually to perform the scan on demand.

Run first using test mode, to ensure expected results before running without it.

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
{% if options.period_to_wait_is_in_hours__boolean %}
  mechanic/scheduler/hourly
{% elsif options.period_to_wait_is_in_days__boolean %}
  mechanic/scheduler/daily
{% endif %}
mechanic/user/trigger
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
only process orders having this tag, ignore orders having this tag, period to wait before checking each order (number, required), period to wait is in hours (boolean), period to wait is in days (boolean), tag to add to the order, cancellation reason to set, restock line items (boolean), send cancellation email to customer (boolean), test mode (boolean)
Code
{% assign only_process_orders_having_this_tag = options.only_process_orders_having_this_tag %}
{% assign ignore_orders_having_this_tag = options.ignore_orders_having_this_tag %}
{% assign period_to_wait_before_checking_each_order = options.period_to_wait_before_checking_each_order__number_required %}
{% assign period_to_wait_is_in_hours = options.period_to_wait_is_in_hours__boolean %}
{% assign period_to_wait_is_in_days = options.period_to_wait_is_in_days__boolean %}
{% assign tag_to_add_to_the_order = options.tag_to_add_to_the_order %}
{% assign cancellation_reason_to_set = options.cancellation_reason_to_set | default: "other" %}
{% assign restock_line_items = options.restock_line_items__boolean %}
{% assign send_cancellation_email_to_customer = options.send_cancellation_email_to_customer__boolean %}
{% assign test_mode = options.test_mode__boolean %}

{% comment %}
  -- check that a valid cancellation reason has been configured; it will default to 'other' if left blank
{% endcomment %}

{% assign valid_cancellation_reasons = "customer,declined,fraud,inventory,other,staff" | split: "," %}

{% unless valid_cancellation_reasons contains cancellation_reason_to_set %}
  {% error %}
    {{ "Cancellation reason " | append: cancellation_reason_to_set | append: " - must be one of 'customer', 'declined', 'fraud', 'inventory', 'other', or 'staff'." | json }}
  {% enderror %}
{% endunless %}

{% comment %}
  -- check for positive waiting period and that only one unit type is chosen
{% endcomment %}

{% if period_to_wait_before_checking_each_order <= 0 %}
  {% error "Period must be positive! :)" %}

{% elsif period_to_wait_is_in_hours == false and period_to_wait_is_in_days == false %}
  {% error "Choose either 'Period to wait is in hours' or 'Period to wait is in days'." %}

{% elsif period_to_wait_is_in_hours and period_to_wait_is_in_days %}
  {% error "Choose exactly one of 'Period to wait is in hours' or 'Period to wait is in days'. :)" %}
{% endif %}

{% assign period_unit = "days" %}

{% if period_to_wait_is_in_hours %}
  {% assign period_unit = "hours" %}
{% endif %}

{% capture cutoff_period -%}
  -{{ period_to_wait_before_checking_each_order }} {{ period_unit }}
{%- endcapture %}

{% comment %}
  -- cutoff_date is used to limit the orders to those that were processed on or before the cutoff date
  -- cutoff_date_s is used later for a fine grain check of the order processed at date
{% endcomment %}

{% assign cutoff_date = "now" | date: "%F", advance: cutoff_period %}
{% assign cutoff_date_s = "now" | date: "%s", advance: cutoff_period | times: 1 %}

{% log
  cutoff_period: cutoff_period,
  cutoff_date: cutoff_date,
  cutoff_date_s: cutoff_date_s
%}

{% if test_mode %}
  {% assign test_mode_summaries = array %}
{% endif %}

{% comment %}
  -- create the query that will be used to filter orders
{% endcomment %}

{% capture orders_query %}
  financial_status:pending processed_at:<{{ cutoff_date }}
  {% if only_process_orders_having_this_tag != blank -%}
    tag:{{ only_process_orders_having_this_tag | strip | json }}
  {%- endif %}
  {% if ignore_orders_having_this_tag != blank -%}
    tag_not:{{ ignore_orders_having_this_tag | strip | json }}
  {%- endif %}
{% endcapture %}

{% assign orders_query = orders_query | strip_newlines | strip %}

{% log orders_query: orders_query %}

{% assign cursor = nil %}

{% comment %}
  -- query and process all orders that meet the query filter
  -- reverse the creation order to get the most recent first (in case this instance is not configured to read all orders)
{% endcomment %}

{% for n in (0..100) %}
  {% capture query %}
    query {
      orders(
        first: 250
        after: {{ cursor | json }}
        query: {{ orders_query | json }}
        sortKey: CREATED_AT
        reverse: true
      ) {
        pageInfo {
          hasNextPage
          endCursor
        }
        nodes {
          id
          name
          processedAt
          cancelledAt
          closedAt
          tags
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "orders": {
            "nodes": [
              {
                "id": "gid://shopify/Order/1234567890",
                "name": "#PREVIEW",
                "processedAt": "1990-01-01",
                "cancelledAt": null,
                "closedAt": null,
                "tags": {{ only_process_orders_having_this_tag | strip | json }}
              }
            ]
          }
        }
      }
    {% endcapture %}

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

  {% for order in result.data.orders.nodes %}
    {% comment %}
      -- exclude orders that occurred after the calculated cutoff date (in epoch seconds, to avoid timezone conversions)
    {% endcomment %}

    {% assign processed_at_s = order.processedAt | date: "%s" | times: 1 %}

    {% if processed_at_s > cutoff_date_s %}
      {% continue %}
    {% endif %}

    {% comment %}
      -- build a summary for output in the task event run logs, and to decide on which mutations to run
    {% endcomment %}

    {% assign summary = hash %}
    {% assign summary["order_name"] = order.name %}
    {% assign summary["order_id"] = order.id %}
    {% assign summary["order_processed_at"] = order.processedAt | date: "%FT%T%:z" %}
    {% assign summary["threshold_processed_at"] = cutoff_date_s | date: "%FT%T%:z" %}
    {% assign summary["order_cancelled_at"] = order.cancelledAt | date: "%FT%T%:z" %}
    {% assign summary["order_closed_at"] = order.closedAt | date: "%FT%T%:z" %}

    {% if order.cancelledAt == blank %}
      {% assign summary["qualifies_for_cancellation"] = true %}
    {% else %}
      {% assign summary["qualifies_for_cancellation"] = false %}
    {% endif %}

    {% if order.closedAt == blank %}
      {% assign summary["qualifies_for_closing"] = true %}
    {% else %}
      {% assign summary["qualifies_for_closing"] = false %}
    {% endif %}

    {% assign summary["qualifies_for_tagging"] = false %}

    {% if tag_to_add_to_the_order != blank %}
      {% assign order_tags = order.tags | join: "," | downcase | split: "," %}
      {% assign order_tag_to_match = tag_to_add_to_the_order | downcase | strip %}

      {% unless order_tags contains order_tag_to_match %}
        {% assign summary["qualifies_for_tagging"] = true %}
      {% endunless %}
    {% endif %}

    {% unless summary.qualifies_for_cancellation or summary.qualifies_for_closing or summary.qualifies_for_tagging %}
      {% continue %}
    {% endunless %}

    {% if test_mode %}
      {% assign test_mode_summaries[test_mode_summaries.size] = summary %}
      {% continue %}
    {% endif %}

    {% log summary %}

    {% if summary.qualifies_for_cancellation %}
      {% comment %}
        -- cancel the order with configured options; this will also automatically close the order
        -- if possible, the order will be voided; this is not configurable in this mutation
        -- refunds are set to false and not configurable in the task because these are unpaid orders
      {% endcomment %}

      {% action "shopify" %}
        mutation {
          orderCancel(
            orderId: {{ order.id | json }}
            notifyCustomer: {{ send_cancellation_email_to_customer | json }}
            reason: {{ cancellation_reason_to_set | upcase }}
            refund: false
            restock: {{ restock_line_items | json }}
          ) {
            job {
              id
            }
            orderCancelUserErrors {
              code
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}


    {% if summary.qualifies_for_closing and summary.qualifies_for_cancellation == false %}
      {% comment %}
        -- the orderCancel mutation will also close the order, so do not try to close it again if cancelling above as well
      {% endcomment %}

      {% action "shopify" %}
        mutation {
          orderClose(
            input: {
              id: {{ order.id | json }}
            }
          ) {
            order {
              closed
              closedAt
            }
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}

    {% if summary.qualifies_for_tagging %}
      {% action "shopify" %}
        mutation {
          tagsAdd(
            id: {{ order.id | json }}
            tags: {{ tag_to_add_to_the_order | json }}
          ) {
            userErrors {
              field
              message
            }
          }
        }
      {% endaction %}
    {% endif %}
  {% endfor %}

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

{% if test_mode %}
  {% log
    orders_count: test_mode_summaries.size,
    order_summaries: test_mode_summaries
  %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Period to wait before checking each order
1
Period to wait is in days
true
Cancellation reason to set
other
Test mode
true