R/Classes/util.R

library(magrittr)
library(googlesheets)

#' Get data from google sheets
#' This function downloads a google sheet. Cannot be tested in travis CI as I wouldn't
#' be able to
#' @param x Sheet Name
#' @return data frame
#' @export
#' @examples
#' getGoogleSheetFromSheetName("Ravi Transactions")
#' getGoogleSheetFromSheetName("Soundari transactions")
getGoogleSheetFromSheetName <- function(sheetName) {

  pr <- paste("getGoogleSheetFromSheetName:",
        "working dir:",
        getwd())
  warning(pr)
  gs_auth(token = "Assets/secure/googlesheets_token.rds")
  gap_ss <- gs_title(sheetName)
  init <- gs_read(gap_ss)
  #cln <- clean(init)
  #validate(cln)
  init
}

#' Get data from google sheets using URL.
#' This is needed for test functions
#' be able to
#' @param x URL
#' @return data frame
#' @export
#' @examples
#' getGoogleSheetFromSheetName("Ravi Transactions")
#' getGoogleSheetFromSheetName("Soundari transactions")
getGoogleSheetFromUrl <- function(url) {

  gap_ss <- gs_url(url)
  init <- gs_read(gap_ss)
  #cln <- clean(init)
  #validate(cln)
  init
}

#' Removes '$' sign from the column
#' @param x List with $ values
#' @return List with numbers
#' @examples
#' clnDollar("$12.1")
clnDollar <- function(x) {

  #convert to ascii
  asc <- iconv( x,to = "ASCII//TRANSLIT")

  #remove ','
  noComma <- gsub("\\,","",asc)
  noDollar <- gsub("\\$","",noComma)

  as.numeric(noDollar)
}

#' Validate and Clean Transaction dataset
#' @param x dataset from getGoogleSheet
#' @return data frame
#' @export
#' @examples
#' init <- getGoogleSheet("Ravi Transactions")
#' checkSchema(init)
checkSchema <- function(ds,schema) {

  dsCols <- colnames(ds)

  #get the columns in schema, that is not available in dataset
  schemaMiss <- setdiff(schema,dsCols)

  #get the columns in dataset that is not in schema
  dataSetMiss <- setdiff(dsCols,schema)

  if( length(schemaMiss) > 0 || length(dataSetMiss) > 0)
    stop(paste("Dataset is not as per required Schema",
               "Required: ",
               paste(schemaMiss, collapse = ','),
               "Got: ",
               paste(dataSetMiss, collapse = ',')
    ))

}


#' Check Reconciled or not
#' @param list of Reconciled status 'yes' / 'no' / 'NA'
#' @return 'Yes' | 'No'
#' @export
#' @examples
#' checkReconciled(c("Yes","No",NA))
checkReconciled <- function(lsRecon) {

  #if there is atleast one NA, then No
  #if there is atleast one No, then No
  #if all yes, then Yes
  #else throw error

  isNa <- detect(lsRecon,function(x) is.na(x))
  isNo <- detect(lsRecon,function(x) x == 'No')
  allYes <- every(lsRecon, function(x) x == 'Yes')

  if(!is.null(isNa))
    'No'
  else if(!is.null(isNo))
    'No'
  else if (allYes[1])
    'Yes'
  else
    stop("Reconciled data can only contain 'Yes' / 'No' / NA")

}
ravi9884/PersonalFinance documentation built on May 4, 2019, 6:38 p.m.