I am trying to setup a simple google apps script to send emails when inventory on various components hits the defined threshold. After reading and searching I put together a script that appears to work but starts to send erroneous emails when I increase the range being pulled from my spreadsheet.
Here's my code and further details are below.
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName("Inventory Report");
var howFar = 5 //sheet.getMaxRows(); // how many rows of data
var onHand = sheet.getRange(2,14,howFar,1).getValues();
var minimum = sheet.getRange(2,16,howFar,1).getValues();
var itemNum = sheet.getRange(2,1,howFar,1).getValues();
var itemName = sheet.getRange(2,2,howFar,1).getValues();
var sendTo = "[email protected]";
var overStock = 1.5; // warning factor over minimum
function stockAlert() {
for (var i = 0; i < onHand.length; i++) {
if (onHand[i] < minimum[i] * overStock && onHand[i] > minimum[i]) {
MailApp.sendEmail( sendTo , "Testing Stock Reorder Notifications", itemNum[i] + " " + itemName[i] +" - Stock is low! Current stock is " + onHand[i] + ". Minimum is " + minimum[i] + ".");
}
else if (minimum[i] > 0 && onHand[i] < minimum[i]) {
MailApp.sendEmail( sendTo , "Testing Stock Cirtical Notifications", itemNum[i] + " " + itemName[i] +" - Stock is Critical and will be depleted! Current stock is " + onHand[i] + ". Minimum is " + minimum[i] + ".");
}
}
}
In my sheet the values for minimum are 200, 400, 200, 300, 600
In my sheet the values for onHand are 270, 270, 920, 920, 1830
This means I should see one low stock email for the first set of values, one critical stock email for the second set of values and no emails for the last 3 sets of values.
If var howfar = 3, the script sends the two appropriate emails.
If var howfar = 5, I get a third critical stock email for the fifth set of values that should not be sent. Interestingly the email body shows that it's referencing the correct set of values but else if should be false.
The body of the incorrect email reads:
itemNumitemName- Stock is Critical and will be depleted! Current stock is 1830. Minimum is 600.
Given my extensive background in not coding, I hope and assume this will be a simple fix, but any all help is greatly appreciated!