| 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] (ORCID: <https://orcid.org/0000-0002-5210-3656>), Kevin Otto Thon [aut], Arnfinn Hykkerud Steindal [aut] (ORCID: <https://orcid.org/0000-0002-4088-7860>), Petter Linberg [aut] |
| Maintainer: | Arnfinn Hykkerud Steindal <[email protected]> |
| License: | GPL-3 |
| Version: | 3.7.0 |
| Built: | 2026-06-01 16:41:14 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.
appLogappLog
A data frame with 20 rows and 8 variables:
character id
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 = shiny::reactiveVal(TRUE), freq = "month", user, runAutoReportButton = FALSE ) autoReportServer2(...)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 = shiny::reactiveVal(TRUE), freq = "month", user, runAutoReportButton = FALSE ) autoReportServer2(...)
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
|
runAutoReportButton |
Logical defining if runAutoReport button should be made available in the GUI. Default is FALSE. If TRUE, a button will be made available to trigger running all auto reports for a given date. This is mainly useful for testing purposes. |
... |
Arguments passed to autoReportServer function |
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.
## 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())) autoReportServer2( id = "test", registryName = "rapbase", type = "dispatchment", org = org$value, paramNames = paramNames, paramValues = paramValues, reports = reports, orgs = orgs, eligible = TRUE, freq = "month", user ) } # 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())) autoReportServer2( id = "test", registryName = "rapbase", type = "dispatchment", org = org$value, paramNames = paramNames, paramValues = paramValues, reports = reports, orgs = orgs, eligible = TRUE, freq = "month", user ) } # 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/db
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, dbName, teamName = NULL, eligible = shiny::reactiveVal(TRUE) ) exportUCApp(dbName = "rapbase") selectListPubkey(pubkey) exportDb(dbName, dropTabs = NULL, tableNames = "", compress = FALSE, session) queryToFile( dbName, tableName = "", query, format = "RDS", compress = FALSE, session )exportUCInput(id) exportUCServer( id, dbName, teamName = NULL, eligible = shiny::reactiveVal(TRUE) ) exportUCApp(dbName = "rapbase") selectListPubkey(pubkey) exportDb(dbName, dropTabs = NULL, tableNames = "", compress = FALSE, session) queryToFile( dbName, tableName = "", query, format = "RDS", compress = FALSE, session )
id |
Character string module ID |
dbName |
Character string database name. If this is 'data', then the database name is taken from the environment variable 'MYSQL_DB_DATA'. |
teamName |
Character string defining the github team name containing
members allowed to export the database. 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 |
dropTabs |
Character vector with names of tables to be excluded from export. |
tableNames |
Character vector with names of tables to export. Only used when exporting the whole database, not a single table. |
compress |
Logical if export data is to be compressed (using gzip). FALSE by default. |
session |
Shiny session object |
tableName |
Character string with name of table to export. Only used when exporting a single table, not the whole database. |
query |
Character string with SQL query to fetch data to export. Only used when exporting a single table, not the whole database. |
format |
Character string with format to export data in. Only used when exporting a single table, not the whole database. Possible values are |
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", dbName = "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", dbName = "rapbase") } ## run the shiny app in an interactive environment if (interactive()) { shiny::shinyApp(ui, server) }
Shiny app with database export functionality
exportApp(teamName = "", dbName = "data", logAsJson = TRUE)exportApp(teamName = "", dbName = "data", logAsJson = TRUE)
teamName |
Character string, corresponding to github team name |
dbName |
Character string, can be used to specify name of database if needed. Defaults to "data", which will work for most registries. |
logAsJson |
Logical, if TRUE (default) logging will be done in JSON format. |
Shiny modules providing the Export Guide
exportGuideUI(id) exportGuideServer(id, dbName) exportGuideServer2(id, dbName) exportGuideApp()exportGuideUI(id) exportGuideServer(id, dbName) exportGuideServer2(id, dbName) exportGuideApp()
id |
Character string module ID |
dbName |
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 <- data.frame(type = c("A", "B")) filterAutoRep(ar, "type", "B") # ar2ar <- data.frame(type = c("A", "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, terminateDate, interval = NULL, returnFormat = "%A %e. %B %Y" )findNextRunDate( runDayOfYear, baseDayNum = as.POSIXlt(Sys.Date())$yday + 1, startDate, terminateDate, interval = 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 |
terminateDate |
Date-class date after which report is no longer run.
Default value set to |
interval |
String defining a time interval as defined in
|
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(runDayOfYear = c(10, 20, 30), baseDayNum = 20, startDate = 1, terminateDate = 50)# Will return Jan 30 in the current year and locale with default formatting findNextRunDate(runDayOfYear = c(10, 20, 30), baseDayNum = 20, startDate = 1, terminateDate = 50)
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, packageName = "rapbase")getConfig(fileName, packageName = "rapbase")
fileName |
String providing configuration file base name |
packageName |
String providing the package name |
A list of (yaml) configuration
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
To be used for testing purposes
halloRapporteket()halloRapporteket()
message A test message
Render text on how Rapporteket deals with personal data
howWeDealWithPersonalData(..., callerPkg = NULL)howWeDealWithPersonalData(..., callerPkg = NULL)
... |
Further arguments, currently not used |
callerPkg |
Character string naming the package this function was called from. The value is used to display the current version of the R package representing the registry at Rapporteket. |
fragment html info text
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 = "data", query, dbType = "mysql") describeRegistryDb(registryName, tabs = c()) nlinesRegistryDb(registryName, tab = "")loadRegData(registryName = "data", query, dbType = "mysql") describeRegistryDb(registryName, tabs = c()) nlinesRegistryDb(registryName, tab = "")
registryName |
String providing the name of the database to connect to. If it is "data" it will use the MYSQL_DB_DATA environment variable, if it is "autoreport" it will use the MYSQL_DB_AUTOREPORT environment variable, and if it is "raplog" it will use the MYSQL_DB_LOG environment variable. If none of these are set, it will use the name provided. |
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 |
tab |
String name of the table for which to get number of lines |
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() ) userLogger(user, msg = "No message provided") 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() ) userLogger(user, msg = "No message provided") 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"))
Every info, warning and error will be logged in json format.
loggerSetup( usernameEnv = "SHINYPROXY_USERNAME", appidEnv = "SHINYPROXY_APPID", hooks = TRUE )loggerSetup( usernameEnv = "SHINYPROXY_USERNAME", appidEnv = "SHINYPROXY_APPID", hooks = TRUE )
usernameEnv |
Global variable containing user name |
appidEnv |
Global variable containing application name |
hooks |
Logical defining if hooks for automatic logging should be set |
Wrapper around logger::log_shiny_input_changes
logShinyInputChanges(...)logShinyInputChanges(...)
... |
Arguments passed to logger::log_shiny_input_changes function |
Make a table to be rendered in a shiny app providing automated reports from a given user or registry as obtained from the environmental variables.
makeAutoReportTab( namespace = character(), user = getUserName(), group = getUserGroups(), orgId = getUserReshId(), type = "subscription", mapOrgId = NULL, includeReportId = FALSE )makeAutoReportTab( namespace = character(), user = getUserName(), group = getUserGroups(), orgId = getUserReshId(), type = "subscription", mapOrgId = NULL, includeReportId = FALSE )
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(dbName, dbType = "mysql")rapOpenDbConnection(dbName, dbType = "mysql")
dbName |
String providing the name of the database to connect to. If it is "data" it will use the MYSQL_DB_DATA environment variable, if it is "autoreport" it will use the MYSQL_DB_AUTOREPORT environment variable, and if it is "raplog" it will use the MYSQL_DB_LOG environment variable. If none of these are set, it will use the name provided. |
dbType |
String providing type of data source, one of "mysql" and "sqlite". Defaults to "mysql". "mssql" is not supported anymore. |
A named list of con and drv representing the db connection handle and driver, respectively.
This is a wrapper around bslib::bs_theme
rapTheme(theme = "flatly", version = 3)rapTheme(theme = "flatly", version = 3)
theme |
Name of the theme. See bslib::bootswatch_themes() for available themes. |
version |
Version of bootstrap to use (3, 4 or 5). |
a Bootstrap theme object
Read automated report metadata
readAutoReportData()readAutoReportData()
a table of autoreport data
try(readAutoReportData())try(readAutoReportData())
Title on the top left of the app, including the logo
regTitle(regTitle = "rapbase")regTitle(regTitle = "rapbase")
regTitle |
Title of the app |
a div containing the logo and the title
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").
Updated version of repLogger() to be used
in reactive contexts where user data is
provided as reactive values. This is the case for
the when user <- navbarWidgetServer2 which
the way of providing user data in shiny applications
at Rapporteket. The use of the original repLogger()
should be changed to repLogger2 as
repLogger() doesn't handle change of user roles
during a session, which can happen in the shiny
applications at Rapporteket.
repLogger2( user, msg = "No message provided", .topcall = sys.call(-1), .topenv = parent.frame() )repLogger2( user, msg = "No message provided", .topcall = sys.call(-1), .topenv = parent.frame() )
user |
This needs to be a navbarWidgetServer2 object. Make sure to be in a reactive context when calling this function. |
msg |
String providing a description of the event to be logged. 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 |
If you are in the main shiny server, you can call user
without passing
it as an argument to the server function, as user is available
in the main server environment. However, if you are in a module server
function, you need to pass user as an argument to
the module server function before you call repLogger2(user).
## Not run: # Inside a reactive context, for example within a # downloadHandler() function, you can call: rapbase::repLogger2(user, msg = "This is a test") # make sure user exists inside server modules # by passing it as an argument to the module server function: module_server <- function(id, user) { ... } ## End(Not run)## Not run: # Inside a reactive context, for example within a # downloadHandler() function, you can call: rapbase::repLogger2(user, msg = "This is a test") # make sure user exists inside server modules # by passing it as an argument to the module server function: module_server <- function(id, user) { ... } ## End(Not run)
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, dato = Sys.Date(), group = NULL, type = c("subscription", "dispatchment"), dryRun = FALSE )runAutoReport( dayNumber = as.POSIXlt(Sys.Date())$yday + 1, dato = Sys.Date(), group = NULL, type = c("subscription", "dispatchment"), dryRun = FALSE )
dayNumber |
Integer day of year where January 1st is 1. Defaults to
current day, i.e. |
dato |
Date-class date when report will be run first time. 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 |
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 try(runAutoReport())# Example depend on environment variable R_RAP_CONFIG_PATH being set try(runAutoReport())
This is a wrapper for runAutoReport() to issue bulletins.
runBulletin()runBulletin()
Whatever runAutoReport() might provide
Function that removes log entries older than a given number of days.
sanitizeLog(eolDays = 730)sanitizeLog(eolDays = 730)
eolDays |
Number of days to keep log entries. Entries older than this will be removed. Default value is 730 days (2 years). |
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 in HTML format. |
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, dbTable = "data") mtimeStagingData(registryName, dbTable = "data") saveStagingData(registryName, dataName, data, dbTable = "data") loadStagingData(registryName, dataName, dbTable = "data") deleteStagingData(registryName, dataName, dbTable = "data") cleanStagingData(eolAge, dryRun = TRUE, dbTable = "data")listStagingData(registryName, dbTable = "data") mtimeStagingData(registryName, dbTable = "data") saveStagingData(registryName, dataName, data, dbTable = "data") loadStagingData(registryName, dataName, dbTable = "data") deleteStagingData(registryName, dataName, dbTable = "data") cleanStagingData(eolAge, dryRun = TRUE, dbTable = "data")
registryName |
Character string providing the registry name. |
dbTable |
Character string providing the database table name to be used |
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 is stored as binary large objects in a database. 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.
## Prep test data registryName <- "rapbase" dataName <- "testData" data <- mtcars ## Save data for staging try(saveStagingData(registryName, dataName, data)) ## List data currently in staging try(listStagingData(registryName)) ## Retrieve data set from staging and compare to outset try(stagedData <- loadStagingData(registryName, dataName)) try(identical(data, stagedData)) ## Get modification time for staging file(s) try(mtimeStagingData(registryName))## Prep test data registryName <- "rapbase" dataName <- "testData" data <- mtcars ## Save data for staging try(saveStagingData(registryName, dataName, data)) ## List data currently in staging try(listStagingData(registryName)) ## Retrieve data set from staging and compare to outset try(stagedData <- loadStagingData(registryName, dataName)) try(identical(data, stagedData)) ## Get modification time for staging file(s) try(mtimeStagingData(registryName))
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, app_id = NULL, eligible = TRUE) statsServer2( id, registryName, app_id = NULL, eligible = shiny::reactiveVal(TRUE) ) statsApp() logFormat(log) logTimeFrame(log, startDate, endDate)statsInput(id) statsUI(id) statsServer(id, registryName, app_id = NULL, eligible = TRUE) statsServer2( id, registryName, app_id = NULL, eligible = shiny::reactiveVal(TRUE) ) statsApp() logFormat(log) logTimeFrame(log, startDate, endDate)
id |
Character string shiny module id |
registryName |
Character string registry name key |
app_id |
An identifier for a particular registry. Default value is NULL, in which case no action is taken. If value is provided, the log is filtered to show only entries matching chosen app_id. |
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) }
A dataset containing test entries.
testdatatestdata
A data frame with 10 rows and 6 variables:
int id
char text
int integer
int big integer
num float number
time date
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(unit = NULL, map_orgname = NULL) getUserEmail(...) getUserFullName(...) getUserGroups(...) getUserName(...) getUserPhone(...) getUserReshId(...) getUserRole(...)userAttribute(unit = NULL, map_orgname = NULL) getUserEmail(...) getUserFullName(...) getUserGroups(...) getUserName(...) getUserPhone(...) getUserReshId(...) getUserRole(...)
unit |
Integer providing the look-up unit id. Default value is NULL in
which case all privileges for |
map_orgname |
A data.frame containing two columns:
|
... |
To keep the same interface as before. Not used. |
Invisibly a list of user metadata and privileges:
The username for whom the privileges apply.
User full name
User phone number
User email
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
try(getUserEmail())try(getUserEmail())
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)userInfo(entity)
entity |
String defining the element to return. Currently, one of 'user', groups', 'resh_id', 'role', 'email', 'full_name' or 'phone'. |
String of single user data element
getUserName, getUserGroups,
getUserReshId, getUserRole
Write automated report metadata
writeAutoReportData(config)writeAutoReportData(config)
config |
a list of yaml configuration |
# Example depend on environment variable R_RAP_CONFIG_PATH being set try(config <- readAutoReportData()) try(writeAutoReportData(config = config))# Example depend on environment variable R_RAP_CONFIG_PATH being set try(config <- readAutoReportData()) try(writeAutoReportData(config = config))