R/tw_download.R

Defines functions tw_download_server tw_download_ui

Documented in tw_download_server tw_download_ui

#' Trailers Widget Download Button UI
#'
#'
#' The download button enables a disabled functionality at
#' start up to avoid missing conditions of campaign
#'
#' @param id The id of the download button UI
#'
#' @return html code for the UI of the shiny app
#'
#' @importFrom shinyjs disabled
#'
#' @export


tw_download_ui <- function(id) {
  ns <- NS(id)
  disabled(downloadButton(ns("download")))
}


#' Trailers Widget Download Button Server
#'
#'
#' @description The download button enables a disabled functionality at
#' start up to avoid missing conditions of campaign
#'
#'
#' @param input list of inputs used in the shiny application session
#' @param output list of outputs used the shiny application session
#' @param session The shiny app session object
#' @param file_name The core name of the file to download
#' @param base_data The list-wise data frame reactive function from the trailers app
#' @param condition The condition to enable the download button
#'
#' @return html code for the UI of the shiny app
#'
#' @importFrom shinyjs enable
#' @importFrom utils zip
#' @importFrom utils write.csv
#'
#' @export


tw_download_server <-
  function(input,
           output,
           session,
           file_name,
           base_data,
           condition) {

    output$download <- downloadHandler(
      filename = function() {
        #Naming of the file export
        # paste0('offers_trailers_clients_', format(Sys.Date(), '%Y%m%d'), '.zip')
        paste0(file_name, format(Sys.Date(), '%Y%m%d'), '.zip')
      },

      content = function(filename) {
        #Naming the different csv tables for zipping
        tr_loc <-
          paste0("trailers_", format(Sys.Date(), '%Y%m%d'), "_out.csv")
        cl_loc <-
          paste0("clients_", format(Sys.Date(), '%Y%m%d'), "_out.csv")

        #Gathering the data and separating it into local variables
        seg_data <- base_data()
        trailers <- seg_data[[1]]
        clients <- seg_data[[2]]
        #go to a temp dir to avoid permission issues
        owd <- setwd(tempdir())
        on.exit(setwd(owd))
        files <- NULL

        #Writing the CSV files
        write.csv(trailers, tr_loc , row.names = FALSE)
        write.csv(clients, cl_loc, row.names = FALSE)
        #include the file locations from the temporary directory
        files <- c(tr_loc, cl_loc, files)
        #zip files in the temporary directory
        zip(filename, files)
      }
    )

    observeEvent(condition(), {
      if (nchar(condition()) > 3) {
        shinyjs::enable('download')
      }
    },label = 'Observe the 3 Character Minimum')

  }
HarryRosen/hrimodules documentation built on Jan. 11, 2022, 12:36 a.m.