-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.r
2067 lines (1883 loc) · 80.9 KB
/
app.r
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
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
##################################### HEADER ################################
# SCRIPTNAME: app.R
# DESCRIPTION: Master file for BRC Water Quality Data Management Shiny App
# WRITTEN BY: Dan Crocker
# DATE OF LAST UPDATE: Spring 2019
# Credits: Code inspired by Dean Attali -
# https://deanattali.com/2015/06/14/mimicking-google-form-shiny/
##############################################################################.
### TO DO ####
# Login credentials?
### Add login page (password Input- login provides the following:
# FC- Name - Region - site and volunteer lists should get filtered automatically
# PC - gets access to all sites and volunteers, can see hidden modules and access to import button
# Should submitted records be in tidy format? or non-tidy - for archive -
# non-tidy format will preserve nulls, whereas tidy format will not
# In other data add a button for attach photo - similar to comment - Add photo name, parameter number, photo credit
# is selectize input where Field Monitor is default - but can type in other name.
# Photo is logged and a csvFile is generated
# Add save button to submitted data page (for edits)
# Add process and import UI to server (use WIT at template)
# Update select input after import on submitted data tab - so file selector updates
# Add comment modal button for submitted comments
# When datatable modules are empty- disable buttons or remove entirely and display a helpful message
print(paste0("BRCWQDM App lauched at ", Sys.time()))
# options(error= recover)
### Load Libraries ####
ipak <- function(pkg){
new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
if (length(new.pkg))
install.packages(new.pkg, dependencies = TRUE, repos="https://cloud.r-project.org", quiet = T, verbose = F)
sapply(pkg, require, character.only = TRUE)
}
packages <- c("shiny","shinyjs", "shinyFiles", "shinyTime", "shinyalert","shinydashboard", "shinycssloaders","rmarkdown", "knitr", "tidyselect", "lubridate",
"plotly", "leaflet", "RColorBrewer", "data.table", "DT", "scales", "stringr", "shinythemes", "ggthemes", "tidyr", "tibble",
"dplyr", "magrittr", "httr", "tibble", "bsplus", "readxl", "rdrop2", "RSQLite", "readr", "purrr", "htmlwidgets", "ggplot2",
"pool", "curl", "glue","googlesheets4", "fs", "rpivotTable", "xts", "htmltools", "dygraphs")
# install.packages("https://github.com/jeroen/curl/archive/master.tar.gz", repos = NULL)
# update.packages("curl", repos="http://cran.rstudio.com/", quiet = T, verbose = F)
# source('all_sessions.R', local = TRUE)
# "devtools"
# "miniUI"
# "rstudioapi"
# "rgdal"
### Set Directories ####
wdir <<- getwd()
### LOCAL PROJECT DIRECTORY ####
### Settings dependent on launch mode (docker or normal) ####
if(launch_mode == "docker") {
suppressPackageStartupMessages(
sapply(packages, require, character.only = TRUE)
)
LocalDir <<- "/usr/local/src/LocalProjectDir/"
} else { # app is not run in docker container
suppressPackageStartupMessages(
ipak(packages)
)
LocalDir <<- config[1]
}
dataDir <<- paste0(LocalDir,"Data/")
app_user <<- config[2]
user_zone <<- config[13]
### CSV Files ####
stagedDataCSV <<- paste0(dataDir,"StagedData/BRC_StagedData.csv")
stagedCommentsCSV <<- paste0(dataDir,"StagedData/BRC_StagedComments.csv")
submittedDataDir <<- paste0(dataDir,"SubmittedData")
### RDS FILES ####
rdsFiles <<- paste0(dataDir,"rdsFiles/")
stagedDataRDS <<- paste0(rdsFiles,"stagedData.rds")
stagedCommentsRDS <<- paste0(rdsFiles,"stagedComments.rds")
submittedDataRDS <<- paste0(rdsFiles,"submittedData.rds")
submittedCommentsRDS <<- paste0(rdsFiles,"submittedComments.rds")
### Database Data RDS - updated each time data is imported or using admin tools
data_n_RDS <<- paste0(rdsFiles,"data_num_db.rds")
data_t_RDS <<- paste0(rdsFiles,"data_text_db.rds")
data_c_RDS <<- paste0(rdsFiles,"data_comment_db.rds")
trans_log_RDS <<- paste0(rdsFiles,"trans_log_db.rds")
### RDS DATABASE FILES ####
### Periodic updates - supporting tables
sitesRDS <<- paste0(rdsFiles,"sites_db.rds")
peopleRDS <<- paste0(rdsFiles,"people_db.rds")
parametersRDS <<- paste0(rdsFiles,"parameters_db.rds")
assignmentsRDS <<- paste0(rdsFiles,"assignments_db.rds")
photosRDS <<- paste0(rdsFiles,"photos_db.rds")
### SOURCE EXTERNAL SCRIPTS ####
source(paste0(wdir, "/funs/csv2df.R"))
source(paste0(wdir, "/funs/editableDT_modFuns.R"))
source(paste0(wdir, "/mods/mod_editDT.R"))
source(paste0(wdir, "/funs/sendEmail.R"))
source(paste0(wdir, "/mods/mod_add_comment.R"))
source(paste0(wdir, "/mods/mod_add_photo.R"))
source(paste0(wdir, "/mods/mod_add_sampler.R"))
source(paste0(wdir, "/mods/mod_add_tlog.R"))
source(paste0(wdir, "/mods/mod_map.R"))
source(paste0(wdir, "/funs/data_update.R"))
source(paste0(wdir, "/mods/mod_photo_browser.R"))
source(paste0(wdir, "/mods/mod_event_viewer.R"))
source(paste0(wdir, "/funs/dropB.R"))
source(paste0(wdir, "/funs/gsheets.R"))
source(paste0(wdir, "/mods/mod_data_explorer.R"))
### Make reactive data list
rxdata <<- reactiveValues()
### Download database rds files from dropbox ####
# This checks for updated rds files for data and comments and updates local files if out of date
GET_DATABASE_DATA()
### Download rds files cached on dropbox to local data folder and load these and any staged RDS files
LOAD_DB_RDS()
people_db <- readRDS(peopleRDS)
# data_num_db <- readRDS(data_n_RDS)
# parameters_db <- readRDS(parametersRDS)
# sites_db <- readRDS(sitesRDS)
### Change to the last record date (rds file)
last_update <- data_num_db$DATE_TIME %>% max()
### AS IS fields require no manipulation and can go directly to outputs
### Date and Time and any other QC'd values need to come from reactive elements
remote_data_dir <- paste0(getwd(),"/data/")
table_fields <<- readr::read_csv(paste0(wdir,"/data/table_fields.csv"))
data_fields <<- table_fields[1:38,]
comment_fields <<- table_fields[39:43,]
### DATA FIELDS ####
fieldsASIS <<- data_fields$shiny_input[data_fields$as_is == "yes"]
### Data Column names csv ####
col_names <<- data_fields$shiny_input
### Comment Column Names csv ####
comm_col_naes <<- comment_fields$shiny_input
### Select Option Choices ####
### All selection dependent lists need to go in server
### These lists are static
sites_db <- sites_db %>%
arrange(WATERBODY_NAME)
sites <<- sites_db$BRC_CODE
names(sites) <- paste0(sites_db$WATERBODY_NAME, " - ", sites_db$SITE_NAME, " (", sites_db$BRC_CODE, ")")
sites <<- sites
### Sampler choices - From assignements in current year and year prior ####
samplers_db <<- assignments_db %>%
filter(ROLE == "Field", YEAR >= (year(Sys.Date()) - 2)) %>%
add_case(NAME = "BRC SamplerX") %>%
.$NAME %>%
unique() %>%
sort()
wea_choices <<- c("Storm (heavy rain)", "Rain (steady rain)",
"Showers (intermittent rain)", "Overcast","Clear/Sunny", "Other","Not Recorded")
wat_appear_choices <<- c("Clear", "Milky", "Foamy", "Oily Sheen",
"Dark Brown", "Greenish", "Orange", "Tea Color", "Other", "Not Recorded")
wat_trash_choices <<- c("None", "Light", "Medium", "Heavy", "Not Recorded")
wat_odor_choices <<-c("None", "Sewage", "Fishy", "Chlorine",
"Rotten Eggs", "Other", "Not Recorded")
wat_NAV_choices <<- c("None", "Light", "Medium", "Heavy", "Not Recorded")
wat_clarity_choices <<- c("Clear","Slight","Medium","Heavy", "Not Recorded")
wat_erosion_choices <<- c("Undercut bank", "Slumping", "Erosional gullies in bank",
"Bridge or building undermining", "No erosion", "Not Recorded")
depth_choices <<- c("Gage (Staff Plate-feet)", "Ruler (inches)", "Not Recorded", "Dry (No Flow)", "No Datum")
### See Ref article here: https://github.com/daattali/shiny-server/blob/master/mimic-google-form/app.R
### SAVE DATA TO CSV ####
saveData <<- function(data, csvFile) {
if(file.exists(csvFile)){
write.table(x = data, file = csvFile,
row.names = FALSE, quote = TRUE, na = "", append = TRUE,
col.names = FALSE, qmethod = "d")
} else {
write.table(x = data, file = csvFile,
row.names = FALSE, col.names = col_names, na = "", quote = TRUE,
qmethod = "d", append = FALSE)
}
return("Record added to staged data.")
}
### SAVE COMMENT TO CSV ####
saveComment <- function(data, csvFile) {
if(file.exists(csvFile)){
write.table(x = data, file = csvFile,
row.names = FALSE, quote = TRUE, append = TRUE,
col.names = FALSE, qmethod = "d")
} else {
write.table(x = data, file = csvFile,
row.names = FALSE, col.names = comm_col_names, quote = TRUE,
qmethod = "d", append = FALSE)
}
return("Comment added to staged comments")
}
refreshData <<- function() {
if(file.exists(stagedDataCSV) == TRUE){
data <- read.table(stagedDataCSV, stringsAsFactors = FALSE, header = T, sep = " " , na.strings = "NA")
df <- data_csv2df(data, data_fields, stagedDataCSV) ### saves RDS file as data.frame
saveRDS(df, stagedDataRDS)
rxdata$stagedData <<- df
msg <- "Loading staged data ..."
} else {
rxdata$stagedData <<- NULL
msg <- "There were no prior staged data to load ..."
}
return(msg)
}
refreshComments <<- function() {
if(file.exists(stagedCommentsCSV) == TRUE){
data <- read.table(stagedCommentsCSV, stringsAsFactors = FALSE, sep = " " , header = T)
df <- comm_csv2df(data, comment_fields) ### saves RDS file as data.frame
saveRDS(df, stagedCommentsRDS)
rxdata$stagedComments <<- df
msg <- "Loading staged comments ..."
} else {
rxdata$stagedComments <<- NULL
msg <- "There were no prior staged comments to load ..."
}
return(msg)
}
print(refreshData())
print(refreshComments())
### CSS ####
appCSS <- ".mandatory_star { color: red; }
#error { color: red; }"
fieldsMandatory <- c("site", "sampler" )
labelMandatory <- function(label) {
tagList(
label,
span("*", class = "mandatory_star")
)
}
SubmitActionCount <- reactiveVal(0)
ImportActionCount <- reactiveVal(0)
### End Global Scope ####
### NOTES FOR UI AND SERVER ####
# User enters records in form
# When record complete --> Save Record --> saves csv --> displays in DT (Add to new tab)
# When user saves new record - overwrite csv file in staging --> updates DT
# The save button is not active unless data is edited in DT
# When all records have been added user presses enter records
# The submit button executes a process function which does all calculations
# A preview table shows up in a new tab, which cannot be edited
# The final csv file is moved from staged to processed folder (can be edited and reprocessed if needed)
### UI ####
ui <- tagList(
### Creates padding at top for navBar space due to "fixed-top" position
tags$style(type='text/css',
'body {padding-top: 70px;}',
'h2 {
font-family: "Arial Black";
font-weight: 500;
line-height: 1.1;
color: #0C4B91;
}'
),
shinyjs::useShinyjs(),
useShinyalert(),
shinyjs::inlineCSS(appCSS),
### Create the Top Navigation Bar as well as define aesthetics
navbarPage("Blackstone River Coalition Water Quality Data Management", position = "fixed-top",
inverse = FALSE, collapsible = TRUE,
theme = shinytheme("flatly"), windowTitle = "BRCWQM",
footer = tagList(hr(),
column(4,strong(paste("Most recent date of data: ", last_update)),br()),
column(8,tags$div(tags$em("Created by Dan Crocker"), align = "right"), br())
),
### DATA ENTRY TAB ####
tabPanel("DATA ENTRY",
fluidRow(
column(2, imageOutput("brc_logo1", height = 80), align = "left"),
column(8, h2("Enter Monitoring Data and Lab Results Here", align = "center")),
column(2, imageOutput("zap_logo1", height = 80), align = "right")
),
h4("After each sampling event is added click the 'Enter Record' button. Any
records that have been entered will be staged and available in future sessions,
or they may be processed, reviewed, and submitted on the other tabs.
Data may be corrected in the 'Staged Data' tab or in the staged 'csv'file ", align = "center"),
# "Blackstone River Coalition Water Quality Management"),
# downloadButton("downloadBtn", "Save records"),
div(id = "form",
bs_accordion(id = "sample_inputs") %>%
bs_set_opts(panel_type = "primary", use_heading_link = TRUE) %>%
# * Sample Event Info ----
bs_append(title = "SAMPLE EVENT INFO", content =
wellPanel(fluidRow(
column(width = 12,
fluidRow(
column(width = 6,
selectInput("site", labelMandatory("Choose Sample Location:"), c("",sites), selected = "")
),
column(width = 4 ,
uiOutput("sampler_UI")
),
column(width = 2,
ADD_SAMPLER_UI("add_sampler")
)
),
fluidRow(
column(width = 4,
dateInput("date", labelMandatory("Sample Date:"))
),
column(width = 3,
timeInput("time", labelMandatory("Sample Starting Time (24-hr format):"), seconds = FALSE)
),
column(width = 2,
numericInput("lab_num", "Lab Record#:", value = NULL, min = 1, max =50, step = 1)
)
)
) #End col
)) # End Well Panel and FR
) %>%
# * Physical Parameters ----
bs_set_opts(panel_type = "primary", use_heading_link = TRUE) %>%
bs_append(title = "PHYSICAL PARAMETERS", content =
wellPanel(fluidRow(
column(width = 12,
fluidRow(
column(width = 3,
radioButtons("wea48", "Weather Last 48 Hours (P01):", choices = wea_choices, selected = "Not Recorded"),
textAreaInput("comm_P01", labelMandatory("Comments for Weather Last 48 Hours (P01):"), placeholder = "Describe 'other'"),
radioButtons("wea_now", "Weather at time of sample (P02):", choices = wea_choices, selected = "Not Recorded"),
textAreaInput("comm_P02", labelMandatory("Comments for Weather at time of Sample (P02):"), placeholder = "Describe 'other'"),
numericInput("temp_air","Ending Air Temperature (C) (P03):",
value = NULL, min = -20, max = 40, step = 0.5),
numericInput("temp_wat", "Ending Water Temperature (C) (P04):",
value = NULL, min = 0, max = 30, step = 0.5),
ADD_COMMENT_UI("add_comment_physical")
),
column(width = 3,
checkboxGroupInput("wat_appear", "Water Appearance (P05):", choices = wat_appear_choices, selected = "Not Recorded"),
textAreaInput("comm_P05", labelMandatory("Comments for Water Appearance (P05):"), placeholder = "Describe 'other'"),
radioButtons("wat_trash", "Presence of Trash (P06):", choices = wat_trash_choices, selected = "Not Recorded")
),
column(width = 3,
checkboxGroupInput("erosion", "Stream bank/infrastructure erosion (P07):", choices = wat_erosion_choices, selected = "Not Recorded"),
textAreaInput("comm_P07", labelMandatory("Comments for Erosion (P07):"), placeholder = "Describe 'other'"),
checkboxGroupInput("wat_odor", "Water Odor (P08):", choices = wat_odor_choices, selected = "Not Recorded"),
textAreaInput("comm_P08", labelMandatory("Comments for Water Odor (P08):"), placeholder = "Describe 'other'")
),
column(width = 3,
radioButtons("wat_nav", "Nuisance Aquatic Vegetation (NAV) (P09):", choices = wat_NAV_choices, selected = "Not Recorded"),
radioButtons("wat_clarity", "Water Clarity (Visual Turbidity) (P10)", choices = wat_clarity_choices, selected = "Not Recorded"),
numericInput("lab_turb","Lab Turbidity (NTU) (P11.A):", value = NULL, min = 0, max = 2500, step = 0.5),
numericInput("lab_turb_rep","Lab Turbidity Replicate (NTU) (P11.B):", value = NULL, min = 0, max = 2500, step = 0.5)
)
)
) #End col
)) # End Well Panel and FR
) %>%
# * Depth Parameters ----
bs_set_opts(panel_type = "primary", use_heading_link = TRUE) %>%
bs_append(title = "DEPTH PARAMETERS", content =
wellPanel(fluidRow(
column(width = 12,
fluidRow(
column(width = 4,
radioButtons("depth_type", "Type of depth measurement (D01):",
choiceNames = depth_choices, choiceValues = depth_choices, selected = "No Datum")
),
column(width = 4,
uiOutput("depth")
),
column(width = 4,
ADD_COMMENT_UI("add_comment_depth")
) # End Col
)
))#End FR
) # End Well Panel
) %>%
# * Chemical Parameters ----
bs_set_opts(panel_type = "primary", use_heading_link = TRUE) %>%
bs_append(title = "CHEMICAL PARAMETERS", content =
wellPanel(fluidRow(
column(width = 12,
fluidRow(
column(width = 3,
numericInput("do","Dissolved Oxygen (mg/L) (C01):", value = NULL, min = 0, max = 25),
numericInput("o2","Oxygen Saturation (%) (C02):", value = NULL, min = 0, max = 100, step = 1)
),
column(width = 3,
numericInput("no3","Nitrate (mg/L)(C03.A):", value = NULL, min = 0, max = 20),
numericInput("no3_rep","Nitrate Lab Replicate (mg/L)(C03.B):", value = NULL, min = 0, max = 20),
numericInput("no3_field_rep","Nitrate Field Replicate (mg/L)(C03.C):", value = NULL, min = 0, max = 20)
),
column(width = 3,
numericInput("po4","Orthophosphate (mg/L)(C04.A):", value = NULL, min = 0, max = 2),
numericInput("po4_rep","Orthophosphate Lab Replicate (mg/L)(C04.B):", value = NULL, min = 0, max = 2),
numericInput("po4_field_rep","Orthophosphate Field Replicate (mg/L)(C04.C):", value = NULL, min = 0, max = 2)
),
column(width = 3,
numericInput("conduct", "Specific Conductivity (uS/cm)(C05.A):", value = NULL, min = 0, max = 10000, step = 1),
numericInput("conduct_rep", "Specific Conductivity Lab Replicate (uS/cm)(C05.B):", value = NULL, min = 0, max = 10000, step = 1),
numericInput("conduct_field_rep", "Specific Conductivity Field Replicate (uS/cm)(C05.C):", value = NULL, min = 0, max = 10000, step = 1),
ADD_COMMENT_UI("add_comment_chemical")
))
)
)) # End Well Panel and FR
) %>%
# * Biological Parameters ----
bs_set_opts(panel_type = "primary", use_heading_link = TRUE) %>%
bs_append(title = "BIOLOGICAL PARAMETERS", content =
wellPanel(fluidRow(
column(width = 12,
em("Note - A value of 1 will automatically be flagged as below detection (<)"),
fluidRow(
column(width = 6,
numericInput("e_coli", "E. coli (MPN/100mL) (B01):", value = NULL, min = 0, max = 25000),
checkboxInput("aql_e_coli", label = "Check this box if the result above represents the upper quantification limit (>)", value = FALSE),
numericInput("e_coli_field_rep", "E. coli - Field Replicate (MPN/100mL) (B05):", value = NULL, min = 0, max = 25000),
checkboxInput("aql_e_coli_field_rep", label = "Check this box if the result above represents the upper quantification limit (>)", value = FALSE),
numericInput("e_coli_lab_rep", "E. coli - Lab Replicate (MPN/100mL) (B02):", value = NULL, min = 0, max = 25000),
checkboxInput("aql_e_coli_lab_rep", label = "Check this box if the result above represents the upper quantification limit (>)", value = FALSE)
),
column(width = 6,
numericInput("e_coli_field_blank", "E. coli - Field Blank (MPN/100mL) (B04):", value = NULL, min = 0, max = 25000),
numericInput("e_coli_lab_blank", "E. coli - Lab Blank (MPN/100mL) (B03):", value = NULL, min = 0, max = 25000),
ADD_COMMENT_UI("add_comment_biological")
))
)
)) # End Well Panel and FR
) %>%
# * Other Sample Information ----
bs_set_opts(panel_type = "primary", use_heading_link = TRUE) %>%
bs_append(title = "OTHER SAMPLE INFORMATION", content =
wellPanel(fluidRow(
column(width = 6,
ADD_COMMENT_UI("add_comment_other")
),
# column(width = 4,
# checkboxInput("photos","Photos associated with sampling event?")
# ),
column(width = 6,
ADD_PHOTO_UI("add_photo_data_entry"),
)
)
) # End Well Panel
),
# * Enter Record ----
tags$head(tags$script(src = "message-handler.js")),
actionButton("enter", "Enter Record", class = "btn-primary"),
shinyjs::hidden(
span(id = "enter_msg", "Adding record entry ..."),
div(id = "error",
div(br(), tags$b("Error: "), span(id = "error_msg"))
) # End div error
)
), # End div form
shinyjs::hidden(
div(id = "thankyou_msg",
h3("Thanks, your record was entered successfully!"),
actionLink("enter_another", "Enter another record")
)# End div thankyou_msg
)
), # End TabPanel
### STAGED DATA TAB ####
tabPanel("STAGED DATA",
fluidRow(
column(2, imageOutput("brc_logo2", height = 80), align = "left"),
column(8, h2("Data Ready to Process & Submit", align = "center")),
column(2, imageOutput("zap_logo2", height = 80), align = "right")
),
tabsetPanel(
# * Staged Data ----
tabPanel("STAGED DATA", type = "pills",
fluidRow(
column(12,
### This is to adjust the width of pop up "showmodal()" for DT modify table
tags$head(tags$style(HTML('
.modal-lg {
width: 1200px;
}
'))),
helpText("Note: Remember to save any edits/deletions!"),
# br(),
### tags$head() is to customize the download button
tags$head(tags$style(".butt{background-color:#222f5b;} .butt{color: #e6ebef;}")),
actionButton(inputId = "SaveStagedData",label = "Save", width = "245px", class="butt"),
editableDTUI("stagedDataDT")
),
column(6,
verbatimTextOutput("rec_comments")
)
)
), # END DATA tp
# * Staged Comments ----
tabPanel("STAGED COMMENTS", type = "pills",
fluidRow(
column(12,
### This is to adjust the width of pop up "showmodal()" for DT modify table
tags$head(tags$style(HTML('
.modal-lg {
width: 1200px;
}
'))),
helpText("Note: Remember to save any edits/deletions!"),
# br(),
### tags$head() is to customize the download button
tags$head(tags$style(".butt{background-color:#222f5b;} .butt{color: #e6ebef;}")),
actionButton(inputId = "SaveStagedComments",label = "Save", width = "245px", class="butt"),
# downloadButton("Trich_csv", "Download in CSV", class="butt"),
# Set up shinyalert
editableDTUI("stagedCommentsDT")
)
)
), # End tp
# * Process and Submit ----
tabPanel("PROCESS & SUBMIT", value = 'process_submit', type = "pills",
fluidRow(
column(12,
h4("Make sure all data has been entered and checked over for accuracy. Click the 'PROCESS' button \n
when you are ready to proceed. During processing the data will be checked for errors and anomalies.\n
If no problems are found then you may submit the data to the Program Manager for final QC and database import.")
# actionButton(inputId = "process",label = "PROCESS", width = "200px", class="butt"),
# actionButton(inputId = "submit",label = "SUBMIT", width = "200px", class="butt"),
)
),
fluidRow(
column(6,
wellPanel(
strong(h4("Process staged records:")),
br(),
uiOutput("process1.UI"),
br(),
h4(textOutput("text.process1.status"))
)
),
column(6,
wellPanel(
strong(h4("Submit processed staged records to the BRC Program Coordinator:")),
br(),
uiOutput("submit.UI"),
br(),
uiOutput("text.submit.status")
)
)
),
fluidRow(
column(12,
tabsetPanel(
tabPanel("Processed Data",
dataTableOutput("table.process1.data")
),
tabPanel("Processed Comments",
dataTableOutput("table.process1.comments")
) # End Tab Panel
) # End Tabset Panel
) # End Col
) # End Fluid row
) # End TabPanel
)
),# End Tab Panel
### SUBMITTED RECORDS TAB ####
tabPanel("SUBMITTED DATA",
fluidRow(
column(2, imageOutput("brc_logo3", height = 80), align = "left"),
column(8, h2("These Records Have Been Submitted", align = "center")),
column(2, imageOutput("zap_logo3", height = 80), align = "right")
),
fluidRow(
column(12,
tags$head(tags$style(HTML('
.modal-lg {
width: 1200px;
}
'))),
uiOutput("selectFile_ui"),
br(),
uiOutput("submitted_data.UI")
) #End Col
) # End FR
), # End Tab Panel
### MORE TAB ####
navbarMenu("More",
### DATABASE TAB ####
tabPanel("DATABASE",
fluidRow(
column(2, imageOutput("brc_logo4", height = 80), align = "left"),
column(8, h2("BRC Water Quality Database", align = "center")),
column(2, imageOutput("zap_logo4", height = 80), align = "right")
),
fluidRow(
column(12,
wellPanel(
strong(h4("BRCWQDM DATABASE TABLES")),
em("The data displayed here are not generated from a live database connection. These data are from cached RDS files."),
em("In order to use the filters for numeric columns (ID, SEID, RESULT, CENSOR_VAL), you must provide a range of numeric values with an ellipsis between each number."),
em("For example: 197...450. If you need to search for one number you can use the same number on both sides of the ellipsis, or you can enter the number in the search box above the right side of the table.")
),
tabsetPanel(
tabPanel("Numeric Data",
fluidRow(downloadButton("download_data_num", "Download table as csv"), align = "center"),
DTOutput("data_num_db")
),
tabPanel("Text Data",
fluidRow(downloadButton("download_data_text", "Download table as csv"), align = "center"),
DTOutput("data_text_db")
),
tabPanel("Comments",
fluidRow(downloadButton("download_data_comments", "Download table as csv"), align = "center"),
DTOutput("data_comment_db")
),
tabPanel("Photos",
column(12,
PHOTOS_UI("photo_browser")
)
),
tabPanel("Event Viewer",
column(12,
EVENTS_UI("event_viewer")
)
),
tabPanel("Data Explorer",
column(12,
EXPLORER_UI("data_explorer")
)
),
tabPanel("Transaction Log",
fluidRow(downloadButton("download_trans_log", "Download table as csv"), align = "center"),
DTOutput("data_trans_log_db")
) # End Tab Panel
) # End Tabset Panel
) # End Col
) # End Fluid row
), # End Tab Panel
### MAP TAB ####
tabPanel("MAP",
fluidRow(
column(2, imageOutput("brc_logo5", height = 80), align = "left"),
column(8, h2("BRC Water Quality Sampling Sites", align = "center")),
column(2, imageOutput("zap_logo5", height = 80), align = "right")
),
fluidRow(
column(12,
BRCMAP_UI("brc_map")
)
)
),
### REPORTS TAB ####
tabPanel("REPORTS",
fluidRow(
column(2, imageOutput("brc_logo6", height = 80), align = "left"),
column(8, h2("Reports", align = "center")),
column(2, imageOutput("zap_logo6", height = 80), align = "right")
),
fluidRow(
column(12,
h4("Click this button to test email functionality - check email and log file for result", align = "center"),
actionButton(inputId = "email_test",label = "Send a testing Email", width = "245px", class="butt")
)
)
),
### TRAINING LOG TAB ####
tabPanel("TRAINING LOG",
fluidRow(
column(2, imageOutput("brc_logo9", height = 80), align = "left"),
column(8, h2("BRC Volunteer Training Log", align = "center")),
column(2, imageOutput("zap_logo9", height = 80), align = "right")
),
fluidRow(column(12,
TLOG_UI("tlog")
)
)
),
### INSTRUCTIONS TAB ####
tabPanel("INSTRUCTIONS",
fluidRow(
column(2, imageOutput("brc_logo7", height = 80), align = "left"),
column(8, h2("BRC Water Quality Sampling Sites", align = "center")),
column(2, imageOutput("zap_logo7", height = 80), align = "right")
),
fluidRow(column(12,
h2("Instructions and Data Processing Workflow", align = "center"),
htmlOutput("instructions")
)
)
),
### ADMIN TOOLS ####
tabPanel("ADMIN TOOLS",
fluidRow(
column(2, imageOutput("brc_logo8", height = 80), align = "left"),
column(8, h2("Admin Tools", align = "center")),
column(2, imageOutput("zap_logo8", height = 80), align = "right")
),
uiOutput("admin_tools.UI")
)
) # End navbar Menu
) # End navbar page
) # End UI - taglist
####################################################.
### SERVER ####
####################################################.
server <- function(input, output, session) {
### Generate User list ####
user_list <<- assignments_db %>%
filter(YEAR == max(assignments_db$YEAR), ROLE %in% c("Field Coordinator","Program Coordinator", "App Developer")) %>%
.$NAME
### Verify User ####
# if(app_user %in% user_list){
# print(paste0("App user '", app_user, "' verified!"))
# } else {
# stop("App user '", app_user,"' cannot be verified - please contact the program coordinator and ensure your configuration file user name matches your role in the BRCWQDM database. ")
# }
### Set User Role ####
user_role <<- "Program Coordinator"
# user_role <<- filter(assignments_db, YEAR == max(assignments_db$YEAR),
# NAME == app_user,
# ROLE %in% c("App Developer", "Program Coordinator", "Field Coordinator")) %>% .$ROLE
# user_role <<- "Field Coordinator"
if(user_role %in% c("App Developer", "Program Coordinator")){
shinyjs::show("ADMIN TOOLS")
} else {
shinyjs::hide("ADMIN TOOLS")
}
### Download submitted data from dropbox ####
GET_SUBMITTED_DATA()
fileChoices <- function(){
# if(submittedFileNum > 0){
dataFiles <- list.files(submittedDataDir, pattern = "*Data*", full.names = TRUE)
names(dataFiles) <- list.files(submittedDataDir, pattern = "*Data*", full.names = FALSE) %>%
str_replace_all("_SubmittedData_"," ") %>% str_replace_all(".csv","")
dataFiles
# } else{
# NULL
# }
}
rxdata$fileChoices <- fileChoices()
### Get samplers from googledrive ####
if(exists("testing")) {
print("Testing mode is on ... no downloads from google sheets")
rxdata$samplers <<- samplers_db %>% sort()
} else {
try(GS_GET_SAMPLERS(sheet = config[15])) # Updates rxdata$samplers
}
# rxdata$samplers <<- try(GS_GET_SAMPLERS(sheet = config[15])) # Updates rxdata$samplers
photos_db <<- readRDS(photosRDS)
rxdata$photos <- photos_db
### Get photos from google sheets ####
if(!exists("testing")) {
try(GS_GET_PHOTOS(sheet = config[14], photos = photos_db)) # Updates rxdata$photos
}
### Get training log from google sheets ####
# * This creates rxdata$training_log for the first time ----
try(GS_GET_TRAINING_LOG(sheet = config[16]))
selected_site <- reactive({
input$site
})
selected_date <- reactive({
input$date
})
selected_sampler <- reactive({
input$sampler
})
if(user_role == "Program Coordinator"){
selectFile_lab <<- "Choose submitted data to process and import:"
} else {
selectFile_lab <<- "Choose previously submitted data to view:"
}
# SelectFile UI
output$selectFile_ui <- renderUI({
selectInput("selectFile", label = selectFile_lab,
choices = c("", rxdata$fileChoices), selected = "" , multiple = FALSE, width = "400px")
})
# Update Select Input when a file saved imported (actually when the import button is pressed (successful or not))
observeEvent(input$SaveSubmittedData, {
updateSelectInput(session = session,
inputId = "selectFile",
label = selectFile_lab,
choices = c("", rxdata$fileChoices),
selected = "")
})
# Update Select Input when a file is imported (actually when the import button is pressed (successful or not))
observeEvent(input$import,{
rxdata$fileChoices <- fileChoices()
})
observeEvent( input$submit,{
rxdata$fileChoices <- fileChoices()
})
observeEvent(input$import, {
updateSelectInput(session = session,
inputId = "selectFile",
label = selectFile_lab,
choices = c("", rxdata$fileChoices),
selected = "")
})
observeEvent(input$submit, {
updateSelectInput(session = session,
inputId = "selectFile",
label = selectFile_lab,
choices = c("",rxdata$fileChoices),
selected = "")
})
DataEditCols <- data_fields$dt_cols[data_fields$editable == "yes"]
CommentEditCols <- comment_fields$dt_cols[comment_fields$editable == "yes"]
staged_df <- callModule(editableDT, "stagedDataDT",
data = reactive(rxdata$stagedData),
data_name = "stagedData",
inputwidth = reactive(170),
edit_cols = DataEditCols)
staged_comments <- callModule(editableDT, "stagedCommentsDT",
data = reactive(rxdata$stagedComments),
data_name = "stagedComments",
inputwidth = reactive(170),
edit_cols = CommentEditCols)
submitted_df <- callModule(editableDT, "submittedDataDT",
data = reactive(rxdata$submittedData),
data_name = "submittedData",
inputwidth = reactive(170),
edit_cols = DataEditCols)
submitted_comments <- callModule(editableDT, "submittedCommentsDT",
data = reactive(rxdata$submittedComments),
data_name = "submittedComments",
inputwidth = reactive(170),
edit_cols = CommentEditCols)
observeEvent(input$selectFile, {
req(input$selectFile != "")
data_csv <<- input$selectFile
comment_csv <<- str_replace(data_csv,"Data_","Comments_")
data <- read.table(data_csv, stringsAsFactors = FALSE, header = T, sep = " " , na.strings = "NA")
df <- data_csv2df(data, data_fields, file = data_csv) ### saves RDS file as data.frame
saveRDS(df, submittedDataRDS)
rxdata$submittedData <- readRDS(submittedDataRDS)
if (file.exists(comment_csv)) {
data <- read.table(comment_csv, stringsAsFactors = FALSE, header = T, sep = " " , na.strings = "NA")
df <- comm_csv2df(data, comment_fields) ### saves RDS file as data.frame
saveRDS(df, submittedCommentsRDS)
rxdata$submittedComments <- readRDS(submittedCommentsRDS)
} else {
print("There were no submitted comments associated with the submitted data file")
}
})
### OTHER/NOT RECORDED ACTIONS ####
shinyjs::hide("comm_P01")
shinyjs::hide("comm_P02")
shinyjs::hide("comm_P05")
shinyjs::hide("comm_P07")
shinyjs::hide("comm_P08")
### SHOW HIDDEN COMMENTS ####
observeEvent(input$wea48, {
if("Other" %in% input$wea48){
shinyjs::show("comm_P01")
fieldsMandatory <- c(fieldsMandatory,"comm_P01")
} else {
shinyjs::hide("comm_P01")
fieldsMandatory <- fieldsMandatory[fieldsMandatory != "comm_P01"]
}
})
observeEvent(input$wea48, {
if("Not Recorded" %in% input$wea48){
updateCheckboxGroupInput(session, "wea48",
selected = "Not Recorded"
)
}
})
observeEvent(input$wea_now, {
if("Other" %in% input$wea_now){
shinyjs::show("comm_P02")
fieldsMandatory <- c(fieldsMandatory,"comm_P02")
} else {
shinyjs::hide("comm_P02")
fieldsMandatory <- fieldsMandatory[fieldsMandatory != "comm_P02"]
}
})
observeEvent(input$wea_now, {
if("Not Recorded" %in% input$wea_now){
updateCheckboxGroupInput(session, "wea_now",
selected = "Not Recorded"
)
}
})
observeEvent(input$wat_appear, {
if("Other" %in% input$wat_appear){
shinyjs::show("comm_P05")
fieldsMandatory <- c(fieldsMandatory,"comm_P05")
} else {
shinyjs::hide("comm_P05")
fieldsMandatory <- fieldsMandatory[fieldsMandatory != "comm_P05"]
}
})
observeEvent(input$wat_appear, {
if("Not Recorded" %in% input$wat_appear){
updateCheckboxGroupInput(session, "wat_appear",
selected = "Not Recorded"
)
}
})
observeEvent(input$erosion, {
if("Other" %in% input$erosion){
shinyjs::show("comm_P07")
fieldsMandatory <- c(fieldsMandatory,"comm_P07")
} else {
shinyjs::hide("comm_P07")
fieldsMandatory <- fieldsMandatory[fieldsMandatory != "comm_P07"]
}
})
observeEvent(input$erosion, {
if("Not Recorded" %in% input$erosion){
updateCheckboxGroupInput(session, "erosion",
selected = "Not Recorded"
)
}
})
observeEvent(input$wat_odor, {
if("Other" %in% input$wat_odor){
shinyjs::show("comm_P08")
fieldsMandatory <- c(fieldsMandatory,"comm_P08")
} else {
shinyjs::hide("comm_P08")
fieldsMandatory <- fieldsMandatory[fieldsMandatory != "comm_P08"]
}
})
observeEvent(input$wat_odor, {
if("Not Recorded" %in% input$wat_odor){
updateCheckboxGroupInput(session, "wat_odor",
selected = "Not Recorded"
)
}
})
observeEvent(input$wat_clarity, {
if("Not Recorded" %in% input$wat_clarity){
updateCheckboxGroupInput(session, "wat_clarity",
selected = "Not Recorded"
)
}
})
### CHECK MANDATORY FIELDS ####
observe({
mandatoryFilled <- vapply(fieldsMandatory,
function(x) {
!is.null(input[[x]]) && input[[x]] != ""
},
logical(1))
mandatoryFilled <- all(mandatoryFilled)
# enable/disable the enter button
shinyjs::toggleState(id = "enter", condition = mandatoryFilled)
})
### REACTIVE DATA ENTRY VALS ####