-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.R
More file actions
295 lines (263 loc) · 11.5 KB
/
app.R
File metadata and controls
295 lines (263 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
#Fetch rainfall from MARS database
library(shiny)
library(shinythemes)
library(pwdgsi)
library(tidyverse)
library(pool)
library(shinyjs)
library(shinyWidgets)
library(lubridate)
options(stringsAsFactors=FALSE)
# Connect to DB
poolConn <- dbPool(
drv = RPostgres::Postgres(),
host = "PWDMARSDBS1",
port = 5434,
dbname = "mars_prod",
user= Sys.getenv("shiny_uid"),
password = Sys.getenv("shiny_pwd"),
timezone = NULL)
# Disconnect from DB when stopped
onStop(function(){
poolClose(poolConn)
})
# Refer dat is today minus 2 months
refer_date <- today() %m-% months(2)
# The last rain gage date
max_rainfall_date <- as.Date(odbc::dbGetQuery(poolConn, paste0("select max(dtime) from data.tbl_gage_rain where dtime > '", refer_date, "'")) %>% pull)
# The last baro date
max_baro_date <- as.Date(odbc::dbGetQuery(poolConn, paste0("SELECT max(dtime) FROM data.viw_barodata_neighbors where dtime > '", refer_date, "'")) %>% pull)
# The last date of baro or rain gage data
#### Why is this needed?
max_date = max(c(max_rainfall_date, max_baro_date))
# UI
ui <- fluidPage(theme = shinytheme("cerulean"),
titlePanel("MARS Fetch Rainfall & Baro Data"),
# Sidebar Panel
sidebarPanel(
selectizeInput("smp_id", "SMP ID",
# Intialize with zero choices
choices = NULL,
options = list(
placeholder = 'Select an Option',
# JS: Set initial value to ""
onInitialize = I('function() { this.setValue(""); }')
)),
# Assign numeric values to rainfall and baro data
selectInput("data_type", "Data Type", choices = c("", "Rainfall" = 1, "Baro" = 2), selected = NULL),
airDatepickerInput("daterange", "Date Range", range = TRUE),
#### What is this for?
verbatimTextOutput("res"),
conditionalPanel(condition = 'input.data_type == 2',
selectInput("interval", "Interval (min)", choices = c("", 5, 15), selected = NULL)
),
conditionalPanel(condition = 'input.data_type == 1',
actionButton("rainfall_data", "Get Rainfall Data"),
disabled(downloadButton("dl_rainfall", "Download Rainfall .csv"))
),
conditionalPanel(condition = 'input.data_type == 2',
actionButton("baro_data", "Get Baro Data"),
disabled(downloadButton("dl_baro_data", "Download Baro .csv"))
)
),
useShinyjs(),
# Main panel
mainPanel(
# Header to let user know that the data was retrieved/generated.
#### Header defaults to baro?
h4(textOutput("rainfall_title")),
h4(textOutput("baro_title"))
)
)
# Server
server <- function(input, output, session){
# Initialize reactiveValues()
rv <- reactiveValues()
# Update rainfall title based on requested/max dates
# If rain gage data hasn't been updated since refer_date, update header to reflect
if(is.na(max_rainfall_date)){
rain_error <- "The latest rainfall data is 2 months or older and must be updated."
rv$rainfall_header <- rain_error
output$rainfall_title <- renderText(rv$rainfall_header)
} else {
# based on current logs structure milestones greater than 5 mean that gage data has been retrieved properly and have moved on to radar
#### Why are we doing this from the logs? Why aren't we doing this from the actual data tables?
rainfall_log <- dbGetQuery(poolConn, "select max(date) from log.tbl_script_rainfall where milestone > 5") %>% pull
rv$rainfall_header <- paste0("Rainfall data was last updated on: ",
as.Date(rainfall_log),
". The latest value is from: ",
max_rainfall_date,
".")
}
# If rain gage data hasn't been updated since refer_date, update header to reflect
if(is.na(max_baro_date)){
baro_error <- "The latest barometric pressure data is 2 months or older and must be updated."
rv$baro_header <- baro_error
output$baro_title <- renderText(rv$baro_header)
} else {
baro_log <- dbGetQuery(poolConn, "select max(date) from log.tbl_script_baro where exit_code = 0") %>% pull
rv$baro_header <- paste0("Barometric data was last updated on: ",
as.Date(baro_log),
". The latest value is from: ",
max_baro_date,
".")
}
# Get list of all smp_ids
#### Why are we doing this?
smp_id <- dbGetQuery(poolConn, paste0("select distinct smp_id from admin.tbl_smp_loc")) %>%
dplyr::arrange(smp_id) %>%
dplyr::pull()
# Update input smp_ids with all distinct ones.
updateSelectizeInput(session, "smp_id", choices = smp_id, selected = character(0), server = TRUE)
# Set end date depending on rainfall or baro
rv$max_date <- reactive(
# Default to today
if(length(input$data_type) == 0) {
lubridate::today()
# If rainfall
} else if (input$data_type == 1) {
max_rainfall_date
# If baro
} else if(input$data_type == 2) {
max_baro_date
})
# Check for changes in daterange
observe(updateAirDateInput(session, "daterange", options = list(maxDate = rv$max_date())))
# Store dates in rv
rv$start_date <- reactive(lubridate::ymd(input$daterange[1], tz = "America/New_York"))
rv$end_date <- reactive(lubridate::ymd(input$daterange[2], tz = "America/New_York"))
# Update date ranges and header when switching data type
observeEvent(input$data_type, {
# If there is no data type and there is an end date
#### This block should be the else?
if(length(input$data_type) > 0 & length(input$daterange[2]) > 0) {
# If the end date is greater than max date, clear
if(input$daterange[2] > rv$max_date()) {
updateAirDateInput(session, "daterange", clear = TRUE)
}
}
# If rainfall data
if(input$data_type == 1) {
output$rainfall_title <- renderText(rv$rainfall_header)
output$baro_title <- renderText("")
}
# If baro data
if(input$data_type == 2){
output$baro_title <- renderText(rv$baro_header)
output$rainfall_title <- renderText("")
}
})
# Add "mins" to the interval
rv$interval <- reactive(paste(input$interval, "mins"))
# Toggle states based on inputs
# TRUE/FALSE if smp_id is a least a character and there is an start and end date.
#### Can we change name of this to be more reflective of what it's doing?
#### Do we need a duplicate one if they are the same statement?
rainfall_go <- reactive(nchar(input$smp_id) > 0 & length(input$daterange[1]) > 0 & length(input$daterange[2]) > 0)
# Observe status of rainfall_go
observe(toggleState(id = "rainfall_data", condition = rainfall_go()))
baro_go <- reactive(nchar(input$smp_id) > 0 & length(input$daterange[1]) > 0 &
length(input$daterange[2]) > 0 & nchar(input$interval) > 0)
observe(toggleState(id = "baro_data", condition = baro_go()))
# Get rainfall data
# Observe clicked rainfall_data button
observeEvent(input$rainfall_data, {
# Catch error from marsFetchRainfallData
tryCatch(rv$rainfall_data <- marsFetchRainfallData(con = poolConn,
target_id = input$smp_id,
source = "gage",
start_date = input$daterange[1],
end_date = input$daterange[2],
daylightsavings = FALSE),
error = function(e) {
rv$rainfall_data <- NULL
showModal(
modalDialog(
title = "No available data",
easy_close = TRUE,
"There is no data available for this date range"
)
)
})
# If rv$rainfall exists
if(!is.null(rv$rainfall_data)) {
# Moving America/New_York to EST to match baro CSV files for QAQC
rv$rainfall_data <- rv$rainfall_data |>
mutate(dtime = with_tz(dtime, tz = "EST")) |>
select(dtime, rainfall_in, gage_uid, gage_event_uid)
rv$rainfall_header <- paste("Rainfall data for", input$smp_id, "from",
input$daterange[1],"to", input$daterange[2],
"has been generated.")
# Enable download button
enable("dl_rainfall")
} else {
# Make sure download is disabled
disable("dl_rainfall")
rv$rainfall_header <- paste("No Rainfall data for", input$smp_id, "from",
input$daterange[1],"to", input$daterange[2],
"is available.")
# Render header
output$rainfall_title <- renderText(rv$rainfall_header)
}
})
# Download rainfall CSV file
#### The download file should be one function/chunks for both data types.
# Observe clicking download button
output$dl_rainfall <- downloadHandler(
filename = function(){
paste(input$smp_id, input$daterange[1], "to", input$daterange[2], "rainfall.csv", sep = "_")
},
content = function(file){
write.csv(rv$rainfall_data, file)
}
)
# Observe Get Baro data button
#### Should be just get data, which downloads the file or gives soft error
# Catch error from marsFetchBaroData
observeEvent(input$baro_data, {
tryCatch(rv$baro_data <- marsFetchBaroData(con = poolConn,
target_id = input$smp_id,
start_date = rv$start_date(),
end_date = rv$end_date(),
data_interval = rv$interval()),
error = function(e) {
rv$baro_data <- NULL
showModal(
modalDialog(
title = "No available data",
easy_close = TRUE,
"There is no avaiable data for this date range"
)
)
})
# If baro_data returns 1+ observations
if(!is.null(rv$baro_data)) {
rv$barodata <- rv$baro_data |>
# Change time zone to EST for QAQC
mutate(dtime = with_tz(dtime, tz = "EST"))
rv$baro_header <- paste("Barometric pressure data found for", input$smp_id, "from", input$daterange[1], "to", input$daterange[2], " has been generated.")
# render header
output$baro_title <- renderText(rv$baro_header)
# Enable download button
enable("dl_baro_data")
} else {
# Make sure download is disabled
disable("dl_baro_data")
rv$baro_header <- paste("No baro data for", input$smp_id, "from",
input$daterange[1],"to", input$daterange[2],
"is available.")
# Render header
output$baro_title <- renderText(rv$baro_header)
}
})
# Download baro data
output$dl_baro_data <- downloadHandler(
filename = function(){
paste(input$smp_id, input$daterange[1], "to", input$daterange[2], "baro.csv", sep = "_")
},
content = function(file){
write.csv(rv$barodata, file)
}
)
}
shinyApp(ui, server)