R/sf_get_objects.R

sf_account <- function(con) {

  #Account
  objectName <- "Account"
  a <- rforcecom.getObjectDescription(con, objectName)
  fields <- as.character(a$name)
  account_raw <- rforcecom.retrieve(con, objectName, fields)

  #simplify
  account <- data.frame(lapply(account_raw, as.character), stringsAsFactors=FALSE) %>%
    mutate(created_date = as.character(CreatedDate) %>% parse_date_time("YmdHMS")) %>%
    mutate(last_modified_date = as.character(LastModifiedDate) %>% parse_date_time("YmdHMS")) %>%
    select(Id, Name, OwnerId, created_date, last_modified_date, AccountSource,
      Sales_Region_Name__c, Customer__c, Partner__c, Country__c )

  #return
  list(account = account, account_raw = account_raw)

}

sf_opportunity <- function(con){

  #Opportunities
  objectName <- "Opportunity"
  a <- rforcecom.getObjectDescription(con, objectName)
  fields <- as.character(a$name)
  opportunity_raw <- rforcecom.retrieve(con, objectName, fields)

  #simplify
  opportunity <- data.frame(lapply(opportunity_raw, as.character), stringsAsFactors=FALSE) %>%
    mutate(created_date = as.character(CreatedDate) %>% parse_date_time("YmdHMS"),
      last_modified_date = as.character(LastModifiedDate) %>% parse_date_time("YmdHMS"),
      close_date = as.character(CloseDate) %>% parse_date_time("Ymd")) %>%
    select(Id, AccountId, Name, StageName, Account_Manager__c, Amount, Type, IsClosed, IsWon, created_date, last_modified_date, close_date)


  #return
  list(opportunity = opportunity, opportunity_raw = opportunity_raw)


}
sf_opportunity_history <- function(con){

  objectName <- "OpportunityHistory"
  a <- rforcecom.getObjectDescription(session, objectName)
  fields <- as.character(a$name)
  opportunity_history_raw <- rforcecom.retrieve(session, objectName, fields)

  opportunity_history_long <- opportunity_history %>% gather(key ="change_attribute", value="value", c(-Id, -OpportunityId, -CreatedDate))

  opportunity_history_change <- opportunity_history_long %>% mutate(CreatedDate = as.character(CreatedDate) %>% parse_date_time("YmdHMS")) %>%
    group_by(OpportunityId, change_attribute) %>%
    mutate(old_value =dplyr::lag(value, order_by = CreatedDate)) %>%
    mutate(old_CreatedDate =dplyr::lag(CreatedDate, order_by = CreatedDate)) %>%
    rename(new_value = value) %>%
    rename(new_CreatedDate = CreatedDate) %>%
    mutate(value_duration = round(difftime(new_CreatedDate,old_CreatedDate, units = "days"), digits = 0)) %>%
    filter(new_value != old_value) %>%
    ungroup()

  #return
  list(opportunity_history_raw = opportunity_history_raw,
    opportunity_history_long = opportunity_history_long,
    opportunity_history_change = opportunity_history_change)


}
rgustavs/tidySalesforce documentation built on May 8, 2019, 6:55 p.m.