Title: | Base Functions and Resources for Rapporteket |
---|---|
Description: | Provide common functions and resources for registry specific R-packages at Rapporteket <https://rapporteket.github.io/rapporteket/articles/short_introduction.html>. This package is relevant for developers of packages/registries at Rapporteket. |
Authors: | Are Edvardsen [aut, cre] , Kevin Otto Thon [aut], Arnfinn Hykkerud Steindal [aut] |
Maintainer: | Arnfinn Hykkerud Steindal <[email protected]> |
License: | GPL-3 |
Version: | 1.24.3 |
Built: | 2024-11-14 10:32:43 UTC |
Source: | https://github.com/rapporteket/rapbase |
Provide explicit reference to function for do.call
.getFun(x)
.getFun(x)
x |
string with explicit reference, i.e. 'package::function' |
value of the exported 'function' in 'package'
Simple test of automated reporting from definitions provided in a yaml config file
.testAutoReport(aNum = 1, aChar = "a", anExp = Sys.Date(), bulletin = 0)
.testAutoReport(aNum = 1, aChar = "a", anExp = Sys.Date(), bulletin = 0)
aNum |
a number |
aChar |
a character |
anExp |
an expression |
bulletin |
Integer defining if report is of type bulletin (1) or not (0). Set to 0 by default |
A simple message listing the contents of the arguments
.testAutoReport()
.testAutoReport()
A dataset containing test entries for the application log.
appLog
appLog
A data frame with 20 rows and 7 variables:
character timestamp
user name
user full name
users group/registry
users role
users organization
log message
These shiny modules may be used to set up auto reporting from registries at Rapporteket.
autoReportUI(id) autoReportOrgInput(id) autoReportOrgServer(id, orgs) autoReportFormatInput(id) autoReportFormatServer(id) autoReportInput(id) autoReportServer( id, registryName, type, org = NULL, paramNames = shiny::reactiveVal(c("")), paramValues = shiny::reactiveVal(c("")), reports = NULL, orgs = NULL, eligible = TRUE, freq = "month" ) autoReportServer2( id, registryName, type, org = NULL, paramNames = shiny::reactiveVal(c("")), paramValues = shiny::reactiveVal(c("")), reports = NULL, orgs = NULL, eligible = TRUE, freq = "month", user ) autoReportApp( registryName = "rapbase", type = "subscription", reports = NULL, paramNames = shiny::reactive(c("")), orgs = NULL ) orgList2df(orgs)
autoReportUI(id) autoReportOrgInput(id) autoReportOrgServer(id, orgs) autoReportFormatInput(id) autoReportFormatServer(id) autoReportInput(id) autoReportServer( id, registryName, type, org = NULL, paramNames = shiny::reactiveVal(c("")), paramValues = shiny::reactiveVal(c("")), reports = NULL, orgs = NULL, eligible = TRUE, freq = "month" ) autoReportServer2( id, registryName, type, org = NULL, paramNames = shiny::reactiveVal(c("")), paramValues = shiny::reactiveVal(c("")), reports = NULL, orgs = NULL, eligible = TRUE, freq = "month", user ) autoReportApp( registryName = "rapbase", type = "subscription", reports = NULL, paramNames = shiny::reactive(c("")), orgs = NULL ) orgList2df(orgs)
id |
Character string providing the shiny module id. |
orgs |
Named list of organizations (names) and ids (values). When set to
|
registryName |
Character string with the registry name key. Must correspond to the registry R package name. |
type |
Character string defining the type of auto reports. Must be one
of |
org |
Shiny reactive or NULL (default) defining the organization (id)
of the data source used for dispatchments and bulletins (in which case it
cannot be set to NULL) and its value will be used to populate the
organization field in auto report data (autoReport.yml) for these
auto report types. On the other hand, since subscriptions are personal
(per user) the only relevant organization id will implicit be that of the
user and in this case any value of |
paramNames |
Shiny reactive value as a vector of parameter names of
which values are to be set interactively at application run time. Each
element of this vector must match exactly those of |
paramValues |
Shiny reactive value as a vector of those parameter values
to be set interactively, i.e. as per user input in the application.
Default value is set to |
reports |
List of a given structure that provides meta data for the reports that are made available as automated reports. See Details for further description. |
eligible |
Logical defining if the module should be allowed to work at full capacity. This might be useful when access to module products should be restricted. Default is TRUE, i.e. no restrictions. |
freq |
Character string defining default frequency set in the auto
report GUI. Must be one of
|
user |
List of shiny reactive values providing user metadata and
privileges corresponding to the return value of
|
The reports argument must be a list where each entry
represents one report and its name will be used in the auto report user
interface for selecting reports, e.g.
reports = list(MagicReport = ...)
will produce the entry "MagicReport"
in the GUI list of reports to select from. The value of each entry must be
another list with the following names and values:
character string describing the report
report function base name (without"()")
character vector naming all arguments of fun
vector with values corresponding to paramNames
These named values will be used to run reports none-interactively on a given schedule and must therefore represent existing and exported functions from the registry R package. For subscriptions the reports list can be used as is, more specifically that the values provided in paramValues can go unchanged. It is likely that parameter values must be set dynamically at runtime in which case paramValues must be a reactive part of the application. See Examples on how function arguments may be used as reactives in an application.
In general, shiny objects. In particular, autoreportOrgServer
returns a list with names "name" and "value" with corresponding reactive
values for the selected organization name and id. This may be used when
parameter values of auto report functions needs to be altered at application
run time. orgList2df
returns a data frame with columns "name" and
"id".
## make a list for report metadata reports <- list( FirstReport = list( synopsis = "First example report", fun = "fun1", paramNames = c("organization", "topic", "outputFormat"), paramValues = c(111111, "work", "html") ), SecondReport = list( synopsis = "Second example report", fun = "fun2", paramNames = c("organization", "topic", "outputFormat"), paramValues = c(111111, "leisure", "pdf") ) ) ## make a list of organization names and numbers orgs <- list( OrgOne = 111111, OrgTwo = 222222 ) ## client user interface function ui <- shiny::fluidPage( shiny::sidebarLayout( shiny::sidebarPanel( autoReportFormatInput("test"), autoReportOrgInput("test"), autoReportInput("test") ), shiny::mainPanel( autoReportUI("test") ) ) ) ## server function server <- function(input, output, session) { org <- autoReportOrgServer("test", orgs) format <- autoReportFormatServer("test") # set reactive parameters overriding those in the reports list paramNames <- shiny::reactive(c("organization", "outputFormat")) paramValues <- shiny::reactive(c(org$value(), format())) autoReportServer( id = "test", registryName = "rapbase", type = "dispatchment", org = org$value, paramNames = paramNames, paramValues = paramValues, reports = reports, orgs = orgs, eligible = TRUE ) } # run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
## make a list for report metadata reports <- list( FirstReport = list( synopsis = "First example report", fun = "fun1", paramNames = c("organization", "topic", "outputFormat"), paramValues = c(111111, "work", "html") ), SecondReport = list( synopsis = "Second example report", fun = "fun2", paramNames = c("organization", "topic", "outputFormat"), paramValues = c(111111, "leisure", "pdf") ) ) ## make a list of organization names and numbers orgs <- list( OrgOne = 111111, OrgTwo = 222222 ) ## client user interface function ui <- shiny::fluidPage( shiny::sidebarLayout( shiny::sidebarPanel( autoReportFormatInput("test"), autoReportOrgInput("test"), autoReportInput("test") ), shiny::mainPanel( autoReportUI("test") ) ) ) ## server function server <- function(input, output, session) { org <- autoReportOrgServer("test", orgs) format <- autoReportFormatServer("test") # set reactive parameters overriding those in the reports list paramNames <- shiny::reactive(c("organization", "outputFormat")) paramValues <- shiny::reactive(c(org$value(), format())) autoReportServer( id = "test", registryName = "rapbase", type = "dispatchment", org = org$value, paramNames = paramNames, paramValues = paramValues, reports = reports, orgs = orgs, eligible = TRUE ) } # run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
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.
createAutoReport( synopsis, package, type = "subscription", fun, paramNames, paramValues, owner, ownerName = "", email, organization, runDayOfYear, startDate = as.character(Sys.Date()), terminateDate = NULL, interval = "", intervalName = "", dryRun = FALSE )
createAutoReport( synopsis, package, type = "subscription", fun, paramNames, paramValues, owner, ownerName = "", email, organization, runDayOfYear, startDate = as.character(Sys.Date()), terminateDate = NULL, interval = "", intervalName = "", dryRun = FALSE )
synopsis |
String with description of the report and to be used in subject field of email distributed reports |
package |
String with package name also corresponding to registry |
type |
Character string defining type of auto report. Currently, one of 'subscription' (default) or 'dispatchment' |
fun |
String providing name of function to be called for generating report |
paramNames |
String vector where each element corresponds to the input parameter to be used in the above function |
paramValues |
String vector with corresponding values to paramNames |
owner |
String providing the owner of the report. Usually a user name |
ownerName |
String providing full name of owner. Defaults to an empty string to maintain backwards compatibility |
email |
String with email address to recipient of email containing the report |
organization |
String identifying the organization the owner belongs to |
runDayOfYear |
Integer vector with day numbers of the year when the report is to be run |
startDate |
Date-class date when report will be run first time. Default
value is set to |
terminateDate |
Date-class date after which report is no longer run.
Default value set to |
interval |
String defining a time interval as defined in
|
intervalName |
String providing a human understandable representation of
|
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 |
Nothing unless dryRun is set TRUE in which case a list of all config will be returned
Delete existing report from config
deleteAutoReport(autoReportId)
deleteAutoReport(autoReportId)
autoReportId |
String providing the auto report unique id |
Functions for registries that wants to implement exporting of registry databases, e.g. for local development purposes. Also includes relevant helper functions
exportUCInput(id) exportUCServer(id, registryName, repoName = registryName, eligible = TRUE) exportUCApp(registryName = "rapbase") selectListPubkey(pubkey) exportDb(registryName, compress = FALSE, session)
exportUCInput(id) exportUCServer(id, registryName, repoName = registryName, eligible = TRUE) exportUCApp(registryName = "rapbase") selectListPubkey(pubkey) exportDb(registryName, compress = FALSE, session)
id |
Character string module ID |
registryName |
Character string registry name key |
repoName |
Character string defining the github repository name of the
registry. Default value is |
eligible |
Logical defining if the module should be allowed to work at full capacity. This might be useful when access to module products should be restricted. Default is TRUE, i.e. no restrictions. |
pubkey |
Character vector with public keys |
compress |
Logical if export data is to be compressed (using gzip). FALSE by default. |
session |
Shiny session object |
Shiny objects, mostly. Helper functions may return other stuff too.
## client user interface function ui <- shiny::fluidPage( shiny::sidebarLayout( shiny::sidebarPanel( exportUCInput("test"), ), shiny::mainPanel( NULL ) ) ) ## server function server <- function(input, output, session) { exportUCServer("test", registryName = "rapbase") } ## run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
## client user interface function ui <- shiny::fluidPage( shiny::sidebarLayout( shiny::sidebarPanel( exportUCInput("test"), ), shiny::mainPanel( NULL ) ) ) ## server function server <- function(input, output, session) { exportUCServer("test", registryName = "rapbase") } ## run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
Shiny modules providing the Export Guide
exportGuideUI(id) exportGuideServer(id, registryName) exportGuideApp()
exportGuideUI(id) exportGuideServer(id, registryName) exportGuideApp()
id |
Character string module ID |
registryName |
Character string registry name key |
Functions ui and server representing the (module) app
ui <- shiny::fluidPage( exportGuideUI("exportGuide") ) server <- function(input, output, session) { exportGuideServer("exportGuide", "test") } if (interactive()) { shiny::shinyApp(ui, server) }
ui <- shiny::fluidPage( exportGuideUI("exportGuide") ) server <- function(input, output, session) { exportGuideServer("exportGuide", "test") } if (interactive()) { shiny::shinyApp(ui, server) }
Generic function to filter various entities from auto report data
filterAutoRep(data, by, pass)
filterAutoRep(data, by, pass)
data |
List (nested) specifying auto reports to be filtered. May be
obtained by |
by |
Character string defining the filtering entity and must be one of
|
pass |
Character vector defining the values of the filtering entity that will allow reports to pass through the filter |
List of auto reports matching the filtering criteria
ar <- list(ar1 = list(type = "A"), ar2 = list(type = "B")) filterAutoRep(ar, "type", "B") # ar2
ar <- list(ar1 = list(type = "A"), ar2 = list(type = "B")) filterAutoRep(ar, "type", "B") # ar2
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
findNextRunDate( runDayOfYear, baseDayNum = as.POSIXlt(Sys.Date())$yday + 1, startDate = NULL, returnFormat = "%A %e. %B %Y" )
findNextRunDate( runDayOfYear, baseDayNum = as.POSIXlt(Sys.Date())$yday + 1, startDate = NULL, returnFormat = "%A %e. %B %Y" )
runDayOfYear |
Numeric vector providing year-day numbers |
baseDayNum |
Numeric defining base year-day. Default is today |
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 |
returnFormat |
String providing return format as described in
|
String date for printing
# Will return Jan 30 in the current year and locale with default formatting findNextRunDate(c(10, 20, 30), 20)
# Will return Jan 30 in the current year and locale with default formatting findNextRunDate(c(10, 20, 30), 20)
This function will normally be executed by a cron daemon. Once started this function will nest through schedule functions defined in a configuration file, e.g. "rapbaseConfig.yml".
fireInTheHole(flipPeriod = FALSE)
fireInTheHole(flipPeriod = FALSE)
flipPeriod |
Logical only used for testing. FALSE by default |
This is a crontab example running fireInTheHole() every night at 01 hours, Monday through Friday and with emails suppressed:
0 1 * * 1-5 Rscript -e 'rapbase::fireInTheHole()' >/dev/null 2>&1
# Depends on the env var R_RAP_CONFIG_PATH being properly set fireInTheHole()
# Depends on the env var R_RAP_CONFIG_PATH being properly set fireInTheHole()
Try to obtain yaml-formatted configuration placed either as given by the environment variable R_RAP_CONFIG_PATH or as provided by the package itself. If none can be found the function exits with an error
getConfig(fileName = "dbConfig.yml", packageName = "rapbase")
getConfig(fileName = "dbConfig.yml", packageName = "rapbase")
fileName |
String providing configuration file base name |
packageName |
String providing the package name |
A list of (yaml) configuration
getConfig()
getConfig()
Collect various data from the GitHub API
getGithub(what, value, .token = NULL)
getGithub(what, value, .token = NULL)
what |
Character string defining the api endpoint. Currently one of
|
value |
Character string specifying what to collect from the given endpoint. For "contributors" this should be the name of the repository, for "members" value should be the team slug and for "keys" this should be a github user name. |
.token |
Character string providing av valid token that will be used if the api call requires authentication. Listing of team members do require a token with the appropriate credentials. |
Character vector with results from the GitHub api request
Get all installed packages that depends on 'rapbase' which itself will not be reported
getRapPackages()
getRapPackages()
Character vector of packages names
## Relevant only in a Rapporteket-like context if (isRapContext()) { getRapPackages() }
## Relevant only in a Rapporteket-like context if (isRapContext()) { getRapPackages() }
Provide vector of registries (i.e. their R packages) in config
getRegs(config)
getRegs(config)
config |
list of configuration for automated reports |
character vector of registry (package) names
To be used for testing purposes
halloRapporteket()
halloRapporteket()
message A test message
Render text on how Rapporteket deals with personal data
howWeDealWithPersonalData(session, callerPkg = NULL)
howWeDealWithPersonalData(session, callerPkg = NULL)
session |
A shiny session object used to personalize the text |
callerPkg |
Character string naming the package that makes a call to this function in case version number of the caller package should be added to the returned (html) info text. Default to NULL in which case no version number for the caller will be added to the info text |
fragment html info text
Test if an installed package is linked to Rapporteket based on dependency to the package 'rapbase'
isPkgRapReg(pkg)
isPkgRapReg(pkg)
pkg |
String providing the package name |
Logical TRUE if pkg depends on 'rapbase', FALSE if not
getRapPackages
on how to list all packages that
depend om 'rapbase'
# returns FALSE, rapbase has no explicit dependency to itself isPkgRapReg("rapbase")
# returns FALSE, rapbase has no explicit dependency to itself isPkgRapReg("rapbase")
Call to this function will return TRUE when run on a system where the
environment variable R_RAP_INSTANCE
is set to either "DEV", "TEST",
"QA" or "PRODUCTION" and FALSE otherwise
isRapContext()
isRapContext()
Logical if system has a defined Rapporteket context
isRapContext()
isRapContext()
Generic to registries, provide reporting data obtained from sql databases Underlying this function is rapbase::RapporteketDbConnection
loadRegData(registryName, query, dbType = "mysql") describeRegistryDb(registryName, tabs = c())
loadRegData(registryName, query, dbType = "mysql") describeRegistryDb(registryName, tabs = c())
registryName |
String Name of the registry as defined in dbConfig.yml |
query |
String SQL query to obtain the data |
dbType |
String Type of db to query, currently "mysql" (default) and "mssql" |
tabs |
Character vector for optional definition of tables to describe. Defaults to an empty vector in which case all tables are used |
data frame containing registry data or a list with table names and corresponding fields with attributes
To be used for logging at application level (i.e. when a shiny session is started) or at report level (i.e. each time a report is run). Logging of single report events should be made from reactive environments within the shiny server function or from within the (report) functions used by the same reactive environments.
appLogger( session, msg = "No message provided", .topcall = sys.call(-1), .topenv = parent.frame() ) repLogger( session, msg = "No message provided", .topcall = sys.call(-1), .topenv = parent.frame() ) autLogger( user, name, registryName, reshId, type, pkg, fun, param, msg = "No message provided", .topenv = parent.frame() )
appLogger( session, msg = "No message provided", .topcall = sys.call(-1), .topenv = parent.frame() ) repLogger( session, msg = "No message provided", .topcall = sys.call(-1), .topenv = parent.frame() ) autLogger( user, name, registryName, reshId, type, pkg, fun, param, msg = "No message provided", .topenv = parent.frame() )
session |
Shiny session object to be used for getting user data.
For testing and development purposes |
msg |
String providing a user defined message to be added to the log record. Default value is 'No message provided'. |
.topcall |
Parent call (if any) calling this function. Used to provide
the function call with arguments. Default value is |
.topenv |
Name of the parent environment calling this function. Used to
provide package name (i.e. register) this function was called from.
Default value is |
user |
String providing owner of an automated report. Its value should correspond to the actual user name as provided in a shiny session at Rapporteket. Only used for subscription reports that are run outside a shiny session. |
name |
String providing full name of the report owner. Only used for automated reports that are run outside a shiny session. |
registryName |
String providing registry name. Only used for automated reports that are run outside a shiny session. |
reshId |
String providing the organization id of the (subscription) report author. Only used for automated reports that are run outside a shiny session. |
type |
Character string defining the type of report. Only used for
automated reports that are run outside a shiny session in which case its
value will replace that of |
pkg |
Character string naming the package of the function that is to be logged. Only used for automated reports that are run outside a shiny session. |
fun |
Character string naming the function that should be logged. Only used for automated reports that are run outside a shiny session. |
param |
List of named function parameter. Only used for automated reports that are run outside a shiny session. |
The below fields will be appended to the log, in the following order:
time
: date-time as event is logged as
format(time, "%Y-%m-%d %H:%M:%S")
user
: username as found in the shiny session object or as
provided by function argument
name
: full name of user as found in the shiny session object
group
: users group membership as provided by the shiny
session object. Normally, this will correspond to the registry the user
belongs to
role
: users role as provided by the shiny session object. Its
value will depend on whatever is delivered by the authorization provider,
but for OpenQReg registries 'LU' (local user) and 'SC' (system
coordinator) are typical values
resh_id
: the organization id of the current user as provided
by the shiny session object, OR, when source of logging is auto reports,
the organization ID of the data source used to make the report
environment
: environment from where the logger function was
called (only provided by repLogger()
)
call
: function (with arguments) from where the logger was
called (only provided by repLogger()
)
message: an optional message defined as argument to the function
The autLogger()
function is a special case to be used for automated
reports. Since such reports are run outside a reactive (shiny) context
shiny session data are not available to the logger. Hence, logging data
must be provided as arguments directly. As of rapbase version 1.12.0 logging
of automated reports are already taken care of. Hence, this function should
not be applied per registry application.
Returns nothing but calls a logging appender
Pseudo code of how appLogger()
may be implemented:
library(shiny) library(raplog) server <- function(input, output, session) { raplog::appLogger(session, msg = "Smerteregisteret: starting shiny app") ... }
Pseudo code on how repLogger()
can be implemented as part of a
function in a reactive (shiny) context. First, this is an example of the
shiny server function with the (reactive) function renderPlot()
calling a function that provides a histogram:
library(shiny) library(raplog) server <- function(input, output, session) { ... output$hist <- renderPlot({ makeHist(data, var = input$var, bins = input$bins, session = session) }) ... }
Then, logging is called within the function makeHist()
:
makeHist <- function(data, var, bins, ...) { if ("session" %in% names(list(...))) { raplog::repLogger(session = list(...)[["session"]], msg = "Providing histogram") } ... }
# Depend on the environment variable R_RAP_CONFIG_PATH being set try(appLogger(list())) # Depend on the environment variable R_RAP_CONFIG_PATH being set try(repLogger(list())) # Depend on the environment variable R_RAP_CONFIG_PATH being set try(autLogger(user = "ttester", registryName = "rapbase", reshId = "999999"))
# Depend on the environment variable R_RAP_CONFIG_PATH being set try(appLogger(list())) # Depend on the environment variable R_RAP_CONFIG_PATH being set try(repLogger(list())) # Depend on the environment variable R_RAP_CONFIG_PATH being set try(autLogger(user = "ttester", registryName = "rapbase", reshId = "999999"))
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.
makeAutoReportTab( session, namespace = character(), user = rapbase::getUserName(session), group = rapbase::getUserGroups(session), orgId = rapbase::getUserReshId(session), type = "subscription", mapOrgId = NULL, includeReportId = FALSE )
makeAutoReportTab( session, namespace = character(), user = rapbase::getUserName(session), group = rapbase::getUserGroups(session), orgId = rapbase::getUserReshId(session), type = "subscription", mapOrgId = NULL, includeReportId = FALSE )
session |
A shiny session object |
namespace |
String naming namespace. Defaults to |
user |
Character string providing the username. Introduced as a new
argument when running apps inside containers. Default value is set to
|
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 |
orgId |
Character string or integer defining the organization (id) for
|
type |
Character string defining the type of auto reports to tabulate.
Must be one of |
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 |
includeReportId |
Logical if the unique report id should be added as the last column in the table. FALSE by default. |
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 edit_button and del_button and upon clicking the
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
shiny::observeEvent("edit_button")
and within this event the
report id is obtained by collecting the string after the double underscore,
e.g. 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 example shiny server function in rapRegTemplate on how this function may be implemented.
Matrix providing a table to be rendered in a shiny app
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
makeRunDayOfYearSequence(startDay = Sys.Date(), interval)
makeRunDayOfYearSequence(startDay = Sys.Date(), interval)
startDay |
Start date of sequence. May be provided as a string, e.g. \"2019-03-17\" or as class \"Date\". Defaults to today |
interval |
String representing a valid seq.POSIXt interval such as "DSTday", "week", "month", "quarter" or "year") |
Integer vector of day numbers
makeRunDayOfYearSequence(interval = "month")
makeRunDayOfYearSequence(interval = "month")
Function that will return tables used in reports.
mst( tab, col_names = colnames(tab), type = "pdf", cap = "", label = knitr::opts_current$get("label"), digs = 0, align = NULL, fs = 8, lsd = FALSE )
mst( tab, col_names = colnames(tab), type = "pdf", cap = "", label = knitr::opts_current$get("label"), digs = 0, align = NULL, fs = 8, lsd = FALSE )
tab |
Data frame or matrix representing the table. |
col_names |
Character vector with column names. Defaults
|
type |
Character string defining output, either "html" or "pdf". Default is "pdf". |
cap |
Character string with table caption. Empty string by default. |
label |
Character string defining the label in case the table needs to
be referenced elsewhere in the overall document. For instance, setting this
to 'my_table' the corresponding inline rmarkdown reference to use is
|
digs |
Integer number of digits to use. 0 by default. |
align |
Character vector specifying column alignment in the LaTeX way,
e.g. |
fs |
Integer providing the font size. Applies only for pdf output. Default value is 8. |
lsd |
Logical if table is to be scaled down. Applies only for pdf output. FALSE by default. |
mst()
creates RMarkdown code for creating standard tables.
Character string containing RMarkdown table code
mst(tab = mtcars[1:10, ])
mst(tab = mtcars[1:10, ])
To be applied for user input when there is actually no choice :-)
noOptOutOk()
noOptOutOk()
String with possible state of mind (in Norwegian) once left with no options
noOptOutOk()
noOptOutOk()
Provide common functions and resources for registry specific R-packages at Rapporteket. This packages is relevant for developers of packages/registries at Rapporteket
Close down data connection handle
rapCloseDbConnection(con)
rapCloseDbConnection(con)
con |
Open connection object that is to be closed |
Generic to registries, handle the data source connections, including usernames and passwords needed to open these connections
rapOpenDbConnection(registryName, dbType = "mysql")
rapOpenDbConnection(registryName, dbType = "mysql")
registryName |
String id used for the registry in global configuration file from which information on the database connection is provided |
dbType |
String providing type of data source, one of "mysql" and "mssql". Defaults to "mysql" |
A named list of con and drv representing the db connection handle and driver, respectively.
Read automated report metadata
readAutoReportData(fileName = "autoReport.yml", packageName = "rapbase")
readAutoReportData(fileName = "autoReport.yml", packageName = "rapbase")
fileName |
String defining name of the yaml configuration file. Default 'autoReport.yml' |
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) |
a list of yaml data
readAutoReportData()
readAutoReportData()
Function that renders documents at Rapporteket from rmarkdown source files.
Output formats may be (vanilla) HTML or PDF based on our own pandoc latex
template or fragments of html when the result is to be embedded in existing
web pages. Rmarkdown allow parameters to be part of report processing. Thus,
parameters that are specific to reports must be provided (as a named list)
when calling renderRmd()
.
renderRmd( sourceFile, outputType = "html", logoFile = NULL, params = list(), template = "default" )
renderRmd( sourceFile, outputType = "html", logoFile = NULL, params = list(), template = "default" )
sourceFile |
Character string providing the path to the rmarkdown source file. |
outputType |
Character string specifying the output format. Must be one
of |
logoFile |
Character string with path to the logo to be used for PDF
output. Often, this will be the registry logo. Only PNG and PDF graphics are
allowed. Default value is |
params |
List of report parameters (as named values) to override the
corresponding entries under params in the rmarkdown document yaml
header. Default is |
template |
Character string defining which template to use for making pdf documents. Must be one of "default" or "document" where the first is assumed if this argument is not set. |
Character string with path to the rendered file or, if
outputType
is set to "html_fragment", a character string providing an
html fragment. Files are named according to tempfile()
with an empty
pattern and with the extension according to outputType
("pdf" or "html").
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
runAutoReport( dayNumber = as.POSIXlt(Sys.Date())$yday + 1, type = c("subscription", "dispatchment"), dryRun = FALSE )
runAutoReport( dayNumber = as.POSIXlt(Sys.Date())$yday + 1, type = c("subscription", "dispatchment"), dryRun = FALSE )
dayNumber |
Integer day of year where January 1st is 1. Defaults to
current day, i.e. |
type |
Character vector defining the type of reports to be processed.
May contain one or more of
|
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 |
Emails with corresponding file attachment. If dryRun == TRUE just a message
# Example depend on environment variable R_RAP_CONFIG_PATH being set runAutoReport()
# Example depend on environment variable R_RAP_CONFIG_PATH being set runAutoReport()
This is a wrapper for runAutoReport()
to issue bulletins. Purpose is
to ease simplify fire-in-the-hole at Rapporteket
runBulletin()
runBulletin()
Whatever runAutoReport()
might provide
Function to run noweb file contained in a package. Assume all noweb files of the package are placed flat under the inst directory
runNoweb(nowebFileName, packageName, weaveMethod = "knitr")
runNoweb(nowebFileName, packageName, weaveMethod = "knitr")
nowebFileName |
Basename of the noweb file, e.g. 'myFile.Rnw'. |
packageName |
Name of the package containing noweb file(s) |
weaveMethod |
Method to apply for weaving. Currently available are 'Sweave' and 'knitr', default to the latter. |
Sanitize log entries that have reached end of life
sanitizeLog()
sanitizeLog()
NULL on success
This function can be used to send email from within R at Rapporteket. It relies on (and must hence be provided) specific settings through local configuration to work properly.
sendEmail(conf, to, subject, text, attFile = NULL)
sendEmail(conf, to, subject, text, attFile = NULL)
conf |
List containing (Rapporteket) config such as sender email address, SMTP server url and port number |
to |
Character vector containing email addresses. May also contain
full names like ' |
subject |
Character string providing email subject. |
text |
Character string providing the plain email text |
attFile |
Character string providing the full file path to an attachment. Default is NULL in which case no attachment is made |
Invisible sending of email
Low level functions for handling registry staging data at Rapporteket. As such, these functions does not provide staging data management per se. Proper management, e.g. staging data updates and fallback logic must therefore be established within each registry that take staging data into use.
listStagingData(registryName, dir = Sys.getenv("R_RAP_CONFIG_PATH")) mtimeStagingData(registryName, dir = Sys.getenv("R_RAP_CONFIG_PATH")) saveStagingData( registryName, dataName, data, dir = Sys.getenv("R_RAP_CONFIG_PATH") ) loadStagingData(registryName, dataName, dir = Sys.getenv("R_RAP_CONFIG_PATH")) deleteStagingData( registryName, dataName, dir = Sys.getenv("R_RAP_CONFIG_PATH") ) cleanStagingData(eolAge, dryRun = TRUE)
listStagingData(registryName, dir = Sys.getenv("R_RAP_CONFIG_PATH")) mtimeStagingData(registryName, dir = Sys.getenv("R_RAP_CONFIG_PATH")) saveStagingData( registryName, dataName, data, dir = Sys.getenv("R_RAP_CONFIG_PATH") ) loadStagingData(registryName, dataName, dir = Sys.getenv("R_RAP_CONFIG_PATH")) deleteStagingData( registryName, dataName, dir = Sys.getenv("R_RAP_CONFIG_PATH") ) cleanStagingData(eolAge, dryRun = TRUE)
registryName |
Character string providing the registry name. |
dir |
Character string providing the path to where the staging data
directory resides in case of storage as files. Default value is
|
dataName |
Character string providing the data set name. |
data |
A data object such as a data.frame to be stored as
|
eolAge |
Numeric providing the staging data end-of-life age in seconds.
Based on the current time and the time of storage staging files
older than |
dryRun |
Logical defining if function is to be run in dry (none destructive) mode. |
Staging data can be stored as files or as binary large objects in a database
and method of choice is defined by the rapbase
configuration.
Regardless of storage method a per registry symmetric encryption of storage
content is enforced. Keys used for encryption are generated from existing
database credentials. Therefore, please note that removing or changing
such credentials will render any historic staging data inaccessible.
cleanStagingData()
globally removes all staging data with store date
prior to the end-of-life age provided. This is a vastly destructive function
that should be used with great care.
listStagingData()
returns a character vector of staging data
sets for the given registry (registryName
).
mtimeStagingData()
returns a staging data set named POSIXct
vector of modification times for the given registry
(registryName
).
saveStagingData()
when successful returns the data object
(data
), invisibly. If saving fails a warning is issued and the
function returns FALSE.
loadStagingData()
returns the data object corresponding to
the name given upon saving (dataName
). If the requested data set
for loading does not exist the function returns FALSE.
deleteStagingData()
returns TRUE if the data set was deleted
and FALSE if not.
cleanStagingData()
returns a list of data sets (to be)
removed.
rapbase:::pathStagingData()
is an internal helper function and
returns a character string with the path to the staging directory of
registryName
. If its parent directory (dir
) does not exists
an error is returned.
## Prep test data registryName <- "rapbase" dataName <- "testData" data <- mtcars dir <- tempdir() ## Save data for staging saveStagingData(registryName, dataName, data, dir) ## List data currently in staging listStagingData(registryName, dir) ## Retrieve data set from staging and compare to outset stagedData <- loadStagingData(registryName, dataName, dir) identical(data, stagedData) ## Get modification time for staging file(s) mtimeStagingData(registryName, dir)
## Prep test data registryName <- "rapbase" dataName <- "testData" data <- mtcars dir <- tempdir() ## Save data for staging saveStagingData(registryName, dataName, data, dir) ## List data currently in staging listStagingData(registryName, dir) ## Retrieve data set from staging and compare to outset stagedData <- loadStagingData(registryName, dataName, dir) identical(data, stagedData) ## Get modification time for staging file(s) mtimeStagingData(registryName, dir)
These modules may be used by registries for easy setup of usage reports. The intended purpose is to provide registry staff access to when and by whom the resources at Rapporteket were used, i.e. application start-up and single report usage. As such, this will be a tool to provide useful statistics. However, it might also serve as a formal monitor utility but only if logging is carefully implemented throughout the relevant functions that make up the registry application at Rapporteket.
statsInput(id) statsUI(id) statsServer(id, registryName, eligible = TRUE) statsApp() logFormat(log) logTimeFrame(log, startDate, endDate)
statsInput(id) statsUI(id) statsServer(id, registryName, eligible = TRUE) statsApp() logFormat(log) logTimeFrame(log, startDate, endDate)
id |
Character string shiny module id |
registryName |
Character string registry name key |
eligible |
Logical defining if the module should be allowed to work at full capacity. This might be useful when access to module products should be restricted. Default is TRUE, i.e. no restrictions. |
log |
Data frame containing log data (in Rapporteket format) |
startDate |
Date object defining start of interval (character representation "YYYY-MM-DD") |
endDate |
Date object defining end of interval (character representation "YYYY-MM-DD") |
Shiny objects, mostly. Helper functions may return other stuff too.
# client user interface function ui <- shiny::fluidPage( shiny::sidebarLayout( shiny::sidebarPanel(statsInput("test")), shiny::mainPanel(statsUI("test")) ) ) # server function server <- function(input, output, session) { statsServer("test", registryName = "rapbase", eligible = TRUE) } # run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
# client user interface function ui <- shiny::fluidPage( shiny::sidebarLayout( shiny::sidebarPanel(statsInput("test")), shiny::mainPanel(statsUI("test")) ) ) # server function server <- function(input, output, session) { statsServer("test", registryName = "rapbase", eligible = TRUE) } # run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
Shiny modules providing the Stats Guide
statsGuideUI(id) statsGuideServer(id, registryName) statsGuideApp()
statsGuideUI(id) statsGuideServer(id, registryName) statsGuideApp()
id |
Character string module ID |
registryName |
Character string registry name key |
Functions ui and server representing the (module) app
ui <- shiny::fluidPage( statsGuideUI("statsGuide") ) server <- function(input, output, session) { statsGuideServer("statsGuide", "test") } if (interactive()) { shiny::shinyApp(ui, server) }
ui <- shiny::fluidPage( statsGuideUI("statsGuide") ) server <- function(input, output, session) { statsGuideServer("statsGuide", "test") } if (interactive()) { shiny::shinyApp(ui, server) }
Obtain organization unit attributes from an access tree JSON file
unitAttribute(unit, what, file = NULL, path = Sys.getenv("R_RAP_CONFIG_PATH"))
unitAttribute(unit, what, file = NULL, path = Sys.getenv("R_RAP_CONFIG_PATH"))
unit |
Integer providing the look-up unit id |
what |
Character string defining what to return for the given unit id |
file |
Character string file name of the JSON file. Default values is NULL in which case the corresponding value from rapbaseConfig.yml will be used. |
path |
Character string file path of the JSON file. Default value is
|
The corresponding value of 'what'.
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
upgradeAutoReportData(config)
upgradeAutoReportData(config)
config |
List of auto report configuration |
List of (upgraded) auto report configuration
For apps running as containers particular environment variables must be defined for an orderly handling of dynamic user privileges. This function makes use of environmental variables defined by shinyproxy to provide available privileges for the shiny application.
These are helper function for userInfo
. When used without a
shiny session object calls to these functions is made without any arguments.
If redefining contexts is needed, please use userInfo
instead.
userAttribute(group, unit = NULL) getUserEmail(shinySession = NULL, group = NULL) getUserFullName(shinySession = NULL, group = NULL) getUserGroups(shinySession = NULL, group = NULL) getUserName(shinySession = NULL, group = NULL) getUserPhone(shinySession = NULL, group = NULL) getUserReshId(shinySession = NULL, group = NULL) getUserRole(shinySession = NULL, group = NULL)
userAttribute(group, unit = NULL) getUserEmail(shinySession = NULL, group = NULL) getUserFullName(shinySession = NULL, group = NULL) getUserGroups(shinySession = NULL, group = NULL) getUserName(shinySession = NULL, group = NULL) getUserPhone(shinySession = NULL, group = NULL) getUserReshId(shinySession = NULL, group = NULL) getUserRole(shinySession = NULL, group = NULL)
group |
Character string providing the name of the app R package name. The term "group" is used to relate to the environmental variable SHINYPROXY_USERGROUPS that corresponds to the apps a given user can access. Default value is NULL but should always be set when shiny app is run as a shinyproxy container. |
unit |
Integer providing the look-up unit id. Default value is NULL in
which case all privileges for |
shinySession |
A shiny session object. Default value is NULL |
Invisibly a list of user metadata and privileges:
The username for whom the privileges apply.
User full name
User phone number
User email
Group of which the user is a member.
Unit id under which the privileges are defined.
Organization id for the user.
Role of the user.
Name of the organization as defined under the unit id.
String with user attribute
# Requires a valid shiny session object try(getUserEmail()) try(getUserEmail(shinySessionObject))
# Requires a valid shiny session object try(getUserEmail()) try(getUserEmail(shinySessionObject))
Extracts elements from either config, url (shiny), shiny session or environmental variables relevant for user data such as name, group, role and org id (e.g. resh id). Source of info is based on environment context and can be controlled by altering the default settings for which contexts that will apply for the various sources of user data. This function will normally be used via its helper functions (see below).
userInfo( entity, shinySession = NULL, devContexts = c("DEV"), testContexts = c("TEST"), prodContexts = c("QA", "QAC", "PRODUCTION", "PRODUCTIONC"), group = NULL )
userInfo( entity, shinySession = NULL, devContexts = c("DEV"), testContexts = c("TEST"), prodContexts = c("QA", "QAC", "PRODUCTION", "PRODUCTIONC"), group = NULL )
entity |
String defining the element to return. Currently, one of 'user', groups', 'resh_id', 'role', 'email', 'full_name' or 'phone'. |
shinySession |
Shiny session object (list, NULL by default). Must be provided when the source of user attributes is either the shiny app url or an external authentication provider. By default this will apply to the 'TEST', 'QA' and 'PRODUCTION' contexts in which case the shiny session object must be provided. |
devContexts |
A character vector providing unique instances to be
regarded as a development context. In this context user attributes will be
read from configuration as provided by 'rapbaseConfig.yml'. The instances
provided cannot overlap instances provided in any other contexts. By
default set to |
testContexts |
A character vector providing unique instances to be
regarded as a test context. In this context user attributes will be read
from the url call to a shiny application. Hence, for this context the
corresponding shiny session object must also be provided. The instances
provided cannot overlap instances provided in any other contexts. By
default set to |
prodContexts |
A character vector providing unique instances to be
regarded as a production context. In this context user attributes will be
read from the shiny session object (on deployment in shiny-server) or, from
environmental variables (on standalone container deployment). Hence, for
this context the corresponding shiny session object must also be provided.
Instances provided cannot overlap instances in any other contexts. By
default set to |
group |
Character string providing the name of the app R package name. The term "group" is used to relate to the environmental variable SHINYPROXY_USERGROUPS that corresponds to the apps a given user can access. |
String of single user data element
getUserName
, getUserGroups
,
getUserReshId
, getUserRole
Write automated report metadata
writeAutoReportData( fileName = "autoReport.yml", config, packageName = "rapbase" )
writeAutoReportData( fileName = "autoReport.yml", config, packageName = "rapbase" )
fileName |
String defining name of the yaml configuration file. Default 'autoReport.yml' |
config |
a list of yaml configuration |
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) |
# Example depend on environment variable R_RAP_CONFIG_PATH being set config <- readAutoReportData() try(writeAutoReportData(config = config))
# Example depend on environment variable R_RAP_CONFIG_PATH being set config <- readAutoReportData() try(writeAutoReportData(config = config))