-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathautoReport.R
954 lines (887 loc) · 31.4 KB
/
autoReport.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
## Handle automated reports in config
#' Create and add report to config
#'
#' Adds an entry to the system configuration of reports to run at given
#' intervals. After generating the configuration from the new entry
#' the function load the current system configuration, adds the new
#' entry and saves the updated system configuration.
#'
#' @param synopsis String with description of the report and to be used in
#' subject field of email distributed reports
#' @param package String with package name also corresponding to registry
#' @param type Character string defining type of auto report. Currently, one of
#' 'subscription' (default) or 'dispatchment'
#' @param fun String providing name of function to be called for generating
#' report
#' @param paramNames String vector where each element corresponds to the input
#' parameter to be used in the above function
#' @param paramValues String vector with corresponding values to paramNames
#' @param owner String providing the owner of the report. Usually a user name
#' @param ownerName String providing full name of owner. Defaults to an empty
#' string to maintain backwards compatibility
#' @param email String with email address to recipient of email containing the
#' report
#' @param organization String identifying the organization the owner belongs to
#' @param runDayOfYear Integer vector with day numbers of the year when the
#' report is to be run
#' @param startDate Date-class date when report will be run first time. Default
#' value is set to \code{Sys.Date() + 1} \emph{i.e.} tomorrow.
#' @param terminateDate Date-class date after which report is no longer run.
#' Default value set to \code{NULL} in which case the function will provide an
#' expiry date adding 3 years to the current date if in a PRODUCTION context
#' and 1 month if not
#' @param interval String defining a time interval as defined in
#' \code{\link[base:seq.POSIXt]{seq.POSIXt}}. Default value is an empty string
#' @param intervalName String providing a human understandable representation of
#' \code{interval}. Default value is an empty string
#' @param dryRun Logical defining if global auto report config actually is to
#' be updated. If set to TRUE the actual config (all of it) will be returned by
#' the function. FALSE by default
#' @param target List of autoreports in file or database
#'
#' @return Nothing unless dryRun is set TRUE in which case a list of all config
#' will be returned
#' @seealso \code{\link{deleteAutoReport}}
#' @export
createAutoReport <- function(synopsis, package, type = "subscription", fun,
paramNames, paramValues, owner, ownerName = "",
email, organization, runDayOfYear,
startDate = as.character(Sys.Date()),
terminateDate = NULL, interval = "",
intervalName = "", dryRun = FALSE,
target = "file") {
# When NULL, set expiry date based on context
if (is.null(terminateDate)) {
context <- Sys.getenv("R_RAP_INSTANCE")
terminateDate <- as.POSIXlt(Sys.Date())
if (context %in% c("PRODUCTION", "PRODUCTIONC")) {
terminateDate$year <- terminateDate$year + 3
} else {
terminateDate$mon <- terminateDate$mon + 1
}
terminateDate <- as.Date(terminateDate)
}
# make unique id by (hashing) combination of owner and timestamp
ts <- as.character(as.integer(as.POSIXct(Sys.time())))
autoRepId <- digest::digest(paste0(owner, ts))
l <- list()
l$synopsis <- synopsis
l$package <- package
l$type <- type
l$fun <- fun
l$params <- as.list(stats::setNames(paramValues, paramNames))
l$owner <- owner
l$ownerName <- ownerName
l$email <- email
l$organization <- as.character(organization)
l$startDate <- as.character(startDate)
l$terminateDate <- as.character(terminateDate)
l$interval <- interval
l$intervalName <- intervalName
l$runDayOfYear <- runDayOfYear
if (target == "db") {
rd <- list(l)
} else {
# Read current autoreport data and add new entry
rd <- readAutoReportData()
rd[[eval(autoRepId)]] <- l
}
if (dryRun) {
rd
} else {
writeAutoReportData(config = rd, target = target)
}
}
#' Delete existing report from config/db
#'
#' @param autoReportId String providing the auto report unique id
#' @param target List of autoreports in file or database
#'
#' @seealso \code{\link{createAutoReport}}
#' @export
deleteAutoReport <- function(autoReportId, target = "file") {
if (target == "file") {
rd <- readAutoReportData()
# just stop with an error if report does not exist
stopifnot(!is.null(rd[[autoReportId]]))
ind <- names(rd) == autoReportId
rd <- rd[!ind]
writeAutoReportData(config = rd)
} else if (target == "db") {
query <- paste0('DELETE FROM autoreport WHERE id = "', autoReportId, '";')
dbConnect <- rapOpenDbConnection("autoreport")
DBI::dbExecute(dbConnect$con, query)
rapCloseDbConnection(dbConnect$con)
dbConnect <- NULL
}
}
#' Read automated report metadata
#'
#' @param fileName String defining name of the yaml configuration file. Default
#' 'autoReport.yml'
#' @param packageName String defining the package in which the above
#' configuration file resides. A configuration file within an R-package is
#' only used in case the environmental variable 'R_RAP_CONFIG_PATH' is not
#' defined (empty)
#' @param target List of autoreports in file or database
#'
#' @return a list of yaml data
#' @export
#'
#' @examples
#' readAutoReportData()
readAutoReportData <- function(fileName = "autoReport.yml",
packageName = "rapbase",
target = "file") {
if (target == "db") {
config <- getConfig(fileName = "rapbaseConfig.yml")
query <- paste0("SELECT * FROM ", config$r$autoReport$key, ";")
res <- rapbase::loadRegData(config$r$autoReport$key, query)
return(res)
} else if (target == "file") {
path <- Sys.getenv("R_RAP_CONFIG_PATH")
if (path == "") {
stopifnot(file.exists(system.file(fileName, package = packageName)))
config_file <- system.file(fileName, package = packageName)
} else {
if (!file.exists(file.path(path, fileName))) {
warning(paste(
"No configuration file found in", path,
". A new file will be made from the package default"
))
file.copy(system.file(fileName, package = packageName), path)
}
config_file <- file.path(path, fileName)
}
conf <- yaml::yaml.load_file(config_file)
}
upgradeAutoReportData(conf)
# conf
}
#' Upgrade auto reports
#'
#' Upgrade auto report config as new features emerge. Currently, the type
#' definition is added and set to 'subscription' that historically has been
#' the only type used
#'
#' @param config List of auto report configuration
#'
#' @return List of (upgraded) auto report configuration
#' @export
upgradeAutoReportData <- function(config) {
upgradeType <- FALSE
upgradeOwnerName <- FALSE
upgradeParams <- FALSE
upgradeStartDate <- FALSE
for (i in seq_len(length(config))) {
rep <- config[[i]]
if (!"type" %in% names(rep)) {
upgradeType <- TRUE
config[[i]]$type <- "subscription"
}
if (!"ownerName" %in% names(rep)) {
upgradeOwnerName <- TRUE
config[[i]]$ownerName <- ""
}
if ("params" %in% names(rep) && inherits(rep$params[[1]], "list")) {
upgradeParams <- TRUE
paramName <- vector()
paramValue <- vector()
for (j in seq_len(length(rep$params))) {
paramName[j] <- names(rep$params[[j]])
paramValue[j] <- rep$params[[j]]
}
config[[i]]$params <- as.list(stats::setNames(paramValue, paramName))
}
if (!"startDate" %in% names(rep)) {
upgradeStartDate <- TRUE
config[[i]]$startDate <- "1900-01-01"
}
}
if (upgradeType) {
message(paste(
"Auto report data were upgraded:",
"auto reports with no type defined now set to",
"'subscription'."
))
}
if (upgradeOwnerName) {
message(paste(
"Auto report data were upgraded:",
"auto reports with no owner name defined now set to",
"an empty string."
))
}
if (upgradeParams) {
message(paste(
"Auto report data were upgraded:",
"function params list un-nested. Please check that autor reports for",
"registries are still working as expected."
))
}
if (upgradeStartDate) {
message(paste(
"Auto report data were upgraded:",
"auto reports with no start date defined now set to 1900-01-01."
))
}
config
}
#' Write automated report metadata
#'
#' @inheritParams readAutoReportData
#' @param config a list of yaml configuration
#' @param target List of autoreports in file or database
#'
#' @return NULL
#' @export
#'
#' @examples
#' \donttest{
#' # Example depend on environment variable R_RAP_CONFIG_PATH being set
#' config <- readAutoReportData()
#' try(writeAutoReportData(config = config))
#' }
#'
writeAutoReportData <- function(fileName = "autoReport.yml", config,
packageName = "rapbase",
target = "file") {
if (target == "db") {
rc <- getConfig(fileName = "rapbaseConfig.yml")
key <- rc$r$autoReport$key
# Create empty data frame
dataframe <- stats::setNames(
data.frame(
matrix(ncol = 15, nrow = 0)
),
c("id", names(config[[1]]))
) |>
dplyr::mutate(dplyr::across(dplyr::everything(), as.character))
for (element in config) {
for (email in element$email) {
dataframe <- dataframe |> dplyr::add_row(
id = digest::digest(
paste0(
email,
as.character(as.integer(as.POSIXct(Sys.time())))
)
),
synopsis = element$synopsis,
package = element$package,
fun = element$fun,
params = paste0(
"{",
paste0(
"\"",
names(element$params),
"\": \"",
element$params,
"\"",
collapse = ", "
), "}"
),
owner = element$owner,
email = email,
organization = element$organization,
terminateDate = element$terminateDate,
interval = element$interval,
intervalName = element$intervalName,
type = element$type,
ownerName = element$ownerName,
startDate = element$startDate,
runDayOfYear = toString(element$runDayOfYear)
)
}
}
con <- rapOpenDbConnection(key)$con
DBI::dbAppendTable(con, key, dataframe, row.names = NULL)
rapCloseDbConnection(con)
} else if (target == "file") {
path <- Sys.getenv("R_RAP_CONFIG_PATH")
if (path == "") {
# cannot proceed if there is nowhere to store config
stop(paste(
"There is nowhere to store config data.",
"The environment variable R_RAP_CONFIG_PATH must be defined",
"providing av path to a directory where configuration can",
"be written. Stopping"
))
} else {
oriFile <- file.path(path, fileName)
# in case we screw-up, make a backup
tmpTag <- as.character(as.integer(as.POSIXct(Sys.time())))
nameParts <- strsplit(fileName, "[.]")[[1]]
bckFileName <- paste0(nameParts[1], tmpTag, ".", nameParts[-1])
bckFilePath <- file.path(path, "autoReportBackup")
if (!dir.exists(bckFilePath)) {
dir.create(bckFilePath)
}
file.copy(
from = oriFile, to = file.path(bckFilePath, bckFileName),
overwrite = TRUE
)
# to maintain some order, remove files older than 30 days
files <- file.info(list.files(bckFilePath, full.names = TRUE))
rmFiles <- rownames(
files[difftime(
Sys.time(),
files[, "mtime"],
units = "days"
) > 30,
]
)
file.remove(rmFiles)
con <- file(oriFile, "w")
}
yaml::write_yaml(config, con)
close(con)
} else {
stop(paste0(
"Target ", target, " is not supported. Auto report data not written!"
))
}
}
#' Filter auto report data
#'
#' Generic function to filter various entities from auto report data
#'
#' @param data List (nested) specifying auto reports to be filtered. May be
#' obtained by \code{rapbase::getConfig(fileName = "autoReport.yml")}
#' @param by Character string defining the filtering entity and must be one of
#' \code{c("package", "type", "owner", "organization")}. The term 'package'
#' represents the registry name
#' @param pass Character vector defining the values of the filtering entity that
#' will allow reports to pass through the filter
#' @param target List of autoreports in file or database
#'
#' @return List of auto reports matching the filtering criteria
#' @export
#'
#' @examples
#' ar <- list(ar1 = list(type = "A"), ar2 = list(type = "B"))
#' filterAutoRep(ar, "type", "B") # ar2
#'
filterAutoRep <- function(data, by, pass, target = "file") {
stopifnot(by %in% c("package", "type", "owner", "organization"))
if (length(data) == 0) {
list()
} else {
if (target == "db") {
return(dplyr::filter(data, .data[[by]] %in% pass))
} else {
ind <- integer()
for (i in seq_len(length(data))) {
if (data[[i]][[by]] %in% pass) {
ind <- c(ind, i)
}
}
c(data[ind])
}
}
}
#' Provide vector of registries (\emph{i.e.} their R packages) in config
#'
#' @param config list of configuration for automated reports
#'
#' @return character vector of registry (package) names
#' @export
getRegs <- function(config) {
regs <- vector(mode = "character")
for (i in seq_len(length(config))) {
reg <- config[[i]]$package
if (!(reg %in% regs)) {
regs <- c(regs, reg)
}
}
regs
}
## Run automated reports
#' Simple test of automated report
#'
#' Simple test of automated reporting from definitions provided in a yaml
#' config file
#'
#' @param aNum a number
#' @param aChar a character
#' @param anExp an expression
#' @param bulletin Integer defining if report is of type bulletin (1) or not
#' (0). Set to 0 by default
#'
#' @return A simple message listing the contents of the arguments
#' @export
#'
#' @examples
#' .testAutoReport()
.testAutoReport <- function(aNum = 1, aChar = "a", anExp = Sys.Date(),
bulletin = 0) {
if (bulletin == 0) {
bulletin <- FALSE
} else {
bulletin <- TRUE
}
msg <- paste(
"This is a simple test of automated reports.",
"Arguments provided:\n",
"aNum:", as.character(aNum), ",\n",
"aChar:", aChar, ",\n",
"anExp:", as.character(anExp), "\n"
)
fileName <- paste0(tempfile(), ".txt")
con <- file(fileName, "w")
cat(msg, file = fileName)
close(con)
if (bulletin) {
msg
} else {
fileName
}
}
#' Provide explicit reference to function for do.call
#'
#' @param x string with explicit reference, i.e. 'package::function'
#'
#' @return value of the exported 'function' in 'package'
#' @export
.getFun <- function(x) {
if (length(grep("::", x)) > 0) {
parts <- strsplit(x, "::")[[1]]
getExportedValue(parts[1], parts[2])
} else { # nocov start
x
} # nocov end
}
#' Run reports as defined in yaml config and ship content by email
#'
#' Usually to be called by a scheduler, e.g. cron. If the provided day of
#' year matches those of the config the report is run as otherwise specified in
#' config. Functions called upon are expected to return a character string
#' providing a path to a file that can be attached to an email or, in case of a
#' bulletin, the email body itself. For bulletins, files cannot be attached.
#' The email itself is prepared and sent to recipients defined in the config
#'
#' @param dayNumber Integer day of year where January 1st is 1. Defaults to
#' current day, \emph{i.e.} \code{as.POSIXlt(Sys.Date())$yday + 1} (POSIXlt
#' yday is base 0)
#' @param type Character vector defining the type of reports to be processed.
#' May contain one or more of
#' \code{c("subscription", "dispatchment", "bulletin")}. Defaults value set to
#' \code{c("subscription", "dispatchment")}.
#' @param target List of autoreports in file or database
#' @param dryRun Logical defining if emails are to be sent. If TRUE a message
#' with reference to the payload file is given but no emails will actually be
#' sent. Default is FALSE
#' @param dato Date-class date when report will be run first time. Default value
#' is set to \code{Sys.Date()}
#'
#' @return Emails with corresponding file attachment. If dryRun == TRUE just a
#' message
#' @export
#'
#' @examples
#' \donttest{
#' # Example depend on environment variable R_RAP_CONFIG_PATH being set
#' runAutoReport()
#' }
#'
runAutoReport <- function(dayNumber = as.POSIXlt(Sys.Date())$yday + 1,
dato = Sys.Date(),
type = c("subscription", "dispatchment"),
target = "file", dryRun = FALSE) {
# get report candidates
reps <- readAutoReportData(target = target) %>%
filterAutoRep(by = "type", pass = type, target = target)
# standard text for email body
stdTxt <- readr::read_file(
system.file(
"autoReportStandardEmailText.txt",
package = "rapbase"
)
)
# get sender from common config
conf <- rapbase::getConfig("rapbaseConfig.yml")
for (i in seq_len(ifelse(target == "db", dim(reps)[1], length(reps)))) {
tryCatch(
{
if (target == "db") {
rep <- reps[i, ]
params <- jsonlite::fromJSON(rep$params)
} else {
rep <- reps[[i]]
params <- rep$params
}
if ((
target == "file"
&& dayNumber %in% rep$runDayOfYear
&& as.Date(rep$terminateDate) > Sys.Date()
&& as.Date(rep$startDate) <= Sys.Date()
) || (
target == "db"
&& as.Date(rep$startDate) <= dato
&& as.Date(rep$terminateDate) > dato
&& dato %in% timeplyr::time_seq(
as.Date(rep$startDate),
dato,
time_by = rep$interval
) # 'days', 'weeks', 'months', 'years',
)) {
# get explicit referenced function and call it
f <- .getFun(paste0(rep$package, "::", rep$fun))
content <- do.call(what = f, args = params)
if (rep$type == "bulletin") {
text <- content
attFile <- NULL
} else {
text <- stdTxt
attFile <- content
}
if (dryRun) {
message(paste("No emails sent. Content is:", content))
} else {
autLogger(
user = rep$owner,
name = rep$ownerName,
registryName = rep$package,
reshId = rep$organization,
type = rep$type,
pkg = rep$package,
fun = rep$fun,
param = rep$params,
msg = paste(
"recipients:",
paste(
rep$email,
collapse = ", "
)
)
)
sendEmail(
conf = conf, to = rep$email, subject = rep$synopsis,
text = text, attFile = attFile
)
}
}
},
error = function(e) {
message(paste(
"Report could not be processed (moving on to the next):",
e
))
}
)
}
}
#' Run bulletin auto reports
#'
#' This is a wrapper for \code{runAutoReport()} to issue bulletins. Purpose is
#' to ease simplify fire-in-the-hole at Rapporteket
#'
#' @return Whatever \code{runAutoReport()} might provide
#' @export
runBulletin <- function() {
runAutoReport(type = c("bulletin"))
}
## Miscellaneous functions
#' Make a sequence of day numbers from av given date and interval
#'
#' This function provides an even sequence of day numbers spanning 365/366
#' days from the start date and interval provided. Mainly to be used in
#' setting up automated reports at Rapporteket
#'
#' @param startDay Start date of sequence. May be provided as a string,
#' \emph{e.g.} \"2019-03-17\" or as class \"Date\". Defaults to today
#' @param interval String representing a valid seq.POSIXt interval such as
#' "DSTday", "week", "month", "quarter" or "year")
#'
#' @return Integer vector of day numbers
#' @export
#'
#' @examples
#' makeRunDayOfYearSequence(interval = "month")
makeRunDayOfYearSequence <- function(startDay = Sys.Date(), interval) {
# set end to a year from start
start <- as.POSIXlt(startDay)
end <- start
end$year <- end$year + 1
s <- seq(from = start, to = end, by = interval)
# skip redundant end value
if (length(s) > 1) {
s <- s[seq_len(length(s)) - 1]
}
unique(as.integer(format(s, "%j")))
}
#' Find next run date for automated reports
#'
#' Find the next date that an automated report is supposed to be run. Likely,
#' this function will only be relevant for shiny apps when this date is to
#' be printed
#'
#' @param runDayOfYear Numeric vector providing year-day numbers
#' @param baseDayNum Numeric defining base year-day. Default is today
#' @param startDate Character string of format "YYYY-MM-DD" defining the date of
#' the very first run. If set to NULL (default) or a none future date (compared
#' to the date represented by \code{baseDayNum} for the current year) it will be
#' disregarded.
#' @param returnFormat String providing return format as described in
#' \code{\link[base]{strptime}} in the current locale. Defaults to
#' "\%A \%d. \%B \%Y" that will provide something like
#' 'Mandag 20. januar 2019' in a Norwegian locale
#' @return String date for printing
#' @examples
#' # Will return Jan 30 in the current year and locale with default formatting
#' findNextRunDate(c(10, 20, 30), 20)
#' @export
findNextRunDate <- function(runDayOfYear,
baseDayNum = as.POSIXlt(Sys.Date())$yday + 1,
startDate = NULL,
returnFormat = "%A %e. %B %Y") {
year <- as.POSIXlt(Sys.Date())$year + 1900
if (!is.null(startDate)) {
if (as.Date(startDate) > as.Date(strptime(
paste(year, baseDayNum),
"%Y %j"
))) {
# since we pull the NEXT run day set new base day on day BEFORE star date
baseDayNum <- as.POSIXlt(startDate)$yday
}
}
# special case if out of max range and only one run day defined (yearly)
if (baseDayNum >= max(runDayOfYear) || length(runDayOfYear) == 1) {
# next run will be first run in day num vector
nextDayNum <- min(runDayOfYear)
} else {
# find year transition, if any
nDay <- length(runDayOfYear)
deltaDay <- runDayOfYear[2:nDay] - runDayOfYear[1:(nDay - 1)]
trans <- deltaDay < 0
if (any(trans)) {
indTrans <- match(TRUE, trans)
# vector head
dHead <- runDayOfYear[1:indTrans]
# vector tail
dTail <- runDayOfYear[(indTrans + 1):nDay]
if (baseDayNum >= max(dTail)) {
## next run day to be found in vector head
runDayOfYearSubset <- dHead
} else {
## next run day to be found in vector tail
runDayOfYearSubset <- dTail
}
} else {
runDayOfYearSubset <- runDayOfYear
}
nextDayNum <- min(runDayOfYearSubset[runDayOfYearSubset > baseDayNum])
}
# if current day num larger than nextDayNum report will be run next year
if (as.numeric(format(Sys.Date(), "%j")) > nextDayNum) {
year <- year + 1
}
format(strptime(paste(year, nextDayNum), "%Y %j"), format = returnFormat)
}
# nolint start
#' Make table of automated reports
#'
#' Make a table to be rendered in a shiny app providing automated reports
#' from a given user or registry as obtained from the shiny session
#' object provided or environmental variables when run inside an app container.
#'
#' Each table record (line) represents a uniquely defined automated report.
#' For each line two shiny action buttons are provided to allow
#' for editing and deleting of each entry. For applications
#' implementing this table observing events on these action buttons may be used
#' to allow users to manage automated reports by GUI. The
#' action buttons for editing and deleting are provided with the static input
#' ids \emph{edit_button} and \emph{del_button} and upon clicking the
#' \emph{button} part of their ids will change to the unique id of the
#' report. Hence, a GUI call for editing a report can be caught by
#' \code{shiny::observeEvent("edit_button")} and within this event the
#' report id is obtained by collecting the string after the double underscore,
#' \emph{e.g.} \code{strsplit(input$edit_button, "__")[[1]][2]}.
#'
#' Optionally, report id may be provided as the last column in the table to
#' allow further development for registry specific purposes. Regardless, this
#' column should normally be hidden in the GUI.
#'
#' Take a look at the
#' \href{https://github.com/Rapporteket/rapRegTemplate/blob/main/inst/shinyApps/app1/server.R}{example shiny server function in rapRegTemplate}
#' on how this function may be implemented.
#'
#' @param session A shiny session object
#' @param namespace String naming namespace. Defaults to \code{character()} in
#' which case no namespace will be created. When this function is used by
#' shiny modules namespace must be provided.
#' @param user Character string providing the username. Introduced as a new
#' argument when running apps inside containers. Default value is set to
#' \code{rapbase::getUserName(session)} to allow backward compatibility.
#' @param group Character string defining the registry, normally corresponding
#' to the R package name and the value stemming from the SHINYPROXY_GROUPS
#' environment variable. Introduced as a new argument when running apps inside
#' containers. Default value is set to \code{rapbase::getUserGroups(session)}
#' to allow backward compatibility.
#' @param orgId Character string or integer defining the organization (id) for
#' \code{user}. Default value is set to \code{rapbase::getUserReshId(session)}
#' to allow backward compatibility.
#' @param type Character string defining the type of auto reports to tabulate.
#' Must be one of \code{"subscription"}, \code{"dispatchment"} or
#' \code{"bulletin"}. Default value set to \code{"subscription"}.
#' @param mapOrgId Data frame containing the two columns 'name' and 'id'
#' corresponding to unique name and id of organizations. Default is NULL in
#' which case the ids provided in auto report data will be used. In case
#' mapOrgId is not NULL but no id match is found the id found in the auto
#' report data will also be used
#' @param includeReportId Logical if the unique report id should be added as
#' the last column in the table. FALSE by default.
#' @param target autoreport-list in file or database
#'
#' @return Matrix providing a table to be rendered in a shiny app
#' @importFrom dplyr "%>%"
#' @export
# nolint end
makeAutoReportTab <- function(session,
namespace = character(),
user = rapbase::getUserName(session),
group = rapbase::getUserGroups(session),
orgId = rapbase::getUserReshId(session),
type = "subscription",
mapOrgId = NULL,
includeReportId = FALSE,
target = "file") {
stopifnot(type %in% c("subscription", "dispatchment", "bulletin"))
autoRep <- readAutoReportData(target = target) %>%
filterAutoRep(by = "package", pass = group, target = target) %>%
filterAutoRep(by = "type", pass = type, target = target)
if (type == "subscription") {
autoRep <- autoRep %>%
filterAutoRep(by = "owner", pass = user, target = target) %>%
filterAutoRep(by = "organization", pass = orgId, target = target)
}
dateFormat <- "%A %e. %B %Y"
if (target == "db") {
if (length(autoRep$id) == 0) {
return(as.matrix(autoRep))
}
l <- list()
for (i in seq_len(nrow(autoRep))) {
runDayOfYear <- as.vector(
as.integer(strsplit(autoRep[i, ]$runDayOfYear, ",")[[1]])
)
nextDate <- findNextRunDate(
runDayOfYear = runDayOfYear,
startDate = autoRep[i, ]$startDate,
returnFormat = dateFormat
)
if (as.Date(nextDate, format = dateFormat) > autoRep[i, ]$terminateDate) {
nextDate <- "Utl\u00F8pt"
}
dataSource <- autoRep[i, ]$organization
if (!is.null(mapOrgId)) {
if (dataSource %in% mapOrgId$id) {
dataSource <- mapOrgId$name[mapOrgId$id == dataSource]
}
}
r <- list(
"Rapport" = autoRep[i, ]$synopsis,
"Datakilde" = dataSource,
"Mottaker" = autoRep[i, ]$email,
"Periode" = autoRep[i, ]$intervalName,
"Slutt" = strftime(
as.Date(
autoRep[i, ]$terminateDate
),
format = "%b %Y"
),
"Neste" = nextDate,
"Endre" = as.character(
shiny::actionButton(
inputId = shiny::NS(namespace, paste0("edit__", autoRep[i, ]$id)),
label = "",
icon = shiny::icon("edit"),
onclick = sprintf(
"Shiny.onInputChange('%s', this.id)",
shiny::NS(namespace, "edit_button")
)
)
),
"Slett" = as.character(
shiny::actionButton(
inputId = shiny::NS(namespace, paste0("del__", autoRep[i, ]$id)),
label = "",
icon = shiny::icon("trash"),
onclick = sprintf(
"Shiny.onInputChange('%s', this.id)",
shiny::NS(namespace, "del_button")
)
)
)
)
if (includeReportId) {
r <- c(r, list("id" = autoRep[i, ]$id))
}
if (!type %in% c("subscription")) {
r <- c(list(Ansvarlig = autoRep[i, ]$ownerName), r)
}
l <- rbind(l, r)
}
return(as.matrix(l))
} else {
l <- list()
for (n in names(autoRep)) {
nextDate <- findNextRunDate(
runDayOfYear = autoRep[[n]]$runDayOfYear,
startDate = autoRep[[n]]$startDate,
returnFormat = dateFormat
)
if (as.Date(nextDate, format = dateFormat) > autoRep[[n]]$terminateDate) {
nextDate <- "Utl\u00F8pt"
}
dataSource <- autoRep[[n]]$organization
if (!is.null(mapOrgId)) {
if (dataSource %in% mapOrgId$id) {
dataSource <- mapOrgId$name[mapOrgId$id == dataSource]
}
}
r <- list(
"Rapport" = autoRep[[n]]$synopsis,
"Datakilde" = dataSource,
"Mottaker" = paste0(autoRep[[n]]$email, collapse = "<br>"),
"Periode" = autoRep[[n]]$intervalName,
"Slutt" = strftime(
as.Date(
autoRep[[n]]$terminateDate
),
format = "%b %Y"
),
"Neste" = nextDate,
"Endre" = as.character(
shiny::actionButton(
inputId = shiny::NS(namespace, paste0("edit__", n)),
label = "",
icon = shiny::icon("edit"),
onclick = sprintf(
"Shiny.onInputChange('%s', this.id)",
shiny::NS(namespace, "edit_button")
)
)
),
"Slett" = as.character(
shiny::actionButton(
inputId = shiny::NS(namespace, paste0("del__", n)),
label = "",
icon = shiny::icon("trash"),
onclick = sprintf(
"Shiny.onInputChange('%s', this.id)",
shiny::NS(namespace, "del_button")
)
)
)
)
if (includeReportId) {
r <- c(r, list("id" = n))
}
if (!type %in% c("subscription")) {
r <- c(list(Ansvarlig = autoRep[[n]]$ownerName), r)
}
l <- rbind(l, r)
}
return(as.matrix(l))
}
}