Apple Tracker with Google Scripts

The new Apple Tracker tool helps you find Apple Stores near your zip code that are more likely to have stock of the new iPhone and iPad units. The tools is written in Google Apps Script and internally fetches the data from Apple’s website and parses the JSON response to check the stock in various Apple Stores.

http://store.apple.com/us/retail/availabilitySearch?parts.0=<PART#>&zip=<ZIP>

All Apple products have a unique Part # – like ME313LL/A for iPhone 5S 64 GB Gold AT&T or MF118LL/A for iPad Mini Retina 128 GB Gray Sprint Wifi + Cellular – and the Apple tracker sends an HTTP request to the store.apple.com URL to check availability of that product in Apple Stores near a specific zip code.

Here’s the Google Script that check the iPhone and iPad stock at various Apple Stores automatically.


function trackInventory() {
  
  var report = ""; // Email Report

  // Find Apple Product that are to be tracked
  var items = SpreadsheetApp.getActiveSheet().getRange("B6:D121").getValues();
  
  // Check inventory of Apple Stores near this zip code
  var zip = UserProperties.getProperty("zip");
  
  for (var i=0; i<items.length; i++) {
    
    if (items[i][2] === "Y") {
      
      // Check product availability at the given zip code
      var url = "http://store.apple.com/us/retail/availabilitySearch?parts.0="
                              + encodeURIComponent(items[i][1]) + "&zip=" + zip;
      
      var locations = "";
      
      try {
        
        var response = UrlFetchApp.fetch(url);        
        var json = Utilities.jsonParse(response.getContentText());
        
        for (var j=0; j<json.body.stores.length; j++) {
          // Is the product (Apple Part) listed as "available" in that Apple Store
          var store = json.body.stores[j];
          if (store["partsAvailability"][items[i][1]]["pickupSearchQuote"] != "Unavailable for Pickup") {            
            locations += "<li><small><a href='" + store["directionsUrl"] + "'>" + store["storeDisplayName"] + "</a> "
            + store["address"]["address2"] + ", " + store["city"] + " " + store["address"]["postalCode"] 
            + " " + store["state"] + " (" + store["phoneNumber"] + ")</small></li>";
          }          
        }
        
        if (locations.length) {
          report += "<p><strong><a href='" + storeURL(items[i][0]) 
                 + "'>" + items[i][0] + "</a></strong> is currently available at: </p><ul>";
          report += locations + "</ul>";
        }
        
      } catch (e) {
        Logger.log(e.toString());
      }
    }
    
  }
  
  // Send HTML Mail with the product availability details
  if (report.length) {
      MailApp.sendEmail(UserProperties.getProperty("email"), "Apple Tracker", report, {htmlBody: report});
  }
}

function onOpen() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var menu = [ 
    {name: "Step 1: Initialize", functionName: "OpenWizard"},
    {name: "Step 2: Start Tracking", functionName: "OpenWizard"}
  ];  
  
  ss.addMenu("Apple Store Tracker", menu);
  ss.toast("Please click the Apple Tracker menu above to continue..", "", 5);
}

// Create UI to get email address and zip code from the user
function OpenWizard() {
  
  var app = UiApp.createApplication().setTitle('Apple Inventory Tracker').setHeight(160).setWidth(300);
  var top_panel = app.createFlowPanel();   
  top_panel.add(app.createLabel("").setHeight(10));
  
  top_panel.add(app.createLabel("Please enter your ZIP code"));
  var zip = app.createTextBox().setName("zip").setWidth(250).setValue(UserProperties.getProperty("zip"));
  top_panel.add(zip);
  
  top_panel.add(app.createLabel("").setHeight(10));
  top_panel.add(app.createLabel("Please enter your Email Address"));
  var email = app.createTextBox().setName("email").setWidth(250).setValue(UserProperties.getProperty("email"));
  top_panel.add(email);
  
  top_panel.add(app.createLabel("").setHeight(5));
  var btn = app.createButton("Start Tracking");
  top_panel.add(btn);
  
  var handler = app.createServerHandler('storeDB').addCallbackElement(zip).addCallbackElement(email);
  btn.addClickHandler(handler);
  
  app.add(top_panel);
  SpreadsheetApp.getActiveSpreadsheet().show(app);
}


// Get the Apple Store URL based on the Part Name
function storeURL(partName) {
  
  var storeURL;
  
  if (partName.search("iPad Air") != -1)
    storeURL = "http://store.apple.com/us/buy-ipad/ipad-air";
  else if (partName.search("iPad Mini Retina") != -1)
    storeURL = "http://store.apple.com/us/buy-ipad/ipad-mini-retina";
  else
    storeURL = "http://store.apple.com/us/buy-iphone/iphone5s";
  
  return storeURL;
}

// Store the Zip and Email address in User Properties
function storeDB(e) {
  
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  
  UserProperties.setProperty("email", e.parameter.email);
  UserProperties.setProperty("zip", e.parameter.zip);
  
  var app = UiApp.getActiveApplication();
  app.close();
  return app;
  
}