Skip to content

Instantly share code, notes, and snippets.

@bdunagan
Created January 29, 2017 10:44
Show Gist options
  • Save bdunagan/6fb27f97b4cf40abcbb5fe973a08c081 to your computer and use it in GitHub Desktop.
Save bdunagan/6fb27f97b4cf40abcbb5fe973a08c081 to your computer and use it in GitHub Desktop.
Salesforce: Create a Report object using Analytics API
# Instantiate Salesforce Report using Restforce.
# Requires Salesforce Analytics API with v29.
# Usage
# report = Restforce::Report.find("1234567890")
# puts report.name
# puts report.filters
# puts report.rows
module Restforce
class Report < Object
attr_accessor :name
attr_accessor :rows
attr_accessor :filters
def initialize(name, filters, rows)
self.name = name
self.filters = filters
self.rows = rows
end
def self.find(report_id)
return nil if report_id.blank?
sfdc_client = Restforce.new(
:username => RESTFORCE_CREDENTIALS["username"],
:password => RESTFORCE_CREDENTIALS["password"],
:client_id => RESTFORCE_CREDENTIALS["client_id"],
:client_secret => RESTFORCE_CREDENTIALS["client_secret"])
return nil if sfdc_client.nil?
# Request report from SFDC. Note that the API is limitd to 2k rows in response and there is no workaround.
# https://developer.salesforce.com/releases/release/related/AnalyticsAPI
sfdc_response = sfdc_client.get "/services/data/v29.0/analytics/reports/#{report_id}?includeDetails=true"
name = sfdc_response.body.reportMetadata["name"]
# Collect headers.
headers = []
sfdc_headers = sfdc_response.body.reportExtendedMetadata.to_hash["detailColumnInfo"]
sfdc_headers.each do |key, value|
headers << value["label"]
end
# Collect rows.
rows = []
sfdc_rows = sfdc_response.body.factMap.to_hash["T!T"]["rows"]
sfdc_rows.each do |row|
row = row["dataCells"]
index = 0
hash = {}
row.each do |values|
hash[headers[index]] = values["label"]
index += 1
end
rows << hash
end
# Collect filters.
filters = []
sfdc_filters = sfdc_response.body.reportMetadata["reportFilters"]
sfdc_filters.each do |row|
filters << row.to_hash
end
return Report.new(name, filters, rows)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment