Mechanic Get Mechanic
Task library

Delete draft orders older than 30 days

Keep your draft order list tidy - use this task to automatically delete orders that are older than a configurable number of days.

Try this task

When it runs

Occurs when a user manually triggers the task

What you choose

  • Days to wait before deleting a draft order
  • Test mode
  • Run daily
Task code and subscriptions

You can edit the Liquid code after installing this task. View on GitHub or ask a question in the Mechanic Slack community.

Subscriptions

mechanic/user/trigger
{% if options.run_daily__boolean %}mechanic/scheduler/daily{% endif %}
How task subscriptions work

Option types and flags

Task code

{% assign now_s = "now" | date: "%s" | times: 1 %}
{% assign x_days_ago_interval_s = options.days_to_wait_before_deleting_a_draft_order__number_required | times: 24 | times: 60 | times: 60 %}
{% assign x_days_ago_s = now_s | minus: x_days_ago_interval_s %}
{% assign x_days_ago_date = x_days_ago_s | date: "%Y-%m-%d" %}

{% assign ids_to_delete = array %}

{% assign cursor = nil %}

{% for n in (0..100) %}
  {% capture query %}
    query {
      draftOrders(
        first: 250
        after: {{ cursor | json }}
        query: {{ "created_at:<" | append: x_days_ago_date | json }}
        sortKey: ID
      ) {
        edges {
          cursor
          node {
            id
            name
            createdAt
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% for draftOrder_edge in result.data.draftOrders.edges %}
    {% assign draftOrder = draftOrder_edge.node %}

    {% assign ids_to_delete[ids_to_delete.size] = draftOrder.id %}
  {% endfor %}

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

{% if event.preview %}
  {% assign ids_to_delete[0] = "gid://shopify/DraftOrder/1234567890" %}
{% endif %}

{% if options.test_mode__boolean %}
  {% capture message -%}
    Test mode: found {{ ids_to_delete.size }} qualifying draft order(s). Disable test mode and run again to delete draft orders that qualify during that run.
  {%- endcapture %}

  {% action "echo" message %}
{% else %}
  {% for id in ids_to_delete %}
    {% action "shopify" %}
      mutation {
        draftOrderDelete(
          input: {
            id: {{ id | json }}
          }
        ) {
          userErrors {
            field
            message
          }
        }
      }
    {% endaction %}
  {% endfor %}
{% endif %}
Mechanic Liquid reference

Default option values

Days to wait before deleting a draft order
30
Test mode
true