-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathapp.R
1675 lines (1485 loc) · 71.5 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
# app.R
#
# The goals of this Shiny App are as follows:
# 1. Read in files (zip, csv, SAS, SPSS, RDS, or Stata) containing tables adhering to the common data model
# 2. Check for presence of required variables and tables
# 3. Conduct data quality checks
# 4. Provide feedback on possible data quality errors, interactively and in downloadable form
# 5. Create reports summarizing dataset characteristics and data quality errors
# 6. Allow interactive visualization of dataset
# 7. Submit checked files to secure file storage (authenticated users)
#
# Judy Lewis, PhD, Vanderbilt Institute for Clinical and Translational Research
# Jeremy Stephens, Vanderbilt University Department of Biostatistics
# Version 1: August 10, 2017
# Version 2 (including integration with Hub): March 2019
# Version 3: Generalized to other data models: May 2021
# Version 3.1: Added data quality checks for IeDEA Sentinel Research Network
# Version 3.2: Added logic to automatically retrieve latest version of JSON for data model, code list, and project info
#
# HEPSANET customized version: 2024-07-30
# For this version, sourcing AWS key is commented out, along with library (aws.s3),
# since no dataset transfer is part of the application currently
# check folder permissions for project files
# NOTE: file.access is a pretty weird function and returns 0 for success
if (any(file.access(c('projectFiles', file.path('www', 'projectFiles')), 2) != 0)) {
stop("can't write to projectFiles folders, please change permissions")
}
library(shiny)
library(shinydashboard)
library(rjson)
library(tools)
library(lubridate)
library(shinyjs)
library(kableExtra)
library(rmarkdown)
library(knitr)
library(haven)
library(readr)
library(DT)
library(tidyverse)
library(ggplot2)
library(plotly)
#library(aws.s3)
library(cowplot)
library(httr)
library(jsonlite)
library(Hmisc)
library(scales)
library(filesstrings)
library(purrr)
library(htmltools)
library(data.table)
# global variable to track size of uploaded files so that users can be warned when application busy
usage <- list()
source("server_name.R", local = TRUE)
source("redcapTokens.R", local = TRUE)
#source("awsKey.R", local = TRUE)
source("helpers.R", local = TRUE)
source("specificHelpers.R", local = TRUE)
source("REDCapURL.R", local = TRUE)
source("REDCapCore.R", local = TRUE)
source("definitions.R", local = TRUE)
# specificDefinitions should be edited to match current research network specs
source("specificDefinitions.R", local = TRUE)
# source("otherVisitStats.R", local = TRUE) add when ready to add more report features
# html for appBusy announcement
busyAnnounce <- read_file("busyAnnounce.html")
################################################################################################
# All column names in uploaded spreadsheets will be converted to all caps since variable names in
# the IeDEA data specification are all caps.
################################################################################################
# appBusy will be TRUE when the application not responsive due to calculations
appBusy <- FALSE
changelogVersion <- getAllRecords(tokenForHarmonistChangelog, 'HarmonistChangelog',
fields = 'version_num')
if (inherits(changelogVersion, "postFailure")){
versionLinkText <- "" # to hide link if REDCap isn't responding
} else {
changelogVersion <- rbindlist(changelogVersion, fill=TRUE)
sorted_versions <- sort(changelogVersion$version_num, decreasing = TRUE)
current_version <- toString(sorted_versions[1])
versionLinkText <- paste("Harmonist Data Toolkit Version ", current_version)
}
shinyUI <- dashboardPage(
title = paste0(networkName," Harmonist Data Toolkit"),
# custom header to include badge to indicate presence or absence of an active data request
tags$header(
span(
img(src="projectFiles/project_logo_100_40.png"), # filename stored in Harmonist0C, file must be in www directory
span("Harmonist Data Toolkit",class="harmonist-title"),
class = "harmonist-logo"
),
uiOutput("requestStatus", class = "request-status"),
class = "main-header"
),
# Sidebar panel
dashboardSidebar(width = 260,
collapsed = FALSE,
sidebarMenuOutput("menu"),
uiOutput("exitUI"),
uiOutput("warnOnQuit"),
tags$div(
id = "versionInfo",
tags$p(actionLink('changelogLink', versionLinkText)),
tags$p(tags$a("Contact us", href="mailto:[email protected]", target="_blank"))
)
),
#main Panel
dashboardBody(
shinyjs::useShinyjs(),
tabItems(
tabItem(tabName = "welcome",
uiOutput("welcomeUI")
),
tabItem(tabName = "upload",
fluidPage(
uiOutput("uploadPage")
)
),
tabItem(tabName = "reviewerror",
fluidPage(
uiOutput("errorSummarySep")
)
),
tabItem(tabName = "summaryReports",
fluidPage(
uiOutput("reportPage")
)
),
tabItem(tabName = "submit",
fluidPage(
uiOutput("submitSummary"),
uiOutput("submitOptions"),
uiOutput("submitOutcome"),
uiOutput("afterSubmit")
)
),
tabItem(tabName = "interactivePlots",
uiOutput("plotUI")
),
tabItem(tabName = "help",
uiOutput("helpTabUI")
),
tabItem(tabName = "changelog",
uiOutput("changelogTabUI")
)
),
tags$head(
tags$link(rel = "stylesheet", type = "text/css", href = "AdminLTE.css"),
tags$link(rel = "stylesheet", type = "text/css", href = "style.css"),
# setup google analytics (only if file exists)
if (file.exists("google-analytics.txt")) {
includeHTML("google-analytics.txt")
}
),
# css to force error detail modal boxes to be wide enough to show content
tags$style(
type = 'text/css',
'.modal-dialog.errdetail { width: fit-content !important; }'
)
)
)
shinyServer <- function(input, output, session){
sessionID <- reactive(session$token)
# code to compile lists and tables of uploaded files and variables
source("uploadDetails.R", local = TRUE)
# code to match uploaded data with data model
source("formattingTablesCode.R", local = TRUE)
# code for each page of application UI -------------------------------
source("welcomeTab.R", local = TRUE)
source("uploadTab.R", local = TRUE)
source("reviewerrorTab.R", local = TRUE)
source("summaryReportsTab.R", local = TRUE)
source("submitTab.R", local = TRUE)
source("helpTab.R", local = TRUE)
source("exitTab.R", local = TRUE)
source("changelogTab.R", local = TRUE)
source("REDCapHelpers.R", local = TRUE)
source("modalFunctions.R", local = TRUE)
source("dateChecking.R", local = TRUE)
source("dataChecks.R", local = TRUE)
source("dateComparisons.R", local = TRUE)
source("dataQuality.R", local = TRUE)
# code for report generation ---------------------------------------
source("reportGenerationOptions.R", local = TRUE)
source("downloadReports.R", local = TRUE)
source("downloadErrorDetails.R", local = TRUE)
# code for interactive plot exploration-----------------------------
source("interactivePlotting.R", local = TRUE)
# reactive values
sessionStartTime <- reactiveVal(isolate(Sys.time()))
lastActivity <- reactiveVal(isolate(Sys.time()))
# reload guard is javascript function that prevents application from closing. Must be set to FALSE
# to allow application to close session
reloadGuardOn <- reactiveVal(FALSE)
sessionOver <- reactiveVal(FALSE)
# useSampleData is set to TRUE if the user chooses to run the Toolkit with the sample dataset provided
# In this case, the user should be prevented from uploading the dataset to the Hub in response to a data request
useSampleData <- reactiveVal(FALSE)
# errorCount is a reactive value that counts the number of errors detected so far. If it exceeds the value
# specified in definitions.R then errorExcess is set to TRUE and errors are no longer accumulated
# This is a temporary fix to address memory problems
errorCount <- reactiveVal(0)
errorRows <- reactiveVal(0)
errorExcess <- reactiveVal(FALSE)
# startDQ is a reactive variable that indicates that the user is ready for data quality checks to begin
startDQ <- reactiveVal(NULL)
# hubInfo is a reactive variable that indicates whether or not the user arrived at the application
# with a valid token (fromHub will be TRUE if that token is associated with a data request)
# and stores the details about the user if they have arrived
# with a valid token
hubInfo <- reactiveValues(
fromHub = NULL,
userDetails = NULL,
dataRequest = FALSE
)
# recordDeleted reactive variable to indicate that record in Harmonist 18 security has been deleted
# if the user has entered with an encrypted token from the Hub
recordDeleted <- reactiveVal(FALSE)
# testUser is a reactive variable that will prevent the creation of records in Harmonist 17
# if TRUE
# probably take this out JUDY
testUser <- reactiveVal(FALSE)
# authenticatedUser will be TRUE once user token has been confirmed in REDCap
# Once session ends, set as FALSE
authenticatedUser <- reactiveVal(FALSE)
# resetFileInput - reactive resetFileInput$reset value to indicate if user is starting over with new files
# initially, reset = FALSE. If user chooses uploading a new dataset, reset = TRUE
# When reset == TRUE, all variables and UI associated with uploaded dataset reset to NULL
resetFileInput <- reactiveValues(
reset = FALSE,
newData = FALSE
)
# tablesAndVariables - reactive value to store lists of uploaded tables and variables
tablesAndVariables <- reactiveValues(
details = NULL,
blankTables = NULL
)
# submitSuccess reactive Val to indicate if effort to submit dataset to AWS was successful or not
submitSuccess <- reactiveVal(NULL)
groupByChoice <- reactiveVal(defGroupVar)
currentGroupSelection <- reactiveVal(NULL)
finalGroupChoice <- reactiveVal(NULL)
#logic to terminate application execution if idle
observe({
# Re-execute this reactive expression after 10 minutes (600,000 milliseconds).
# This expression could also be re-executed when the lastActivity value changes, so it needs to be checked.
if (is.null(infile())) return()
cat("Session:", isolate(sessionID()),"is active",
as.character(now()), "\n", sep = " ", file = stderr())
if (sessionOver()) {
reloadGuardOn(FALSE)
cat("Session:", isolate(sessionID()),"Application already over, another reload/close attempt",
as.character(now()), "\n", sep = " ", file = stderr())
session$reload()
session$close()
return()
}
invalidateLater(intervalToCheckUserActivity, session)
idle <- difftime(Sys.time(), isolate(lastActivity()), units = "mins") # number of minutes since last activity
if (idle >= idleMinToWarn && idle < idleMinToExit ) {
reloadGuardOn(FALSE)
# x minutes of inactivity
# Show modal dialog to warn user that session is timing out in 10 minutes
idleWarningModal(idleTime = round(idle, digits = 0))
}
else if (idle >= idleMinToExit) {
reloadGuardOn(FALSE)
idleExitModal(idleTime = round(idle, digits = 0))
cat("Session:", sessionID(),"Initiating exit actions because idle too long",
as.character(now()), "\n", sep = " ", file = stderr())
exitActions()
}
})
# getUserInfo ------------------------------------------------------
# reactive variable to retrieve details about user if entered from the Hub, NULL otherwise
getUserInfo <- reactive({
# if no hub, then no authorization?
if (projectDef$hub_y != "1") return(NULL)
query <- parseQueryString(session$clientData$url_search)
encryptedToken <- query[["tokendt"]]
if (is.null(encryptedToken)){
authenticatedUser(FALSE)
return(NULL)
}
invalidToken <- FALSE
decryptedToken <- getCrypt(encryptedToken,"d")
if (is.null(decryptedToken)) invalidToken <- TRUE
else {
userInfo <- getOneRecord(tokenForHarmonist18, decryptedToken,
projectName = "Harmonist 18")
if (inherits(userInfo, "postFailure")) {
errorMessageModal(messageHeader = "REDCap Error",
message = "Inability to access REDCap at this time",
# secondaryMessage = "Session will continue without access to data submission")
secondaryMessage = "Please contact [email protected] if this error persists")
updateTabItems(session,"tabs", "welcome")
# no longer allow open access to Toolkit if authentication required
if (authRequired){
invalidToken <- TRUE
}
return(NULL)
}
# check once more - if valid token then userInfo will be list of 14 elements
if (is_empty(userInfo) || length(userInfo) < 2){
invalidToken <- TRUE
} else {
expiration <- userInfo$tokenexpiration_ts
# if no expiration date in record OR if expiration date has passed, invalid token
if (is_blank(expiration) || (Sys.Date() - as.Date(expiration) > 1)) invalidToken <- TRUE
else {
userInfo$decryptedToken <- decryptedToken
cat("Session:", isolate(sessionID())," valid token","\n", file = stderr())
authenticatedUser(TRUE)
}
}
}
if (!invalidToken){
hubPermissionInfo <- getOneRecord(tokenForHarmonist5, userInfo$uploaduser_id, projectName = "Harmonist 5")
if ("harmonist_regperm" %in% names(hubPermissionInfo)){
userInfo$harmonist_regperm <- hubPermissionInfo$harmonist_regperm
} else {
userInfo$harmonist_regperm <- ""
}
}
if (invalidToken){
if (authRequired){
authenticatedUser(FALSE)
}
errorMessageModal(messageHeader = "Invalid, missing, or expired Toolkit token",
secondaryMessage = "")
# message = tags$b("Please request an ",a("IeDEA Toolkit token",
# href="https://bit.ly/iedeatoken", target="_blank")))
# message = "Please request a Toolkit token **give bit.ly link here?** or choose a data request in the Hub")
# message = "Please log in to the Hub again and choose Upload Data.",
# secondaryMessage = "You may also continue this session without access to data submission option")
updateTabItems(session,"tabs", "welcome")
return(NULL)
}
return(userInfo)
})
# At beginning of session this will be triggered and will in obtain user info and determine
# if the user entered from the hub or not
observeEvent(session$token,{
authenticatedUser(FALSE)
print(paste("session =", session$token, "usage = ", sum(unlist(usage))))
postProgress(list(action_step = "start"))
hideTab(inputId = "changelog", target = "Changelog")
# if a user is testing the toolkit, no need to add progress to Harmonist 17
query <- parseQueryString(session$clientData$url_search)
# fromHub is TRUE if a user is responding to a data request in the Hub
hubInfo$fromHub <- FALSE
userInfo <- getUserInfo()
if (is.null(userInfo) && authRequired && !authenticatedUser()){
print("not authenticated user")
hubInfo$fromHub <- FALSE
hubInfo$userDetails <- defaultUserInfo
} else if (is.null(userInfo)){
print("auth not required and unknown user")
hubInfo$fromHub <- FALSE
hubInfo$userDetails <- defaultUserInfo # in definitions.R
} else {
print("we do have user info")
if (userInfo$datacall_id != ""){
hubInfo$dataRequest <- TRUE
}
hubInfo$fromHub <- TRUE
updateTabItems(session,"tabs", "upload")
regionID <- as.numeric(userInfo[["uploadregion_id"]])
# store region codes and names in a data frame-- either from REDCap or if REDCap not available,
# the codes and names are provided (must be updated manually)
regionData <- getOneRegionInfo(regionID)
userInfo[["regionName"]] <- regionData$region_name
userInfo[["regionCode"]] <- regionData$region_code
hubInfo$userDetails <- as.list(userInfo)
}
})
tooBusy <- reactive({
if (is.null(infile())){
invalidateLater(10000, session)
totalUsage <- sum(unlist(usage))
if (totalUsage > maxTotalUsage){ #maxTotalUsage defined in definitions.R
return(TRUE)
}
}
return(FALSE)
})
output$tooBusyMessage <- renderUI({
print(sum(unlist(usage)))
if (tooBusy()){
cat("Session:", sessionID(),"User prevented from uploading files",
as.character(now()), "usage=", sum(unlist(usage)), "\n", sep = " ", file = stderr())
return(
box(#class = "alert alert-danger",
width = 12,
solidHeader = TRUE,
status = "danger",
title = span("Harmonist Toolkit Busy"),# style = "color: white"),
tagList(
tags$p("Please return to the toolkit in 15 minutes. Other users have uploaded large datasets which will make your session slow. Please contact the harmonist team if you experience this error multiple times.")#,
)
)
)
} else return(NULL)
})
# backToHubMessage - reactive variable, adds option at top of every page to return to the IeDEA Hub
# *if* the user came from the Hub. Otherwise, no option to return to Hub
backToHubMessage <- reactive({
if (is.null(hubInfo$fromHub)) return(NULL)
if (projectDef$hub_y != "1") return(NULL)
if (hubInfo$fromHub){
# if no active data request
if (!hubInfo$dataRequest) return(NULL)
hub_url <- paste0(plugin_url, "?token=",
userDetails()$uploadhub_token, "&option=sop",
"&record=", userDetails()$datacall_id,
"&pid=58325")
tags$a(span(paste(userDetails()$uploadconcept_mr,"on Hub"),icon("external-link")),
href = hub_url, target="_blank", class = "backIedea")
} else {
return(NULL)
}
})
# if user decides to upload new dataset, unlink previously loaded dataset and change reset to TRUE
observeEvent(input$uploadNew,{
# if DQ checks have not been performed, go ahead and restart:
if (is.null(formattedTables())){
lastActivity(Sys.time())
cleanupFiles(infile())
startDQ(NULL)
resetFileInput$reset <- TRUE
resetFileInput$newData <- FALSE
errorCount(0)
errorExcess(FALSE)
useSampleData(FALSE)
submitSuccess(NULL)
tablesAndVariables <- NULL
groupByChoice(defGroupVar)
currentGroupSelection(NULL)
finalGroupChoice(NULL)
groupByInfo <- NULL
resetHistoRange()
} else {
# data quality checks are already complete. Confirm that the user wants to start over
restartAfterDQ()
}
})
# if user decides to upload new dataset, unlink previously loaded dataset and change reset to TRUE
observeEvent(input$yesRestart,{
lastActivity(Sys.time())
cleanupFiles(infile())
startDQ(NULL)
resetFileInput$reset <- TRUE
resetFileInput$newData <- FALSE
errorCount(0)
errorRows(0)
errorExcess(FALSE)
useSampleData(FALSE)
submitSuccess(NULL)
tablesAndVariables <- NULL
groupByChoice(defGroupVar)
currentGroupSelection(NULL)
finalGroupChoice(NULL)
groupByInfo <- NULL
resetHistoRange()
})
# when user selects files in fileInput UI, reset newData flag to TRUE and reset flag to FALSE
observeEvent(input$loaded,{
resetFileInput$newData <- TRUE
resetFileInput$reset <- FALSE
errorCount(0)
errorRows(0)
errorExcess(FALSE)
reloadGuardOn(TRUE)
# if no data has been uploaded before, and if the session start time
# was more than 2 minutes ago, that means the session hasn't really started.
# The application has been idle so reset the session start time as now
# so that the session_mins value in REDCap is accurate
if (is.null(infile()) && difftime(Sys.time(), sessionStartTime(), units="mins") > 2){
sessionStartTime(Sys.time())
}
# if it's the first time data uploaded and user is from Hub, delete token
# changed to only delete token if responding to data request
if (hubInfo$dataRequest && !recordDeleted()){
if (hubInfo$userDetails$decryptedToken != "tokenjudy"){
result <- deleteOneRecord(tokenForHarmonist18, hubInfo$userDetails$decryptedToken)
if (inherits(result, "postFailure")) {
# record NOT deleted, so this means that someone could re-use the
# token later to possibly upload another dataset
} else {
recordDeleted(TRUE)
}
}
}
cat("Session:", isolate(sessionID()),"User selected files to upload at",
as.character(now()), "\n", sep = " ", file = stderr())
})
# If user clicks button on Welcome tab labeled "Continue to Step 1" change active tab to Step 1: Upload files
observeEvent(input$fromWelcomeToStep1,{
updateTabItems(session,"tabs", "upload")
})
# If user clicks button on Upload tab labeled "Continue to Step 2" change active tab to Step 2: Check data
# and initiate data quality checks with startDQ TRUE.
observeEvent(input$step2,{
if (is.null(startDQ()) &&
groupByChoice() == defGroupVar &&
groupByInfo()$numPrograms == 1 &&
!is.null(groupByInfo()$otherGroupOptions)){
showModal(tags$div(id="dataQualityChecks",
modalDialog(
easyClose = FALSE,
title = "Confirm Grouping Options",
size = 'l',
paste0("Your patients are currently grouped by ",
defGroupVar,
" and are all in one group."),
"To choose a different grouping option select the Change button below.",
footer = tagList(
actionButton("continueOneProg", "Continue"),
actionButton("changeSelection", "Change", class = "btn-success")
),
fade = FALSE
)
))
} else {
startStep2()
}
# if some fatal error was found in data checks, errorTable() will be null
if (is.null(errorTable())){
updateTabItems(session, "tabs", "upload")
} else updateTabItems(session,"tabs", "reviewerror")
})
# If user clicks button on reviewerrors tab labeled "Continue to Step 3" change active tab to Step 3: create summary
observeEvent(input$step3,{
updateTabItems(session,"tabs", "summaryReports")
})
# If user clicks button on Create summary tab labeled "Continue to Step 4" change active tab to Step 4: Submit data
observeEvent(input$step4,{
updateTabItems(session,"tabs", "submit")
})
# reactive variable to track if URL query string was already updated in response to browser navigation arrow click
justUpdated <- reactiveVal(FALSE)
# if a new tab is selected (either by clicking on a tab or using the browser navigation arrows),
# check to see if query string was already updated. If not, update the URL with the
# selected tab
observeEvent(input$tabs,{
if (justUpdated()) {
justUpdated(FALSE)
return(NULL)
}
tab <- input$tabs
# if user has chosen Step 2 tab and dataset has been uploaded but data quality checks haven't been
# initiated, start data quality checks
if ((tab == "reviewerror") && (!is.null(uploadedTables())) && is.null(startDQ())){
if (groupByChoice() == defGroupVar &&
groupByInfo()$numPrograms == 1 &&
!is.null(groupByInfo()$otherGroupOptions)){
showModal(tags$div(id="dataQualityChecks",
modalDialog(
easyClose = FALSE,
title = "Confirm Grouping Options",
size = 'l',
paste0("Your patients are currently grouped by ",
defGroupVar,
" and are all in one group."),
"To choose a different grouping option select the Change button below.",
footer = tagList(
actionButton("continueOneProg", "Continue"),
actionButton("changeSelection", "Change", class = "btn-success")
),
fade = FALSE
)
))
} else {
startStep2()
}
}
tokenString <- NULL
token <- getQueryString()[["tokendt"]]
if (!is_empty(token)){
tokenString <- paste0("tokendt=", token, "&")
}
lastActivity(Sys.time())
req(sessionID())
# update URL to include tab= newly selected tab name
updateQueryString(paste0("?",tokenString,"tab=",input$tabs), mode = "push")
# track how often user clicks on Help or Review Errors tabs
if (tab == "help"){
postProgress(list(action_step = "help"))
} else if ((tab == "reviewerror") && !is.null(uploadedTables())){
postProgress(list(action_step = "reviewerror"))
}
})
observeEvent(input$continueOneProg,{
removeModal()
startStep2()
})
startStep2 <- function(){
tokenString <- NULL
token <- getQueryString()[["tokendt"]]
if (!is_empty(token)){
tokenString <- paste0("tokendt=", token, "&")
}
startDQ(TRUE)
finalGroupChoice(groupByChoice())
formattedTables()
errorTable()
updateQueryString(paste0("?",tokenString,"tab=reviewerror"), mode = "push")
}
observeEvent(input$changeSelection,{
tokenString <- NULL
token <- getQueryString()[["tokendt"]]
if (!is_empty(token)){
tokenString <- paste0("tokendt=", token, "&")
}
updateQueryString(paste0("?",tokenString,"tab=reviewerror"), mode = "push")
showGroupModal(saveAndGo = TRUE)
})
# when the URL changes, check to see if the new tab is different from the current tab
#
observeEvent(getQueryString()[["tab"]],{
req(input$tabs)
newTabRequest <- getQueryString()[["tab"]]
if (newTabRequest == "showMissing") {
updateTabItems(session, "tabs", "upload")
}
justUpdated(FALSE)
if (newTabRequest != input$tabs){
updateTabItems(session, "tabs", newTabRequest)
justUpdated(TRUE)
}
})
# userDetails ------------------------------------------------------------
# user information either passed through URL if from iedeahub or selected by user otherwise
userDetails <- reactive({
if (is.null(hubInfo$userDetails)) return(NULL)
return(hubInfo$userDetails)
})
#read in example concept description json. In the future: choose specific concept as determined by token in URL
concept <- reactive({
if (projectDef$hub_y != "1") return(rjson::fromJSON(file = "concept0.json"))
if (!hubInfo$fromHub) return(rjson::fromJSON(file = "concept0.json"))
cat("Session:", isolate(sessionID())," user is from the Hub","\n", file = stderr())
# if this is a Hub user but no data call
if (!hubInfo$dataRequest) return(rjson::fromJSON(file = "concept0.json"))
record_id_Harmonist3 <- hubInfo$userDetails$datacall_id
conceptInfo <- getOneRecord(tokenForHarmonist3, record_id_Harmonist3, projectName = "Harmonist 3", formName = "data_specification")
if (inherits(conceptInfo, "postFailure")) {
errorMessageModal(messageHeader = "Failed to fetch request concept",
message = "Please check internet connection and try again later",
secondaryMessage = "REDCap could not access data request details")
updateTabItems(session, "tabs", "welcome")
# reset so that session can continue but without concept details #revisit this because it doesn't fix
hubInfo$fromHub <- FALSE
return(rjson::fromJSON(file = "concept0.json"))
}
conceptInfo <- as.list(conceptInfo)
conceptInfo$tablefields <- rjson::fromJSON(conceptInfo$shiny_json[[1]])
conceptInfo$contact1 <- getOneRecord(tokenForHarmonist5, conceptInfo$sop_creator[[1]], projectName = "Harmonist 5")
# if (conceptInfo$sop_creator2 != ""){ # now it's "Select Name" if empty ?
conceptInfo$contact2 <- getOneRecord(tokenForHarmonist5, conceptInfo$sop_creator2[[1]], projectName = "Harmonist 5")
# } else{
# conceptInfo$contact2 <- ""
# }
conceptInfo$datacontact <- getOneRecord(tokenForHarmonist5, conceptInfo$sop_datacontact[[1]], projectName = "Harmonist 5")
# data downloaders are stored as a comma-delimited list in REDCap sop_downloaders
downloaders <- as.list(strsplit(conceptInfo$sop_downloaders[[1]], ",")[[1]])
conceptInfo$downloaders <- lapply(downloaders, function(x){getOneRecord(tokenForHarmonist5, x, projectName = "Harmonist 5")})
# consolidate requested file format info
formatPrefs <- names(conceptInfo)[str_detect(names(conceptInfo), "dataformat_prefer")]
requestedFormats <- c()
requestedExtensions <- c()
for (formatPref in formatPrefs){
formatChosen <- conceptInfo[[formatPref]]
if (is.null(formatChosen)) next
# formatChosen will be "1" if user selected that format
if (formatChosen == "1") {
index <- as.numeric(str_after_last(formatPref, "_"))
formatName <- fileFormats[[as.character(index)]] #fileFormats in definitions.R
formatExtension <- fileExtensions[[as.character(index)]] #fileExtensions in definitions.R
requestedFormats <- c(requestedFormats, formatName)
requestedExtensions <- c(requestedExtensions, formatExtension)
}
}
if (is.null(requestedFormats)) requestedFormats <- "None specified"
conceptInfo$requestedFormats <- requestedFormats
conceptInfo$requestedExtensions <- requestedExtensions
conceptInfo$sop_inclusion <- removeHTML(conceptInfo$sop_inclusion)
conceptInfo$sop_exclusion <- removeHTML(conceptInfo$sop_exclusion)
cat("Session:", isolate(sessionID()),
" preferred formats: ", requestedFormats, "\n", file = stderr())
return(conceptInfo)
})
# request status badge in header, persists, indicates if user is responding to active data request
output$requestStatus <- renderUI({
if (projectDef$hub_y != "1") return(NULL)
if (is.null(hubInfo$userDetails)) return(NULL)
# if (!hubInfo$dataRequest) return(NULL) now that auth required,
# if user details exist, show them
if (hubInfo$fromHub){
region <- userDetails()$regionCode
name <- paste(userDetails()$uploaduser_firstname, userDetails()$uploaduser_lastname)
return(
tagList(span(region, class="label label-primary"), span(name))
)
} else {
return(
tagList(span("No active data request", class="badge badge-request"))
)
}
})
# infile -----------------------------------------------------------------
# infile is a reactive variable that returns link to files selected and uploaded to toolkit
# (unzipped if a zip file was selected)
infile <- reactive({
if (resetFileInput$reset) return(NULL)
if (!resetFileInput$newData) return(NULL)
req(session)
req(userDetails())
lastActivity(isolate(Sys.time()))
if (useSampleData()){
dir <- tempfile(pattern = 'dir')
zipPath <- file.path("www", "projectFiles", "sample_dataset.zip")
filenames <- unzip(zipPath, exdir = dir)
result <- as.data.frame(t(sapply(filenames, function(filename) {
list(name = basename(filename), size = file.size(filename), type = "", datapath = filename)
})))
return(list(files = result))
}
if (is.null(input$loaded)) return(NULL)
cat("Session:", sessionID(),"User files selected at",
as.character(now()), "size",
paste(input$loaded$size,collapse = ","),"\n", sep = " ", file = stderr())
postProgress(list(action_step = "uploaddata",
toolkituser_id = userDetails()$uploaduser_id,
datarequest_id = userDetails()$datacall_id,
upload_filenames = paste(input$loaded$name,collapse = ","),
upload_filesize = paste(as.character(input$loaded$size),
collapse = ", ")))
zipTypes <- c("application/zip", "application/x-zip-compressed")
# check to see if the user uploaded a zip file
if (any(input$loaded$type %in% zipTypes)) {
# if a zip file was shared, make sure that only one file was uploaded
if (nrow(input$loaded) > 1) {
errorMessageModal(messageHeader = "File Selection Error",
message = tagList(
tags$p("You must either upload a single ZIP file or multiple data files."),
tags$p("Uploaded files detected:"),
makeBulletedList(input$loaded$name)
)
)
cleanupFiles(input$loaded)
return(NULL)
}
# save zip file path in case the user wants to upload it later
zipfile <- input$loaded$datapath
# extract the zip file and return an error if the unzip function is not successful
filenames <- tryCatch(unzip(zipfile, exdir = dirname(input$loaded$datapath)),
warning = function(w) return(NULL),
error = function(e) return(NULL)
)
if (is.null(filenames)){
errorMessageModal(
messageHeader = "Unable To Open ZIP File",
message = paste0("Error: ", input$loaded$name, " does not appear to be saved in a valid ZIP file format. Please confirm that binary compression or other non-standard ZIP format was not used to save the dataset."))
cleanupFiles(input$loaded)
return(NULL)
}
result <- as.data.frame(t(sapply(filenames, function(filename) {
list(name = basename(filename), size = file.size(filename), type = "", datapath = filename)
})))
#unlink(input$loaded$datapath) # check to see if this works
# are there any nested zip files? are there multiple files with the same name? These are hard stops
nestedZipFlag <- any(str_detect(result$name, ".zip"))
tableNames <- tolower(file_path_sans_ext(result$name))
tableNames <- tableNames[which(tableNames %in% tolower(names(tableDef)))]
duplicateTableFlag <- any(duplicated(tableNames))
if (nestedZipFlag || duplicateTableFlag){
nestedZipMsg <- ifelse(nestedZipFlag, "nested ZIP files", "")
duplicateTableMsg <- ifelse(duplicateTableFlag, " files with duplicate table names", "")
connector <- ifelse(nestedZipFlag && duplicateTableFlag, "and", "")
errorMessageModal(
messageHeader = "File Selection Error",
message = tagList(
tags$p("Your ZIP file included",
nestedZipMsg,
connector,
duplicateTableMsg),
tags$p("Uploaded files detected:"),
makeBulletedList(result$name)
)
)
cleanupFiles(input$loaded)
return(NULL)
}
list(files = result, zipfile = zipfile)
} else {
# user uploaded one or more non-zip files
list(files = input$loaded)
}
})
# readOneTable ------------------------------------------------------------
# readOneTable reads in one table at a time and converts the column names to all caps
# to match the IeDEA DES and forces table
readOneTable <- function(tableName){
print("Begin ReadOneTable")
inputLink <- infile()$files
index <- which(tolower(file_path_sans_ext(inputLink$name)) == tolower(tableName) &
tolower(file_ext(inputLink$name)) %in% validFileTypes)
fileExt <- tolower(file_ext(inputLink$name[index]))
updateModal(message = inputLink$name[index],
title = "Reading file",
subtitle = NULL)
# read csv files
if (fileExt == "csv"){
myfile <- tryCatch(read_csv(inputLink[[index, 'datapath']],
col_types = cols(.default = "c"),
na = character(),
trim_ws = TRUE),
# warning = function(w) {},# JUDY revisit this. Warning occurs if strange characters in fields
error = function(e) {
fileReadError(extension = fileExt,
fileName = inputLink$name[index],
errorMessage = e$message)
resetFileInput$reset <- TRUE
return(NULL)
})
}
# read SAS sas7bdat files
else if (fileExt == "sas7bdat"){
myfile <- tryCatch(read_sas(inputLink[[index, 'datapath']]),
error = function(e){
fileReadError(extension = fileExt,
fileName = inputLink$name[index],
errorMessage = e$message)
resetFileInput$reset <- TRUE
return(NULL)
})
}
# read Stata DTA files
else if (fileExt == "dta"){
myfile <- tryCatch(read_dta(inputLink[[index, 'datapath']]),
error = function(e){
fileReadError(extension = fileExt,
fileName = inputLink$name[index],
errorMessage = e$message)
resetFileInput$reset <- TRUE
return(NULL)
})
}
# read SPSS SAV files
else if (fileExt == "sav"){
myfile <- tryCatch(read_sav(inputLink[[index, 'datapath']]),
error = function(e){
fileReadError(extension = fileExt,
fileName = inputLink$name[index],
errorMessage = e$message)
resetFileInput$reset <- TRUE
return(NULL)
})
}
# read R rds files
else if (fileExt == "rds"){
myfile <- tryCatch(read_rds(inputLink[[index, 'datapath']]),
error = function(e){
fileReadError(extension = fileExt,
fileName = inputLink$name[index],
errorMessage = e$message)
resetFileInput$reset <- TRUE
return(NULL)
})
}
else { # we should never reach this point...
errorMessageModal(messageHeader = "Invalid File Type",
message = tagList(
tags$p("Your uploaded files included: "),
tags$p("Valid file extensions for data model tables:",
paste(validFileTypes, collapse = ", "), " and zip")
)
)
resetFileInput$reset <- TRUE
return(NULL)
}
if (!is.null(myfile)){
myfile <- as.data.frame(myfile)
# determine if any of the column names include non-alphabetic characters
# because later code will crash with strange characters
cleanColNames <- str_replace_all(names(myfile), " ", "")
names(myfile) <- cleanColNames