Accept a maximum number of orders per hour, with Mechanic.

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

Accept a maximum number of orders per hour

This task works by monitoring the number of orders created per hour, and clearing the inventory for all in-stock items when the hourly order limit is reached. Optionally, this task can restore inventory to its original levels at minute zero of the next hour, or on demand.

Runs Occurs whenever an order is created and Occurs every hour. Configuration includes maximum hourly orders, only count orders matching this query, only clear inventory for products with this tag, restore inventory levels the next hour, and restore inventory levels on demand.

15-day free trial – unlimited tasks

Documentation

This task works by monitoring the number of orders created per hour, and clearing the inventory for all in-stock items when the hourly order limit is reached. Optionally, this task can restore inventory to its original levels at minute zero of the next hour, or on demand.

This task works by setting your inventory to zero when the hourly order limit is reached. (Specifically, this means setting inventory levels to 0 for all items that have a greater-than-zero inventory level.) There are no popups, or any specific messaging - your inventory will simply be dropped to zero, and if your shop is configured to stop selling out-of-stock products, your customers will be prevented from making additional purchases.

Optionally, this task can restore inventory to its original levels at midnight the next hour, or on demand. (Restore levels on demand by enabling this option, then using the "Run task" button.)

This task does not work well when you have multiple orders per minute, and we do not recommend using it for high-volume stores. It works by counting the current hour's orders, at the time of each purchase - if the current count exactly equals your maximum, it performs the inventory reset. Because that counting process can take a few seconds, receiving multiple orders per minute can result in missing that very specific window when the current count exactly equals your maximum.

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
shopify/orders/create
{% if options.restore_inventory_levels_the_next_hour__boolean %}
  mechanic/scheduler/hourly
{% endif %}
{% if options.restore_inventory_levels_on_demand__boolean %}
  mechanic/user/trigger
{% endif %}
Tasks use subscriptions to sign up for specific kinds of events. Learn more
Options
maximum hourly orders (number, required), only count orders matching this query, only clear inventory for products with this tag, restore inventory levels the next hour (boolean), restore inventory levels on demand (boolean)
Code
{% comment %}
  Options order:

  {{ options.maximum_hourly_orders__number_required }}
  {{ options.only_count_orders_matching_this_query }}
  {{ options.only_clear_inventory_for_products_with_this_tag }}
  {{ options.restore_inventory_levels_the_next_hour__boolean }}
  {{ options.restore_inventory_levels_on_demand__boolean }}
{% endcomment %}

{% if options.maximum_hourly_orders__number_required <= 0 %}
  {% error "'Maximum hourly orders' must be at least 1. :)" %}
{% endif %}

{% assign inventory_is_zeroed_cache_key = "inventory_is_zeroed:" | append: task.id %}
{% assign inventory_is_zeroed = cache[inventory_is_zeroed_cache_key] | default: false %}

{% if event.topic contains "shopify/orders" %}
  {% assign cursor = nil %}
  {% assign orders_this_hour = 0 %}
  {% assign previous_hour = "now" | date: "%Y-%m-%dT%H:00:00%z" %}
  {% assign previous_hour_s = previous_hour | date: "%s" %}
  {% assign base_cache_key = "inventory_to_restore:" | append: previous_hour_s %}

  {% capture orders_query %}
    created_at:>={{ previous_hour | json }} {{ options.only_count_orders_matching_this_query }}
  {% endcapture %}

  {% assign orders_query = orders_query | strip %}

  {% for n in (0..100) %}
    {% capture query %}
      query {
        orders(
          first: 250
          after: {{ cursor | json }}
          query: {{ orders_query | json }}
        ) {
          pageInfo {
            hasNextPage
            endCursor
          }
          nodes {
            id
          }
        }
      }
    {% endcapture %}

    {% assign result = query | shopify %}

    {% if event.preview %}
      {% assign inventory_is_zeroed = false %}

      {% capture result_json %}
        {
          "data": {
            "orders": {
              "nodes": [
                {% for n in (1..options.maximum_hourly_orders__number_required) %}
                  {
                    "id": "gid://shopify/Order/1234567890"
                  }{% unless forloop.last %},{% endunless %}
                {% endfor %}
              ]
            }
          }
        }
      {% endcapture %}

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

    {% assign orders_this_hour = orders_this_hour | plus: result.data.orders.nodes.size %}

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

  {% log orders_this_hour_thus_far: orders_this_hour, orders_query: orders_query, inventory_is_already_zeroed: inventory_is_zeroed %}

  {% if orders_this_hour >= options.maximum_hourly_orders__number_required and inventory_is_zeroed == false %}
    {% action "cache", "set", inventory_is_zeroed_cache_key, true %}

    {% assign cursor = nil %}
    {% assign inventory_adjustments = array %}

    {% for n in (0..2000) %}
      {% capture query %}
        query {
          inventoryItems(
            first: 3
            after: {{ cursor | json }}
          ) {
            pageInfo {
              hasNextPage
              endCursor
            }
            nodes {
              id
                variant {
                  product {
                    tags
                  }
                }
              inventoryLevels(first: 100) {
                nodes {
                  id
                  quantities(names: "available") {
                    name
                    quantity
                  }
                  location {
                    id
                  }
                }
              }
            }
          }
        }
      {% endcapture %}

      {% assign result = query | shopify %}

      {% if event.preview %}
        {% capture result_json %}
          {
            "data": {
              "inventoryItems": {
                "nodes": [
                  {
                    "id": "gid://shopify/InventoryItem/1234567890",
                    "variant": {
                      "product": {
                        "tags": [
                          {% if options.only_clear_inventory_for_products_with_this_tag != blank %}
                            {{ options.only_clear_inventory_for_products_with_this_tag | json }}
                          {% endif %}
                        ]
                      }
                    },
                    "inventoryLevels": {
                      "nodes": [
                        {
                          "id": "gid://shopify/InventoryLevel/1234567890?inventory_item_id=1234567890",
                          "quantities": [
                            {
                              "name": "available",
                              "quantity": 20
                            }
                          ],
                          "location": {
                            "id": "gid://shopify/Location/1234567890"
                          }
                        }
                      ]
                    }
                  }
                ]
              }
            }
          }
        {% endcapture %}

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

      {% for inventory_item in result.data.inventoryItems.nodes %}
        {% if options.only_clear_inventory_for_products_with_this_tag != blank %}
          {% unless inventory_item.variant.product.tags contains options.only_clear_inventory_for_products_with_this_tag %}
            {% continue %}
          {% endunless %}
        {% endif %}

        {% for inventory_level in inventory_item.inventoryLevels.nodes %}
          {% if inventory_level.quantities.first.quantity > 0 %}
            {% comment %}
              NOTE: use availble quantity in the hash to be stored in cache... however, a negative delta will be made in the mutation to zero out the inventory
            {% endcomment %}

            {% assign inventory_adjustment = hash %}
            {% assign inventory_adjustment["inventoryItemId"] = inventory_item.id %}
            {% assign inventory_adjustment["locationId"] = inventory_level.location.id %}
            {% assign inventory_adjustment["delta"] = inventory_level.quantities.first.quantity %}
            {% assign inventory_adjustments = inventory_adjustments | push: inventory_adjustment %}
          {% endif %}
        {% endfor %}
      {% endfor %}

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

    {% if inventory_adjustments == blank %}
      {% break %}
    {% endif %}

    {% assign groups_of_inventory_adjustments = inventory_adjustments | in_groups_of: 250, fill_with: false %}

    {% for group_of_inventory_adjustments in groups_of_inventory_adjustments %}
      {% action "shopify" %}
        mutation {
          inventoryAdjustQuantities(
            input: {
              reason: "correction"
              name: "available"
              changes: [
                {% for inventory_adjustment in group_of_inventory_adjustments -%}
                  {
                    inventoryItemId: {{ inventory_adjustment.inventoryItemId | json }}
                    locationId: {{ inventory_adjustment.locationId | json }}
                    delta: {{ inventory_adjustment.delta | times: -1 }}
                  }
                {%- endfor %}
              ]
            }
          ) {
            inventoryAdjustmentGroup {
              reason
              changes {
                name
                delta
                quantityAfterChange
                item {
                  id
                  sku
                }
                location {
                  name
                }
              }
            }
            userErrors {
              code
              field
              message
            }
          }
        }
      {% endaction %}

      {% comment %}
        -- store the inventory to restore in cache even if neither restore option is selected... just in case :)
      {% endcomment %}

      {% assign cache_key = base_cache_key | append: "_group" | append: forloop.index0 %}
      {% assign cache_value = hash %}
      {% assign cache_value["value"] = group_of_inventory_adjustments %}

      {% unless forloop.last %}
        {% assign next_cache_key = base_cache_key | append: "_group" | append: forloop.index %}
        {% assign cache_value["next_key"] = next_cache_key %}
      {% endunless %}

      {% action "cache", "set", cache_key, cache_value %}
    {% endfor %}
  {% endif %}

{% elsif event.topic == "mechanic/scheduler/hourly" or event.topic == "mechanic/user/trigger" %}
  {% action "cache", "del", inventory_is_zeroed_cache_key %}
  {% assign cache_keys = array %}

  {% assign hour_in_s = 60 | times: 60 %}
  {% assign previous_hour = "now" | date: "%s" | minus: hour_in_s | date: "%Y-%m-%dT%H:00:00%z" %}
  {% assign previous_hour_s = previous_hour | date: "%s" %}

  {% assign cache_key = "inventory_to_restore:" | append: previous_hour_s | append: "_group0" %}

  {% assign inventory_adjustments_cache_group = cache[cache_key] | default: hash %}

  {% if inventory_adjustments_cache_group == blank %}
    {% assign previous_hour = "now" | date: "%Y-%m-%dT%H:00:00%z" %}
    {% assign previous_hour_s = previous_hour | date: "%s" %}
    {% assign cache_key = "inventory_to_restore:" | append: previous_hour_s | append: "_group0" %}
    {% assign inventory_adjustments_cache_group = cache[cache_key] | default: hash %}
  {% endif %}

  {% if event.preview %}
    {% assign inventory_adjustment = hash %}
    {% assign inventory_adjustment["inventoryItemId"] = "gid://shopify/InventoryItem/1234567890" %}
    {% assign inventory_adjustment["locationId"] = "gid://shopify/Location/1234567890" %}
    {% assign inventory_adjustment["delta"] = 20 %}
    {% assign inventory_adjustments_cache_group["value"] = array | push: inventory_adjustment %}
  {% endif %}

  {% if inventory_adjustments_cache_group == blank %}
    {% error
      message: "No cached inventory data was found!",
      cache_key: cache_key
    %}
    {% break %}

  {% else %}
    {% for n in (0..1000) %}
      {% action "shopify" %}
        mutation {
          inventoryAdjustQuantities(
            input: {
              reason: "correction"
              name: "available"
              changes: {{ inventory_adjustments_cache_group.value | graphql_arguments }}
            }
          ) {
            inventoryAdjustmentGroup {
              reason
              changes {
                name
                delta
                quantityAfterChange
                item {
                  id
                  sku
                }
                location {
                  name
                }
              }
            }
            userErrors {
              code
              field
              message
            }
          }
        }
      {% endaction %}

      {% assign cache_keys = cache_keys | push: cache_key %}

      {% if inventory_adjustments_cache_group.next_key %}
        {% assign cache_key = inventory_adjustments_cache_group.next_key %}
        {% assign inventory_adjustments_cache_group = cache[cache_key] %}
      {% else %}
        {% break %}
      {% endif %}
    {% endfor %}

    {% for cache_key in cache_keys %}
      {% action "cache", "del", cache_key %}
    {% endfor %}
  {% endif %}
{% endif %}
Task code is written in Mechanic Liquid, an extension of open-source Liquid enhanced for automation. Learn more
Defaults
Maximum hourly orders
10
Only count orders matching this query
-status:cancelled
Restore inventory levels the next hour
true