R/download_ndri_cut.R

Defines functions download_ndri_cut

Documented in download_ndri_cut

#' Download NDRI data from ProcXed
#'
#' Downloads the most recent cut for the selected return
#' from s0260a\\dbxed.
#'
#' @param ndri_return \code{pca}, \code{mye}, or \code{notified}
#' @param fin_year Financial year, as YYYY-YY or YYYYYY
#' @param uid User ID passed to \code{\link{connect_to_procxed}}
#'
#' @return A tibble.
#' @export
#'
#' @examples \dontrun{
#' ndri_return(ndri_return = "pca", year = "2021-22", uid = "U123456")
#' }
download_ndri_cut <- function(ndri_return, fin_year, uid) {

  # Sort out inputs -----------------------------------------------------------
  ndri_return <- stringr::str_to_lower(ndri_return)

  fin_year <- fin_year %>%
    as.character() %>%
    stringr::str_replace_all("[/-]", "")

  uid <- uid %>%
    as.character() %>%
    stringr::str_to_lower()

  # Check inputs are as expected ----------------------------------------------

  ## ndri_return is one of the three types
  if (ndri_return %!in% c("pca", "mye", "notified")) {
    stop("NDRI return should be 'pca', 'mye', or 'notified'.")
  }

  ## uid has the form u999999
  if (!grepl("u[0-9]{6}", uid)) {
    stop("Please enter your user ID in the format 'u999999'.")
  }

  # Create variables needed for download --------------------------------------

  ndri_table <- dplyr::case_when(ndri_return == "pca" ~ "ndripca",
                                 ndri_return == "mye" ~ "ndrimidyear",
                                 ndri_return == "notified" ~ "ndrinotified")

  ndri_schema <- stringr::str_sub(table, 1, 4)

  # Download data from ProcXed ------------------------------------------------

  ## Open connection to server
  procxed_con <- ndr::connect_to_procxed(uid, .in_func = TRUE)

  ## Download data
  data <- dplyr::tbl(procxed_con,
                     dbplyr::in_schema(ndri_schema, ndri_table)) %>%
    tibble::as_tibble()

  ## Close connection to ProcXed server
  DBI::dbDisconnect(procxed_con)

  # Return the downloaded data ------------------------------------------------
  return(data)

}
n-fanton/ndr documentation built on Dec. 21, 2021, 11:07 p.m.