Shopify Flow to Calculate Return Abusers

I am working on a Shopify Flow to check to see if a customer is abusing our generous return policy. What I am wanting to do is

  • Calculate the quantity of units the customer has returned over the last 100 orders.

  • Calculate how many units a customer has purchased over the last 100 orders.

Then I would do some math to determine what their return rate percentage is and add a tag to the customers account if needed.

The reason we need to calculate return percentage this way is because on average we have seen about a 20% faulty rate with some of the products, and we don’t hesitate to just refund the money and our customers are happy with that as it is not a norm in our industry. However we have noticed that some customers are returning closer to a 60%-70% rate so we want to be able to automate the identification of these customers.

I used the response here → Re: Return Abuser Flow Questions but I am not getting the desired results.

Here is a screenshot of the flow so far

The Log output step is not showing any counts, so I am assuming it is something in the Run Code that is not working as expected.

Get Order Data

And my is below
Inputs

query{
  getOrderData {
    returns {
      returnLineItems {
        quantity
      }
    }
  }
}

Outputs

"The output of Run Code"
type Output {
  "The total number of items returned by this buyer"
  totalReturnedItems: Int!
}

JS

export default function main(input) {
  // Make sure that the data you return matches the
  // shape & types defined in the output schema.

  let totalReturnedItems = 0;
  input.getOrderData.forEach((order) => {
    order.returns.forEach((returnItem) => {
      totalReturnedItems += returnItem.returnLineItems.quantity;
    });
  });
  return {
    totalReturnedItems,
  }
}

Does anyone have some guidance on what I am doing wrong or if there is a better way to address this?

It seems that you forgot to loop through all the elements in returnItem.returnLineItems. Try the following code:

export default function main(input) {
  // Make sure that the data you return matches the
  // shape & types defined in the output schema.

  let totalReturnedItems = 0;
  input.getOrderData.forEach((order) => {
    order.returns.forEach((returnItem) => {
      returnItem.returnLineItems.forEach((returnLineItem) => {
        totalReturnedItems += returnLineItem.quantity
      });
    });
  });
  
  return {
    totalReturnedItems,
  }
}

Hey Yuka,

Thanks for responding. I think my logic was wrong from the start, I assumed this would be the best way to capture the refund amount but instead we are going to focus on the dollar amount. Instead I am going to do a return of the SUM of the refund amounts of all partial and full refunds. Then take that number and calculate the percentage of refunds based off of a customers total gross sales.

I will say that your solution did help guide me towards my answer so I will mark it as the accepted solution.

Thanks!