Auto Vendor Credits

Auto Vendor Credits

For anyone familiar with JavaScript, you may find this handy if you get settlement discounts from your suppliers.
You have to :
set up items with the discount amount,
get the id of this item,
set up a a contact custom field called "Settlements",
Enter this id into the contact that offers discount custom settlement field
 run getPayables....

function getPayables(){
  var discounts = "";
  var response = UrlFetchApp.fetch(url);
  var success = response.getResponseCode();
  var data = JSON.parse(response.getContentText());
  var vendors = data.contacts;
  for (var i = 0; i <= vendors.length-1; i++)
    if (vendors[i].outstanding_payable_amount > 0) 
    {
      discounts = "";
      for (var j = 0; j <= vendors[i].custom_fields.length-1; j++)
        if (vendors[i].custom_fields[j].label == "Settlements") discounts = vendors[i].custom_fields[j].value;
      if (discounts > "")
      { 
        var CN = {
          "id" : vendors[i].contact_id,
          "vendor" : vendors[i].vendor_name,
          "due" : vendors[i].outstanding_payable_amount,
          "item" : discounts,
          "cnId" : "",
          "cnAmount" : "",
          "billId" : ""}
        createCredits(CN);
        //getOpenBills(CN); // haven't bothered applying them, left them open !
        //applyToBills(CN)
      }
    }
  return;
}

function createCredits(CN){
  var MyString=
      {
        "vendor_id": CN.id,
        "reference_number" : 'Settlement discounts',
        "line_items":
        [{
          "item_id": CN.item,
          "quantity": CN.due,
          "tax_id": "408271000000057076",
        }
        ]}
  var options = {
    'method' : 'post',
    'contentType' : 'application/json',
    'muteHttpExceptions' : true
  }; 
  var myStuff = encodeURIComponent(JSON.stringify(MyString));
  try{
    var response = UrlFetchApp.fetch(url,options);
    var success = response.getResponseCode();
    var data = JSON.parse(response.getContentText());
    var cNote = data.vendor_credit;
    CN.cnId = cNote.cnId;
    CN.vendor = cNote.vendor_name;
    CN.cnAmount = cNote.total;
  } catch(f) {log_('Credit creation response = ' + f)};
  return CN;
}

And it would be great if Zoho could produce a custom button to do this for us ;-)