Reissue single-use discount codes after order cancellation, with Mechanic.

Mechanic is an automation development platform for Shopify. :)

Reissue single-use discount codes after order cancellation

by Isaac Bowen (team@usemechanic.com)

This task watches for cancellations of orders that have a single-use discount code. When one is found, this task creates a new single-use discount code, for the related customer, and emails it to them.

Runs when an order is cancelled. Configuration includes ignore discount codes containing this text, email subject, email body, and email bcc.

15-day free trial – unlimited tasks

Documentation

This task watches for cancellations of orders that have a single-use discount code. When one is found, this task creates a new single-use discount code, for the related customer, and emails it to them.

This task only supports basic discounts, having up to 250 products or collections (if any). Shipping discounts and buy-one-get-one discounts are not supported.

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 cancelled (shopify/orders/cancelled)
Options
ignore discount codes containing this text, email subject (required), email body (required, multiline), email bcc (email)
Script
{% assign discount_code = order.discount_codes.first.code %}

{% if event.preview and discount_code == blank %}
  {% assign discount_code = "ABCD1234" %}
{% endif %}

{% assign discount_code_qualifies = true %}

{% if discount_code == blank %}
  {% assign discount_code_qualifies = false %}
{% elsif options.ignore_discount_codes_containing_this_text != blank %}
  {% assign discount_code_downcase = discount_code | downcase %}
  {% assign ignore_downcase = options.ignore_discount_codes_containing_this_text | strip | downcase %}
  {% if discount_code_downcase contains ignore_downcase %}
    {% assign discount_code_qualifies = false %}
  {% endif %}
{% endif %}

{% if event.preview or discount_code_qualifies %}
  {% assign reissued_discount_code = discount_code | append: order.order_number %}

  {% capture query %}
    query {
      codeDiscountNodeByCode(code: {{ discount_code | json }}) {
        id
        codeDiscount {
          __typename
          ... on DiscountCodeBasic {
            title
            usageLimit
            codeCount
            startsAt
            endsAt
            appliesOncePerCustomer
            summary
            minimumRequirement {
              __typename
              ... on DiscountMinimumQuantity {
                greaterThanOrEqualToQuantity
              }
              ... on DiscountMinimumSubtotal {
                greaterThanOrEqualToSubtotal {
                  amount
                  currencyCode
                }
              }
            }
            customerGets {
              items {
                __typename
                ... on AllDiscountItems {
                  allItems
                }
                ... on DiscountProducts {
                  productVariants(first: 250) {
                    edges {
                      node {
                        id
                      }
                    }
                  }
                  products(first: 250) {
                    edges {
                      node {
                        id
                      }
                    }
                  }
                }
                ... on DiscountCollections {
                  collections(first: 250) {
                    edges {
                      node {
                        id
                      }
                    }
                  }
                }
              }
              value {
                __typename
                ... on DiscountAmount {
                  amount {
                    amount
                    currencyCode
                  }
                  appliesOnEachItem
                }
                ... on DiscountOnQuantity {
                  effect {
                    ... on DiscountPercentage {
                      percentage
                    }
                  }
                  quantity {
                    quantity
                  }
                }
                ... on DiscountPercentage {
                  percentage
                }
              }
            }
            customerSelection {
              __typename
              ... on DiscountCustomers {
                customers {
                  id
                }
              }
              ... on DiscountCustomerAll {
                allCustomers
              }
              ... on DiscountCustomerSavedSearches {
                savedSearches {
                  id
                }
              }
            }
          }
        }
      }
    }
  {% endcapture %}

  {% assign result = query | shopify %}

  {% if event.preview %}
    {% capture result_json %}
      {
        "data": {
          "codeDiscountNodeByCode": {
            "id": "gid://shopify/DiscountCodeNode/1234567890",
            "codeDiscount": {
              "__typename": "DiscountCodeBasic",
              "title": "DISCOUNT",
              "usageLimit": 1,
              "codeCount": 1,
              "startsAt": "2019-11-04T20:06:44Z",
              "endsAt": "2019-11-13T04:59:59Z",
              "appliesOncePerCustomer": true,
              "summary": "50% off No shipping • Minimum purchase of $5.00 • For Isaac Bowen • One use per customer",
              "minimumRequirement": {
                "__typename": "DiscountMinimumSubtotal",
                "greaterThanOrEqualToSubtotal": {
                  "amount": "5.0",
                  "currencyCode": "USD"
                }
              },
              "customerGets": {
                "items": {
                  "__typename": "DiscountProducts",
                  "productVariants": {
                    "edges": []
                  },
                  "products": {
                    "edges": [
                      {
                        "node": {
                          "id": "gid://shopify/Product/1234567890"
                        }
                      }
                    ]
                  }
                },
                "value": {
                  "__typename": "DiscountPercentage",
                  "percentage": 0.5
                }
              },
              "customerSelection": {
                "__typename": "DiscountCustomers",
                "customers": [
                  {
                    "id": "gid://shopify/Customer/1234567890"
                  }
                ]
              }
            }
          }
        }
      }
    {% endcapture %}

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

  {% assign discountNode = result.data.codeDiscountNodeByCode.codeDiscount %}

  {% log discount_summary: discountNode.summary %}

  {% if discountNode == nil %}
    {% log "No discount found." %}
  {% elsif discountNode.__typename != "DiscountCodeBasic" %}
    {% log "This task only supports basic discounts. It does not support free shipping, or buy-one-get-one." %}
  {% elsif discountNode.appliesOncePerCustomer == false and discountNode.usageLimit != 1 %}
    {% log "This discount can be used multiple times, and so is not applicable." %}
  {% else %}
    {% action "shopify" %}
      mutation {
        discountCodeBasicCreate(
          basicCodeDiscount: {
            title: {{ reissued_discount_code | json }}
            code: {{ reissued_discount_code | json }}
            startsAt: {{ discountNode.startsAt | json }}
            endsAt: {{ discountNode.endsAt | json }}
            usageLimit: {{ discountNode.usageLimit | json }}
            appliesOncePerCustomer: {{ discountNode.appliesOncePerCustomer | json }}
            {% if discountNode.minimumRequirement.__typename == "DiscountMinimumQuantity" %}
              minimumRequirement: {
                quantity: 0
              }
            {% elsif discountNode.minimumRequirement.__typename == "DiscountMinimumSubtotal" %}
              minimumRequirement: {
                subtotal: {
                  greaterThanOrEqualToSubtotal: {{ discountNode.minimumRequirement.greaterThanOrEqualToSubtotal.amount | json }}
                }
              }
            {% endif %}
            customerGets: {
              items: {
                {% if discountNode.customerGets.items.__typename == "AllDiscountItems" %}
                  all: {{ discountNode.customerGets.items.allItems | json }}
                {% elsif discountNode.customerGets.items.__typename == "DiscountProducts" %}
                  products: {
                    productsToAdd: {{ discountNode.customerGets.items.products.edges | map: "node" | map: "id" | json }}
                    productVariantsToAdd: {{ discountNode.customerGets.items.productVariants.edges | map: "node" | map: "id" | json }}
                  }
                {% elsif discountNode.customerGets.items.__typename == "DiscountCollections" %}
                  collections: {
                    add: {{ discountNode.customerGets.items.collections.edges | map: "node" | map: "id" | json }}
                  }
                {% endif %}
              }
              value: {
                {% if discountNode.customerGets.value.__typename == "DiscountAmount" %}
                  discountAmount: {
                    amount: {{ discountNode.customerGets.value.amount.amount | json }}
                    appliesOnEachItem: {{ discountNode.customerGets.value.appliesOnEachItem | json }}
                  }
                {% elsif discountNode.customerGets.value.__typename == "DiscountOnQuantity" %}
                  discountOnQuantity: {
                    quantity: {{ discountNode.customerGets.value.quantity.quantity | json }}
                    effect: {
                      percentage: {{ discountNode.customerGets.value.effect.percentage | json }}
                    }
                  }
                {% elsif discountNode.customerGets.value.__typename == "DiscountPercentage" %}
                  percentage: {{ discountNode.customerGets.value.percentage | json }}
                {% endif %}
              }
            }
            customerSelection: {
              {% if discountNode.customerSelection.__typename == "DiscountCustomers" %}
                customers: {
                  add: {{ discountNode.customerSelection.customers | map: "id" | json }}
                }
              {% elsif discountNode.customerSelection.__typename == "DiscountCustomerAll" %}
                all: {{ discountNode.customerSelection.allCustomers | json }}
              {% elsif discountNode.customerSelection.__typename == "DiscountCustomerSavedSearches" %}
                customerSavedSearches: {
                  add: {{ discountNode.customerSelection.savedSearches | map: "id" | json }}
                }
              {% endif %}
            }
          }
        ) {
          codeDiscountNode {
            id
            codeDiscount {
              ... on DiscountCodeBasic {
                summary
              }
            }
          }
          userErrors {
            code
            field
            message
          }
        }
      }
    {% endaction %}

    {% action "email" %}
      {
        "to": {{ order.email | json }},
        "subject": {{ options.email_subject__required | json }},
        "body": {{ options.email_body__required_multiline | replace: "REISSUED_DISCOUNT_CODE", reissued_discount_code | newline_to_br | json }},
        "reply_to": {{ shop.customer_email | json }},
        "from_display_name": {{ shop.name | json }},
        "bcc": {{ options.email_bcc__email | json }}
      }
    {% endaction %}
  {% endif %}
{% endif %}
Mechanic tasks are written in Liquid, which makes them easy to write and easy to modify. Learn more about our platform.
Defaults
Email subject
We've issued you a new discount code
Email body
Hello,

Now that order {{ order.name }} has been cancelled, we wanted to make sure you have another chance to use your discount.

Your new discount code: REISSUED_DISCOUNT_CODE

Thanks,
{{ shop.name }}