How it works

Follow these 6 simple steps to start receiving automatic alerts when coupon code abuse is detected

database icon

Record Created

App connector: Data • Time to complete: 0 minutes (Auto-configured)
Why this matters: This trigger regularly monitors your order database to detect new records, providing the foundation for hourly discount analysis without requiring constant manual data checks.

This trigger checks your "Shopify Orders" MESA Data table every hour for new records using the schedule. When new order data is detected, the workflow activates and begins the discount analysis process.

Critical requirement: You must have a MESA Data table named "Shopify Orders" that contains order information including "Created At", "Total Price", and "Total Discount" columns. This table is typically populated by another workflow that syncs Shopify orders to MESA Data storage.

Custom SQL Query

App connector: Data • Time to complete: 1 minute
Why this matters: Aggregates your order and discount data by day to calculate discount percentages, transforming raw order records into actionable metrics that reveal usage patterns and potential abuse.

This step runs a custom SQL query against the "Shopify Orders" MESA Data table to aggregate order data by day. The query calculates:

  1. Date: Orders grouped by date (formatted as yyyy-mm-dd)
  2. total: Sum of Total Price for all orders that day
  3. total_discounts: Sum of Total Discount for all orders that day
  4. percentage: Discount rate calculated as total_discounts divided by total (rounded to 2 decimal places)

SQL query breakdown:

SELECT
  TO_CHAR("Created At", 'yyyy-mm-dd'),  -- Group by date
  SUM("Total Price") AS total,           -- Daily revenue
  SUM("Total Discount") AS total_discounts,  -- Daily discounts
  ROUND(SUM("Total Discount") / SUM("Total Price"), 2) AS percentage  -- Discount rate
FROM "Shopify Orders"
GROUP BY TO_CHAR("Created At", 'yyyy-mm-dd')
ORDER BY TO_CHAR("Created At", 'yyyy-mm-dd');

The results return rows showing each day's totals and discount percentage, enabling trend analysis to identify spikes in discount usage.

Format order total by day including discounts

App connector: Code • Time to complete: 1 minute
Why this matters: Transforms the SQL query results into a clean JSON format that AI can easily analyze, ensuring accurate interpretation of discount patterns without data formatting errors.

This custom JavaScript step formats the SQL results into a JSON string. The code takes the array of daily discount data from the previous step and converts it to a JSON string format that's optimal for AI analysis. The formatted data is returned as json_results containing the structured discount information.

// Creates new payload object
let newPayload = {};
// Converts SQL results to JSON string
newPayload.json_results = JSON.stringify(prevResponse);
// Passes formatted data to next step
Mesa.output.next(newPayload);

This formatting step ensures AI receives data in a consistent, parseable format regardless of variations in SQL output.

Compare discount rates to identify coupon abuse

App connector: AI • Time to complete: 3 minutes
Why this matters: Uses AI to intelligently detect abnormal discount patterns by comparing current rates against your baseline average, providing smart analysis that adapts to your specific business patterns rather than rigid thresholds.

This AI step analyzes the formatted discount data to detect abuse patterns. The AI receives the JSON results containing daily discount rates and compares them against a baseline assumption of 10% typical discount rate.

AI instructions:

  1. Compare each day's discount rate against the 10% baseline
  2. Determine if any recent discount rates are significantly higher than typical
  3. Respond with only "Yes" (abuse detected) or "No" (normal patterns)

The temperature setting of "1" balances between consistent analysis and nuanced pattern recognition. The AI considers context like whether high discount days are isolated incidents or sustained patterns, and whether the increase is dramatic enough to indicate abuse versus normal promotional variation.

Baseline customization: The default assumes 10% average discount rate. You can modify the prompt to specify your actual typical discount rate for more accurate detection.

Filter: Was coupon abuse detected?

App connector: Filter • Time to complete: 1 minute
Why this matters: Acts as a gatekeeper that only allows the workflow to continue and send alerts when AI has confirmed suspicious activity, preventing alert fatigue from false positives or normal discount activity.

This filter checks if the AI response equals "Yes". If true (abuse detected), the workflow proceeds to send a Slack alert. If false (AI responded "No"), the workflow stops here without sending a notification. This filtering ensures your team only receives alerts for genuine concerns, not routine discount activity.

Alert precision: The AI's analysis combined with this filter prevents notification fatigue by distinguishing between normal promotional activity (like legitimate sales events) and suspicious discount abuse patterns.

slack logo icon

Send Slack Message

App connector: Slack • Time to complete: 1 minute
Why this matters: Delivers immediate notification to your team when coupon abuse is detected, enabling quick investigation and response to protect revenue before the situation escalates.

This step sends a Slack message to your configured channel. Configuration: You must set two values during setup:

  1. Slack channel: Select the channel where alerts should post (like #fraud-alerts, #finance, or #operations). First invite the MESA Slack app to the channel by typing @MESA and clicking Invite.
  2. Alert message: Customize the notification text. Default is "Coupon code abuse detected" but you can enhance with additional context, instructions for investigation, or formatting for visibility.

Message customization examples:

  1. "🚨 Coupon abuse detected! Discount rate is significantly higher than normal baseline. Check recent orders for suspicious patterns."
  2. "⚠️ Unusual discount activity detected. Review dashboard for details."
  3. Include links to your order dashboard or analytics tools

The message posts immediately when abuse is detected, ensuring your team can investigate while patterns are recent.

*Required: These following must be installed before using this workflow.

Make it your own

Customize this workflow even further:

Include detailed discount data in the alert
Modify the Slack message to include specific numbers from {{custom.json_results}}, showing which days had high discount rates and the exact percentages to provide immediate context for investigation.
Adjust the baseline discount threshold
Change the 10% baseline in the AI prompt to match your actual average discount rate, or create different thresholds for different time periods (like higher baselines during known sale events).
Add email alerts for critical spikes
Connect an email step alongside or after the Slack message to notify leadership or finance teams when discount rates exceed severely abnormal levels, ensuring critical issues reach the right people.
Store abuse incidents in Google Sheets
Add a Google Sheets step after the filter to log every detected abuse instance with timestamp, discount percentage, and AI analysis, creating a historical record for pattern analysis and reporting.

Frequently asked questions

How do I set up the "Shopify Orders" data table that this workflow requires?
The easiest way is to add the template "Store Shopify Orders in a Database". This will setup the table exactly as needed. If you want to build it from scratch, you'll need to create a separate workflow that syncs Shopify orders to a MESA Data table. Use a "Shopify Order Created" or "Order Updated" trigger and a "Data Record Create or Update" action to populate the table with fields for Created At, Total Price, and Total Discount. This provides the foundation data that the abuse detection workflow analyzes.
Can I change the 10% baseline discount rate to match my business?
Yes, edit the AI prompt in the "Compare discount rates to identify coupon abuse" step and replace "assume 10% if unspecified" with your actual typical discount rate. For example, if your average is 15%, change it to "assume 15% if unspecified" to reduce false positives.
What if I want to check more or less frequently than every hour?
Edit the trigger's poll schedule field. Adjust based on your order volume and how quickly you need to detect abuse. You may need to upgrade in order see faster frequency options.
What is a template?
Templates are pre-made workflows by our team of experts. Instead of building a workflow from scratch, these have all the steps needed to complete the task.
Can I personalize a template?
Yes! Every step can be customized to meet your exact requirements. Additionally, you can even add more steps and make it more sophisticated.
Are templates free?
Yes! Our entire library containing hundreds of templates are free to use and customize to your exact needs.

Ready to start receiving automatic alerts when coupon code abuse is detected?

Join thousands who've automated their work and saved an average of 3.5 hours every week.

Start with this template — It's free
7-day free trial • 8 min setup • Cancel anytime