-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.R
1239 lines (1008 loc) · 41.1 KB
/
server.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
pacman::p_load(shiny, shinyjs, shinyWidgets, magrittr, dplyr,
datimvalidation, ggplot2, datimutils,
futile.logger, paws, datapackr, scales,
DT, purrr, rpivotTable, waiter,
flextable, officer, gdtools, digest, fansi)
# js ----
# allows for using the enter button
jscode_login <- '$(document).keyup(function(e) {
var focusedElement = document.activeElement.id;
console.log(focusedElement);
if (e.key == "Enter" && focusedElement == "user_name") {
$("#password").focus();
} else if (e.key == "Enter" && focusedElement == "password") {
$("#login_button").click();
}
});'
#Set the maximum file size for the upload file
options(shiny.maxRequestSize = 150 * 1024 ^ 2)
#Allow unsanitized error messages
options(shiny.sanitize.errors = FALSE)
#Initiate logging
logger <- flog.logger()
if (!file.exists(Sys.getenv("LOG_PATH"))) {
file.create(Sys.getenv("LOG_PATH"))
}
flog.appender(appender.console(), name = "datapack")
################ OAuth Client information #####################################
if (interactive()) {
# testing url
options(shiny.port = 3123)
APP_URL <- "http://127.0.0.1:3123/"# This will be your local host path
} else {
# deployed URL
APP_URL <- Sys.getenv("APP_URL") #This will be your shiny server path
}
{
oauth_app <- httr::oauth_app(Sys.getenv("OAUTH_APPNAME"),
key = Sys.getenv("OAUTH_KEYNAME"), # dhis2 = Client ID
secret = Sys.getenv("OAUTH_SECRET"), #dhis2 = Client Secret
redirect_uri = APP_URL
)
oauth_api <- httr::oauth_endpoint(base_url = paste0(Sys.getenv("BASE_URL"),"uaa/oauth"),
request=NULL,# Documentation says to leave this NULL for OAuth2
authorize = "authorize",
access="token"
)
oauth_scope <- "ALL"
}
has_auth_code <- function(params) {
return(!is.null(params$code))
}
shinyServer(function(input, output, session) {
validation_results <- reactive({ validate() }) # nolint
ready <- reactiveValues(ok = FALSE)
user_input <- reactiveValues(authenticated = FALSE,
status = "",
d2_session = NULL,
memo_authorized = FALSE,
file1_state = NULL,
file2_state = NULL,
uuid = NULL)
epi_graph_filter <- reactiveValues(snu_filter = NULL)
kpCascadeInput_filter <- reactiveValues(snu_filter = NULL)
snu_selector <- reactive({
validation_results() %>% snuSelector()
})
observeEvent(input$file1, {
shinyjs::show("validate")
user_input$file1_state <- 'uploaded'
ready$ok <- FALSE
shinyjs::enable("validate")
})
observeEvent(input$file2, {
shinyjs::show("validate")
user_input$file2_state <- 'uploaded'
ready$ok <- FALSE
shinyjs::enable("validate")
})
observeEvent(input$validate, {
shinyjs::disable("file1")
shinyjs::disable("file2")
shinyjs::disable("validate")
ready$ok <- TRUE
})
observeEvent(input$reset_input, {
shinyjs::reset("side-panel")
shinyjs::reset("file1")
shinyjs::reset("file2")
shinyjs::enable("file1")
shinyjs::enable("file2")
shinyjs::disable("validate")
shinyjs::disable("downloadDataPack")
shinyjs::disable("download_messages")
shinyjs::disable("send_paw")
shinyjs::disable("downloadValidationResults")
shinyjs::disable("compare")
user_input$file1_state <- 'reset'
user_input$file2_state <- 'reset'
ready$ok <- FALSE
})
file_input <- reactive({
file1_state <- user_input$file1_state
file2_state <- user_input$file2_state
if (is.null(file1_state) && is.null(file2_state)) {
return(NULL)
}
input_files <- list()
if (!is.null(file1_state)) {
if (file1_state == "uploaded") {
input_files$file1 <- input$file1
}
if (file1_state == "reset") {
input_files$file1 <- NULL
}
}
if (!is.null(file2_state)) {
if (file2_state == "uploaded") {
input_files$file2 <- input$file2
}
if (file2_state == "reset") {
input_files$file2 <- NULL
}
}
input_files
})
observeEvent(input$send_paw, {
waiter_show(html = waiting_screen_paw, color = "rgba(128, 128, 128, .8)")
d <- validation_results()
r <- sendTimeStampLogToS3(d)
timestampUploadUI(r)
sendDataPackErrorUI(r)
r <- sendDATIMExportToS3(d)
if (!is.null(d$datim$year2)) {
r <- sendYear2ExportToS3(d)
}
sendEventToS3(d, "PAW_EXPORT")
waiter_hide()
datimExportUI(r)
})
observeEvent(input$epiCascadeInput, {
epi_graph_filter$snu_filter <- input$epiCascadeInput
})
observeEvent(input$kpCascadeInput, {
kpCascadeInput_filter$snu_filter <- input$kpCascadeInput
})
observeEvent(input$logout, {
req(input$logout)
# Gets you back to the login without the authorization code at top
updateQueryString("?",mode="replace",session=session)
flog.info(paste0("User ", user_input$d2_session$me$userCredentials$username, " logged out."))
ready$ok <- FALSE
user_input$authenticated <- FALSE
user_input$user_name <- ""
user_input$authorized <- FALSE
user_input$d2_session <- NULL
d2_default_session <- NULL
gc()
session$reload()
})
output$ui <- renderUI({
if (user_input$authenticated == FALSE) {
##### UI code for login page
fluidPage(
fluidRow(
column(width = 2, offset = 5,
br(), br(), br(), br(),
uiOutput("uiLogin")
)
)
)
} else {
uiOutput("authenticated")
}
})
# Username and password text fields, login button
output$uiLogin <- renderUI({
wellPanel(fluidRow(
#img(src = "pepfar.png", align = "center"),
tags$head(tags$script(HTML(jscode_login))), # enter button functionality for login button
tags$div(HTML('<center><img src="pepfar.png"></center>')),
h4("Welcome to the Target Setting Validation App. Please login with your DATIM credentials:")
),
fluidRow(
actionButton("login_button_oauth","Log in with DATIM"),
uiOutput("ui_hasauth"),
uiOutput("ui_redirect")
),
fluidRow(
tags$hr(),
tags$div(HTML("<ul><li><h4>Please be sure you fully populate the PSNUxIM",
" tab when receiving a new PSNUxIM Tool. Consult <a href = ",
"\"https://apps.datim.org/target-setting-userguide/\" target = ",
"\"blank\" > the user guide</a> for further information!",
"</h4></li><li><h4>See the latest updates to the app <a href =",
"\"https://github.com/pepfar-datim/datapackr-app/blob/master/CHANGELOG.md\"",
"target = \"blank\">here.</h4></a></li></ul>"))
),
tags$hr(),
fluidRow(HTML(getVersionInfo())))
})
output$authenticated <- renderUI({
wiki_url <- a("Target Setting Tool User Guide",
href = "https://apps.datim.org/target-setting-userguide/",
target = "_blank")
fluidPage(
tags$head(tags$style(".shiny-notification {
position: fixed;
top: 10%;
left: 33%;
right: 33%;}")),
use_waiter(),
sidebarLayout(
sidebarPanel(
shinyjs::useShinyjs(),
id = "side-panel",
tagList(wiki_url),
tags$hr(),
fileInput(
"file1",
"Choose a Target Setting Tool (Must be an XLSX file!)",
accept = c("application/xlsx",
".xlsx"),
width = "440px"
),
fileInput(
"file2",
"Choose a PSNUxIM Tool (Must be an XLSX file!):",
accept = c("application/xlsx",
".xlsx"),
width = "440px"),
actionButton("validate", "Validate"),
tags$hr(),
p(id = "tool_info", ""),
tags$hr(),
selectInput("downloadType", "Download type", NULL),
downloadButton("downloadOutputs", "Download"),
tags$hr(),
actionButton("send_paw", "Send to PAW"),
tags$hr(),
div(style = "display: inline-block; vertical-align:top; width: 80 px;",
actionButton("reset_input", "Reset inputs")),
div(style = "display: inline-block; vertical-align:top; width: 80 px;",
actionButton("logout", "Logout"))
),
mainPanel(tabsetPanel(
id = "main-panel",
type = "tabs",
tabPanel("Messages", dataTableOutput("messages")),
tabPanel("Analytics checks", tags$div(uiOutput("analytics_checks"))),
tabPanel("Indicator summary", dataTableOutput("indicator_summary"),
tags$h4("Data source: Main DataPack tabs")),
tabPanel("SNU-level summary",
dataTableOutput("snu_summary"),
tags$h4("Data source: Main DataPack tabs")),
tabPanel("Validation rules",
dataTableOutput("vr_rules"),
tags$h4("Data source: PSNUxIM tab")),
tabPanel("HTS Summary Chart",
fluidRow(column(width = 12, div(style = "height:700px", plotOutput("modality_summary")))),
fluidRow(column(width = 12, tags$h4("Data source: PSNUxIM tab")))),
tabPanel("HTS Summary Table",
dataTableOutput("modality_table"),
tags$h4("Data source: PSNUxIM tab")),
tabPanel("HTS Yield",
fluidRow(column(width = 12, div(style = "height:700px", plotOutput("modality_yield")))),
fluidRow(tags$h4("Data source: PSNUxIM tab"))),
tabPanel("HTS Recency",
dataTableOutput("hts_recency"),
tags$h4("Data source: PSNUxIM tab")),
tabPanel("VLS Testing",
fluidRow(column(width = 12, div(style = "height:700px", plotOutput("vls_summary")))),
fluidRow(column(width = 12, tags$h4("Data source: PSNUxIM tab")))),
tabPanel("Epi Cascade Pyramid",
pickerInput("epiCascadeInput", "SNU1",
choices = "",
options = list(`actions-box` = TRUE), multiple = T),
fluidRow(column(width = 12, div(style = "height:700px", plotOutput("epi_cascade")))),
fluidRow(tags$h4("Data source: SUBNATT/IMPATT data & PSNUxIM tab"))),
tabPanel("KP Cascade Pyramid",
pickerInput("kpCascadeInput", "SNU1",
choices = "",
options = list(`actions-box` = TRUE), multiple = T),
fluidRow(column(width = 12, div(style = "height:700px", plotOutput("kp_cascade")))),
fluidRow(tags$h4("Data source: Data source: SUBNATT/IMPATT data & PSNUxIM tab"))),
tabPanel("PSNUxIM Pivot",
fluidRow(column(width = 12, div(rpivotTable::rpivotTableOutput({"pivot"})))), # nolint
fluidRow(tags$h4("Data source: PSNUxIM tab"))),
tabPanel("Year 2 Pivot",
fluidRow(column(width = 12, div(rpivotTable::rpivotTableOutput({"year2_pivot"})))), # nolint
fluidRow(tags$h4("Data source: Year 2 Tab"))),
tabPanel(
"Memo Tables",
fluidRow(
pickerInput(
"memo_pivot_style",
label = "Table Style",
choices = c("Prioritization", "By Agency", "By Partner", "Comparison"),
selected = "Prioritization"
)
),
fluidRow(column(width = 12,
div(dataTableOutput({"memo_compare"})))), # nolint
fluidRow(tags$h4("Data source: PSNUxIM tab & DATIM")))
))
))
})
output$ui_redirect = renderUI({
#print(input$login_button_oauth) useful for debugging
if(!is.null(input$login_button_oauth)){
if(input$login_button_oauth>0){
url <- httr::oauth2.0_authorize_url(oauth_api, oauth_app, scope = oauth_scope)
redirect <- sprintf("location.replace(\"%s\");", url)
tags$script(HTML(redirect))
} else NULL
} else NULL
})
### Login Button oauth Checks
observeEvent(input$login_button_oauth > 0,{
#Grabs the code from the url
params <- parseQueryString(session$clientData$url_search)
#Wait until the auth code actually exists
req(has_auth_code(params))
#Manually create a token
token <- httr::oauth2.0_token(
app = oauth_app,
endpoint = oauth_api,
scope = oauth_scope,
use_basic_auth = TRUE,
oob_value = APP_URL,
cache = FALSE,
credentials = httr::oauth2.0_access_token(endpoint = oauth_api,
app = oauth_app,
code = params$code,
use_basic_auth = TRUE)
)
loginAttempt <- tryCatch({
user_input$uuid <- uuid::UUIDgenerate()
datimutils::loginToDATIMOAuth(base_url = Sys.getenv("BASE_URL"),
token = token,
app = oauth_app,
api = oauth_api,
redirect_uri= APP_URL,
scope = oauth_scope,
d2_session_envir = parent.env(environment())
) },
# This function throws an error if the login is not successful
error = function(e) {
flog.info(paste0("User ", input$user_name, " login failed. ", e$message), name = "datapack")
}
)
if (exists("d2_default_session")) {
user_input$authenticated <- TRUE
user_input$d2_session <- d2_default_session$clone()
d2_default_session <- NULL
#Need to check the user is a member of the PRIME Data Systems Group, COP Memo group, or a super user
user_input$memo_authorized <-
grepl("VDEqY8YeCEk|ezh8nmc4JbX", user_input$d2_session$me$userGroups) |
grepl(
"jtzbVV4ZmdP",
user_input$d2_session$me$userCredentials$userRoles
)
flog.info(
paste0(
"User ",
user_input$d2_session$me$userCredentials$username,
" logged in."
),
name = "datapack"
)
sendEventToS3(NULL, "LOGIN", user_input = user_input)
flog.info(
paste0(
"User ",
user_input$d2_session$me$userCredentials$username,
" logged in."
),
name = "datapack"
)
}
})
output$epi_cascade <- renderPlot({
vr <- validation_results()
epi_graph_filter_results <- epi_graph_filter$snu_filter
if (!inherits(vr, "error") & !is.null(vr)) {
subnatPyramidsChart(vr, epi_graph_filter_results)
} else {
NULL
}
}, height = 600, width = 800)
output$kp_cascade <- renderPlot({
vr <- validation_results()
kpCascadeInput_filter_results <- kpCascadeInput_filter$snu_filter
if (!inherits(vr, "error") & !is.null(vr)) {
kpCascadeChart(vr, kpCascadeInput_filter_results)
} else {
NULL
}
}, height = 600, width = 800)
output$pivot <- rpivotTable::renderRpivotTable({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
if (is.null(vr$data$analytics)) {
return(NULL)
}
PSNUxIM_pivot(vr)
} else {
NULL
}
})
output$year2_pivot <- rpivotTable::renderRpivotTable({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
if (is.null(vr$data$Year2)) {
return(NULL)
}
year2Pivot(vr)
} else {
NULL
}
})
output$memo_compare <- DT::renderDataTable({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
p_data <- switch(
input$memo_pivot_style,
"Prioritization" = vr$memo$datapack$by_prio,
"By Agency" = vr$memo$datapack$by_agency,
"By Partner" = vr$memo$datapack$by_partner,
"Comparison" = (
if ( NROW(vr$memo$comparison) > 0) {
vr$memo$comparison %>%
dplyr::select("Indicator", "Age", "Data Type", "value") %>%
dplyr::filter(`Data Type` != "Percent diff") %>%
dplyr::group_by(Indicator, Age, `Data Type`) %>%
dplyr::summarise(value = sum(value), .groups = "drop") %>%
tidyr::pivot_wider(
id_cols = c(Indicator, Age),
names_from = `Data Type` ) %>%
dplyr::filter(Diff != "0") } else {
data.frame(message="No differences detected")
}
)
)
if (!is.null(p_data)) {
table_options <-
list(columnDefs = list(list(
targets = as.vector(which(sapply(p_data,"class") == "numeric")), class = "dt-right"
)))
p_data <- p_data %>%
dplyr::mutate_if(is.numeric, function(x)
prettyNum(x, big.mark = ","))
DT::datatable(p_data,
option = table_options)
} else {
NULL
}
} else {
NULL
}
})
output$hts_recency <- DT::renderDataTable({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr$data$recency)) {
DT::datatable(vr$data$recency,
options = list(pageLength = 25, columnDefs = list(list(
className = "dt-right", targets = 2),
list(
className = "dt-right", targets = 3),
list(
className = "dt-right", targets = 4)
)))
} else {
NULL
}
})
output$modality_summary <- renderPlot({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
analytics <-
vr %>%
purrr::pluck(., "data") %>%
purrr::pluck(., "analytics")
if (is.null(analytics)) {
return(NULL)
} else {
modalitySummaryChart(vr)
}
} else {
NULL
}
}, height = 600, width = 800)
output$modality_yield <- renderPlot({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
modalityYieldChart(vr)
} else {
NULL
}
}, height = 400, width = 600)
output$vls_summary <- renderPlot({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
vr %>%
purrr::pluck(., "data") %>%
purrr::pluck(., "analytics") %>%
vlsTestingChart()
} else {
NULL
}
}, height = 600, width = 800)
output$modality_table <- DT::renderDataTable({
d <- validation_results()
if (!inherits(d, "error") & !is.null(d$data$modality_summary)) {
DT::datatable(formatModalitySummaryTable(d),
options = list(pageLength = 25, columnDefs = list(list(
className = "dt-right", targets = 2),
list(
className = "dt-right", targets = 3),
list(
className = "dt-right", targets = 4),
list(
className = "dt-right", targets = 5)
)))
} else {
NULL
}
})
output$indicator_summary <- DT::renderDataTable({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
prepareSNUSummaryTable(vr) %>%
dplyr::group_by(indicator_code) %>%
dplyr::summarise(value = format(round(sum(value, na.rm = TRUE)), big.mark = ",", scientific = FALSE)) %>%
dplyr::arrange(indicator_code)
} else {
NULL
}
})
output$snu_summary <- DT::renderDataTable({
vr <- validation_results()
if (!inherits(vr, "error") & !is.null(vr)) {
prepareSNUSummaryTable(vr) %>%
dplyr::mutate(value = format(round_trunc(value), big.mark = ",", scientific = FALSE))
} else {
data.frame(message = "No data is available to display. An error may have occurred.")
}
})
output$vr_rules <- DT::renderDataTable({
vr <- validation_results() %>%
purrr::pluck(., "tests") %>%
purrr::pluck(., "vr_rules_check")
if (inherits(vr, "error") | is.null(vr)) {
return(NULL)
}
if (NROW(vr) == 0) {
data.frame(message = "Congratulations! No validation rule issues found!")
} else {
vr %>%
dplyr::filter(!`Valid`) %>%
dplyr::select(1:6)
}
})
output$messages <- DT::renderDataTable({
vr <- validation_results()
messages <- NULL
if (is.null(vr)) {
return(NULL)
}
if (inherits(vr, "error")) {
return(paste0("ERROR! ", vr$message))
}
messages <- validation_results() %>%
purrr::pluck(., "info") %>%
purrr::pluck(., "messages")
messages_df <- data.frame( Tool = messages$tool, Severity = messages$level, Message = messages$message) %>%
dplyr::arrange(`Severity`,`Tool`)
if (NROW(messages_df) > 0) {
#Display this as a data table
DT::datatable(messages_df,
options = list(pageLength = 25, columnDefs = list(list(
className = "dt-center", targets = 2),
list(
className = "dt-left", targets = 3)
))) %>% formatStyle(
'Severity',
target = 'row',
backgroundColor = styleEqual(c("ERROR", "WARNING", "INFO"), c('#FF6347', '#FFFFFF', '#ADD8E6'))
)
} else {
data.frame(message = "Congratulations! No integrity issues were found!")
}
})
output$analytics_checks <- renderUI({
vr <- validation_results()
messages <- NULL
if (is.null(vr)) {
return(NULL)
}
if (inherits(vr, "error")) {
return(paste0("ERROR! ", vr$message))
} else {
messages <- vr %>%
purrr::pluck(., "info") %>%
purrr::pluck(., "analytics_warning_msg") %>%
purrr::map(., function(x) fansi::to_html(fansi::html_esc(x))) %>%
purrr::map(., function(x) paste("<li><p>", x, "</p></li>")) %>%
paste(., collapse = "") %>%
stringr::str_replace_all("\n", "<p/>") %>%
stringr::str_replace_all("\t", " ")
if (!is.null(messages)) {
shiny::HTML(paste("<ul>", messages, "</ul>"))
} else {
tags$li("No Issues with Analytics Checks: Congratulations!")
}
}
})
output$downloadOutputs <- downloadHandler(
filename = function() {
d <- validation_results()
sane_name <- d$info$sane_name
prefix <- switch(input$downloadType,
"messages" = "Messages",
"cso_flatpack" = "CSO_Flatpack",
"flatpack" = "Flatpack",
"vr_rules" = "Validation_report",
"datapack" = "PSNUxIM",
"update_psnuxim_targets" = "PSNUxIM",
"missing_psnuxim_targets" = "PSNUxIM_Missing_Targets",
"append_missing_psnuxim_targets" = "PSNUxIM",
"comparison" = "Comparison",
"comparison_plus" = "Comparison_plus",
"memo" = paste("COP", substring(d$info$cop_year,first = 3,last = 4), "_Memo"),
"Other"
)
date <- date <- format(Sys.time(), "%Y%m%d_%H%M%S")
suffix <- if (input$downloadType %in% c("memo")) {
".docx"
} else {
".xlsx"
}
paste0(prefix, "_", sane_name, "_", date, suffix)
},
content = function(file) {
d <- validation_results()
if (input$downloadType == "messages") {
sendEventToS3(d, "MESSAGE_DOWNLOAD")
messages_df <- data.frame( Tool = d$info$messages$tool,
Severity = d$info$messages$level,
Message = d$info$messages$message) %>%
dplyr::arrange(`Severity`,`Tool`)
openxlsx::write.xlsx(messages_df, file = file)
}
if (input$downloadType == "cso_flatpack") {
sendEventToS3(d, "CSO_FLATPACK_DOWNLOAD")
wb <- downloadCSOFlatPack(d)
openxlsx::saveWorkbook(wb, file = file, overwrite = TRUE)
}
if (input$downloadType == "flatpack") {
sendEventToS3(d, "FLATPACK_DOWNLOAD")
waiter_show(html = waiting_screen_flatpack, color = "rgba(128, 128, 128, .8)")
datapack_name <- d$info$datapack_name
flog.info(
paste0("Flatpack requested for ", datapack_name),
name = "datapack"
)
wb <- downloadFlatPack(d)
openxlsx::saveWorkbook(wb, file = file, overwrite = TRUE)
waiter_hide()
}
if (input$downloadType == "vr_rules") {
#The exact structure of the tests is unknown, but filter out anything
#which is not a data frame.
is_data_frame <- unlist(lapply(lapply(d$tests,class) , function(x) "data.frame" %in% x))
d$tests <- d$tests[is_data_frame]
sheets_with_data <- d$tests[lapply(d$tests, NROW) > 0 ] %>%
#Limit the number of rows to the maximum in Excel
purrr::map(.,~ dplyr::slice(.x,1:1048575)) %>%
#Collapses nested lists to a string which will fit inside of excel
purrr::map(., ~ .x %>% dplyr::mutate_if(is.list,function(x) paste(as.character(x[[1]]),sep="",collapse=","))) %>%
#Convert everything to characters and apply Excel limits
purrr::map(., ~ .x %>% dplyr::mutate_if(is.character,function(x) substring(as.character(x),0,36766)))
if (length(sheets_with_data) > 0) {
sendEventToS3(d, "VR_RULES_DOWNLOAD")
openxlsx::write.xlsx(sheets_with_data, file = file)
} else {
showModal(modalDialog(
title = "Perfect score!",
"No validation issues, so nothing to download!"
))
}
}
if (input$downloadType == "datapack") {
flog.info(
paste0("Regeneration of Datapack requested for ", d$info$datapack_name)
,
name = "datapack")
waiter_show(html = waiting_screen_datapack, color = "rgba(128, 128, 128, .8)")
d <- downloadDataPack(d,
d2_session = user_input$d2_session,
append = FALSE,
use_template = TRUE
)
openxlsx::saveWorkbook(wb = d$tool$wb, file = file, overwrite = TRUE)
sendEventToS3(d, "DATAPACK_DOWNLOAD")
flog.info(
paste0("Datapack reloaded for ", d$info$datapack_name),
name = "datapack")
waiter_hide()
}
if (input$downloadType == "update_psnuxim_targets") {
flog.info(
paste0("Updating PSNUxIM target values from Main Tabs... ", d$info$datapack_name)
,
name = "datapack")
waiter_show(html = waiting_screen_datapack, color = "rgba(128, 128, 128, .8)")
d <- datapackr::updatePSNUxIMTargetValues(d)
openxlsx::saveWorkbook(wb = d$tool$wb, file = file, overwrite = TRUE)
sendEventToS3(d, "UPDATED_TARGETS_DOWNLOAD")
flog.info(
paste0("PSNUxIM targets updated for ", d$info$datapack_name),
name = "datapack")
waiter_hide()
}
if (input$downloadType == "missing_psnuxim_targets") {
flog.info(
paste0("Generation of missing PSNUxIM targets requested for ", d$info$datapack_name)
,
name = "datapack")
waiter_show(html = waiting_screen_datapack, color = "rgba(128, 128, 128, .8)")
d <- downloadDataPack(d,
d2_session = user_input$d2_session,
append = TRUE,
use_template = TRUE
)
openxlsx::saveWorkbook(wb = d$tool$wb, file = file, overwrite = TRUE)
sendEventToS3(d, "MISSING_PSNUXIM_DOWNLOAD")
flog.info(
paste0("Missing PSNUxIM targets generated reloaded for ", d$info$datapack_name),
name = "datapack")
waiter_hide()
}
if (input$downloadType == "append_missing_psnuxim_targets") {
flog.info(
paste0("Appending PSNUxIM targets requested for ", d$info$datapack_name)
,
name = "datapack")
waiter_show(html = waiting_screen_datapack, color = "rgba(128, 128, 128, .8)")
d <- downloadDataPack(d,
d2_session = user_input$d2_session,
append = TRUE,
use_template = FALSE
)
openxlsx::saveWorkbook(wb = d$tool$wb, file = file, overwrite = TRUE)
sendEventToS3(d, "APPEND_PSNUXIM_DOWNLOAD")
flog.info(
paste0("Missing PSNUxIM targets generated reloaded for ", d$info$datapack_name),
name = "datapack")
waiter_hide()
}
if (input$downloadType %in% c("comparison", "comparison_plus")) {
# sendEventToS3(d, "COMPARISON_DOWNLOAD") future upgrade
waiter_show(html = waiting_screen_comparison, color = "rgba(128, 128, 128, .8)")
flog.info(
paste0(ifelse(input$downloadType == "comparison_plus", "Comparison Plus", "Comparison"),
" requested for ",
d$info$datapack_name)
,
name = "datapack"
)
wb <- downloadComparison(d,
plus = ifelse(input$downloadType == "comparison_plus", TRUE, FALSE))
openxlsx2::wb_save(wb, file = file)
waiter_hide()
}
if (input$downloadType == "memo") {
sendEventToS3(d, "MEMO_DOWNLOAD")
doc <- datapackr::generateApprovalMemo(d,
memo_type = "datapack",
draft_memo = TRUE )
print(doc, target = file)
}
}
)
validate <- function() {
shinyjs::disable("downloadType")
shinyjs::disable("downloadOutputs")
shinyjs::disable("send_paw")
if (!ready$ok) {
shinyjs::disable("validate")
return(NULL)
}
input_files <- file_input()
inFile <- input_files$file1
inFile2 <- input_files$file2
messages <- ""
if (is.null(inFile) && is.null(inFile2)) {
return(NULL)
}
messages <- list()
withProgress(message = "Validating file", value = 0, {
shinyjs::disable("file1")
shinyjs::disable("validate")
incProgress(0.1, detail = ("Unpacking your DataPack"))