Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Function to initialise google analytics html script #4

Merged
merged 37 commits into from
Jul 22, 2024
Merged
Show file tree
Hide file tree
Changes from 26 commits
Commits
Show all changes
37 commits
Select commit Hold shift + click to select a range
6260d78
Added initialise google analytics function.
rmbielby Nov 8, 2023
23568ef
Added extra documentation info
rmbielby Nov 8, 2023
771a116
Resolve merge conflicts from main
rmbielby Mar 13, 2024
f64f95c
Added validation on the ga_code variable for the google analytics scr…
rmbielby Mar 13, 2024
cebb5bd
Added tests for initialise_analytics
rmbielby Mar 13, 2024
a9790e1
Updated documentation
rmbielby Mar 13, 2024
5bfede7
Added magrittr pipe load
rmbielby Mar 13, 2024
8dc456d
Added magrittr DESCRIPTION
rmbielby Mar 13, 2024
7cd6557
Added source package for str_trim
rmbielby Mar 13, 2024
bd7d0c4
Removed yml code that had crept in from another branch
rmbielby Mar 13, 2024
4906b65
Cleaning up documentation
rmbielby Mar 13, 2024
4467b91
Adding test r script to tidy code exclude list
rmbielby Mar 13, 2024
63ecfa0
Adding info into README on analytics initialiser
rmbielby Mar 27, 2024
b09328d
Cleaning up line lengths in initialisers
rmbielby Mar 27, 2024
f46e7e6
Cleaning up line lengths in tidy code
rmbielby Mar 27, 2024
5a45bf8
Updated installation guidance in readme
rmbielby Mar 27, 2024
a7c4d5b
Updated installation guidance in readme
rmbielby Mar 27, 2024
1bb8e70
Adjusting line lengths in analyics function
rmbielby Mar 27, 2024
84a3721
Adjusted messaging spacing in initialiser script
rmbielby Mar 27, 2024
07d1bb2
Tweaks to initialisers code
rmbielby Mar 27, 2024
e9e0d8f
Removed google analyics html
rmbielby Mar 27, 2024
1450aec
Merge branch 'main' into analytsics-init
rmbielby Mar 27, 2024
a212e57
Merge branch 'main' into analytsics-init
rmbielby Jul 22, 2024
f1343d5
Reconfigured analytics initialiser to pull template script from GitHub
rmbielby Jul 22, 2024
0a754ab
Rebuilt package after init_analytics updates
rmbielby Jul 22, 2024
4ee5c8c
Few minor updates around analytics initialisation.
rmbielby Jul 22, 2024
117cf35
Removed google-analytics.html
rmbielby Jul 22, 2024
39a7715
Corrected reference to google-analytics.html in .gitignore
rmbielby Jul 22, 2024
15479bc
Handful of PR change requests on analytics initiailser
rmbielby Jul 22, 2024
41179f5
Recommitting google analytics template sc
rmbielby Jul 22, 2024
6fc3f9a
Updating .gitignore to only ignore analytics html if found in project…
rmbielby Jul 22, 2024
af6d8d9
Few updates from analytics PR
rmbielby Jul 22, 2024
5d253e3
Updting references to init_analytics().
rmbielby Jul 22, 2024
2d8ea4c
Updating references from Stats Dev team to EESp team
rmbielby Jul 22, 2024
00694a2
Updating reference filename for analytics
rmbielby Jul 22, 2024
219e4bd
removing google-analytics.html
rmbielby Jul 22, 2024
9cd99fe
updating analytics references in .gitignore
rmbielby Jul 22, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
.Rhistory
.RData
.Ruserdata
google_analytics.html
docs
inst/doc
www/
1 change: 1 addition & 0 deletions DESCRIPTION
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ Description: R package containing preferred methods for creating official
DfE R-Shiny dashboards.
License: GPL (>= 3)
Imports:
magrittr,
checkmate,
glue,
htmltools,
Expand Down
2 changes: 2 additions & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,10 @@ export(cookies_panel_server)
export(cookies_panel_ui)
export(custom_disconnect_message)
export(dfe_cookie_script)
export(init_analytics)
export(init_cookies)
export(support_panel)
export(tidy_code)
importFrom(htmltools,tagList)
importFrom(htmltools,tags)
importFrom(magrittr,"%>%")
4 changes: 3 additions & 1 deletion R/cookies.R
Original file line number Diff line number Diff line change
Expand Up @@ -235,7 +235,9 @@ init_cookies <- function() {
}

tryCatch(
download.file(url = "https://raw.githubusercontent.com/dfe-analytical-services/dfeshiny/main/inst/cookie-consent.js", destfile = "www/cookie-consent.js"), # nolint: [line_length_linter]
utils::download.file(
url = "https://raw.githubusercontent.com/dfe-analytical-services/dfeshiny/main/inst/cookie-consent.js", # nolint: [line_length_linter]
destfile = "www/cookie-consent.js"),
error = function(e) {
return("Download failed")
},
Expand Down
67 changes: 67 additions & 0 deletions R/initialisers.R
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#' init_analytics
#' @description
#' Creates the google-analytics.html script in order to allow the activation of
#' analytics via GA4. For the full steps required to set up analytics, please
#' refer to the documentation in the readme.
#'
cjrace marked this conversation as resolved.
Show resolved Hide resolved
#' @param ga_code The Google Analytics code
#' @importFrom magrittr %>%
#' @return TRUE if written, FALSE if not
#' @export
#'
#' @examples init_analytics(ga_code = "0123456789")
init_analytics <- function(ga_code) {
is_valid_ga4_code <- function(ga_code) {
stringr::str_length(ga_code) == 10 & typeof(ga_code) == "character"
}

if (is_valid_ga4_code(ga_code) == FALSE) {
stop(
'You have entered an invalid GA4 code in the ga_code argument.
Please enter a 10 digit code as a character string.
e.g. "0123QWERTY"'
)
}

webpage <- RCurl::getURL("https://raw.githubusercontent.com/dfe-analytical-services/dfeshiny/analytsics-init/inst/google-analytics.hml")
Dismissed Show dismissed Hide dismissed
rmbielby marked this conversation as resolved.
Show resolved Hide resolved
tryCatch(
html_script <- gsub(
Dismissed Show dismissed Hide dismissed
"XXXXXXXXXX",
ga_code,
readLines(tc <- textConnection(webpage))
),
error = function(e) {
return("Download failed")
},
message("Downloaded analytics template script")
)

close(tc)
if (file.exists("google-analytics.html")) {
message("Analytics file already exists.")
message("If you have any customisations in that file, make sure you've
backed those up before over-writing.")
user_input <- stringr::str_trim(
readline(
Dismissed Show dismissed Hide dismissed
prompt = "Are you happy to overwrite the existing analytics script (y/N) "
)
)
if (user_input %in% c("y", "Y")) {
write_out <- TRUE
} else {
write_out <- FALSE
}
} else {
write_out <- TRUE
}
if (write_out) {
cat(html_script, file = "google-analytics.html")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
message("")
message("Google analytics script created in google-analytics.html.")
message("You'll need to add the following line to your ui.R script to start
recording analytics:")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
message('tags$head(includeHTML(("google-analytics.html"))),')
cjrace marked this conversation as resolved.
Show resolved Hide resolved
} else {
message("Original Google analytics html script left in place.")
}
}
10 changes: 8 additions & 2 deletions R/tidy_code.R
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,8 @@
#' @param subdirs List of sub-directories to
#' (recursively search for R scripts to be styled)
#'
#' @return True or False value based on if scripts were changed
#' @return TRUE if any changes have been made to any scripts, FALSE if all
#' passed.
#' @export
#'
#' @examples
Expand All @@ -17,7 +18,12 @@ tidy_code <- function(subdirs = c("R", "tests")) {
message("----------------------------------------")
message("App scripts")
message("----------------------------------------")
script_changes <- eval(styler::style_dir(recursive = FALSE)$changed)
script_changes <- eval(
styler::style_dir(
recursive = FALSE,
exclude_files = c("dfeshiny-Ex.R")
)$changed
)
for (dir in subdirs) {
if (dir.exists(dir)) {
message(paste(dir, "scripts"))
Expand Down
26 changes: 25 additions & 1 deletion README.md
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,15 @@ them meet the necessary standards required of public facing government services.

To install, run `renv::install("dfe-analytical-services/dfeshiny")`.

### Potential errors when installing
## Installing functionality in development from a branch

It can be useful when developing the package in particular to trial new or updated functionality in a shiny app. To do this, you can install the required branch using (replacing `branch-name` with the name of the branch you wish to install):

`renv::install("dfe-analytical-services/dfeshiny@branch-name")`

That will install the code from the named branch as dfeshiny in your app. You will need to restart your R session before it will start using the latest version that you've installed.

## Potential errors when installing

If you get `ERROR [curl: (22) The requested URL returned error: 401]`, and don't know why, try running `Sys.unsetenv("GITHUB_PAT")` to temporarily clear your GitHub PAT variable.

Expand All @@ -24,6 +32,22 @@ If this works, then you will need to look for where that "GITHUB_PAT" variable i

## Using this package in a DfE data dashboard

### Adding analytics to your dashboard

For analytics to function on your dashboard, you will need to:

- request a Google Analytics key from the [Statistics Development Team](mailto:[email protected])
- create a html file with the javascript required for your dashboard to connect to Google Analytics
cjrace marked this conversation as resolved.
Show resolved Hide resolved
- add the line: `tags$head(includeHTML(("google-analytics.html"))),` to the ui.R file.

To create the latter, we provide the function `dfeshiny::initialise_analytics()`. You should run this code from the R console providing your Google Analytics code as follows (replacing `ABCDE12345` with the code obtained from the Statistics Development team):
cjrace marked this conversation as resolved.
Show resolved Hide resolved

```
initialise_analytics("ABCDE12345")
cjrace marked this conversation as resolved.
Show resolved Hide resolved
```

This will create the file [google-analytics.html](google-analytics.html) within the home directory of your R project. This html file can be edited to add customised analytics recorders for different shiny elements in your dashboard. Feel free to contact our team if you need support in adding additional functionality.

### Adding a custom disconect message to your dashboard

dfeshiny provides a function to add a custom disconnect message to your dashboard - this will appear when a dashboard would otherwise 'grey-screen' and will include options to refresh the page, go to overflow sites or visit the publication directly on Explore education statistics.
Expand Down
1 change: 1 addition & 0 deletions google-analytics.html
cjrace marked this conversation as resolved.
Show resolved Hide resolved
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<script> // Define dataLayer and the gtag function. window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} // Default ad_storage to 'denied' as a placeholder // Determine actual values based on your own requirements gtag('consent', 'default', { 'ad_storage': 'denied', 'analytics_storage': 'denied' }); </script> <!-- Global site tag (gtag.js) - Google Analytics --> <script async src='https://www.googletagmanager.com/gtag/js?id=G-01234vwxyz'></script> <script> window.dataLayer = window.dataLayer || []; function gtag(){dataLayer.push(arguments);} gtag('js', new Date()); gtag('config', 'G-01234vwxyz'); /* The custom trackers below can be tailored to match the inputs used in your dashboard. */ $(document).on('change', 'select#selectPhase', function(e) { gtag('event', 'select phase', {'event_category' : 'choose Phase', 'event_label' : document.querySelector('select#selectPhase').value }); }); $(document).on('change', 'select#selectArea', function(e) { gtag('event', 'select area', {'event_category' : 'choose Area', 'event_label' : document.querySelector('select#selectArea').value }); }); $(document).on('click', 'ul#navlistPanel', function(e) { gtag('event', 'navlistPanel', {'event_category' : 'navbar click', 'event_label' : document.querySelector('ul#navlistPanel > li.active > a').getAttribute('data-value') }); }); $(document).on('click', 'ul#tabsetpanels', function(e) { gtag('event', 'tab panels', {'event_category' : 'tab panel clicks', 'event_label' : document.querySelector('ul#tabsetpanels > li.active > a').getAttribute('data-value') }); }); $(document).on('click', 'a#download_data', function(e) { gtag('event', 'Download button', {'event_category' : 'Download button click' }); }); $(document).on('shiny:disconnected', function(e) { gtag('event', 'disconnect', { 'event_label' : 'Disconnect', 'event_category' : 'Disconnect' }); }); </script>
66 changes: 66 additions & 0 deletions inst/google-analytics.hml
cjrace marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<script>
// Define dataLayer and the gtag function.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

// Default ad_storage to 'denied' as a placeholder
// Determine actual values based on your own requirements
gtag('consent', 'default', {
'ad_storage': 'denied',
'analytics_storage': 'denied'
});
</script>

<!-- Global site tag (gtag.js) - Google Analytics -->
<script async src='https://www.googletagmanager.com/gtag/js?id=G-XXXXXXXXXX'></script>
<script>
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}

gtag('js', new Date());

gtag('config', 'G-XXXXXXXXXX');

/*
The custom trackers below can be tailored to match the inputs used in your
dashboard.
*/

$(document).on('change', 'select#selectPhase', function(e) {
gtag('event', 'select phase', {'event_category' : 'choose Phase',
'event_label' : document.querySelector('select#selectPhase').value
});
});

$(document).on('change', 'select#selectArea', function(e) {
gtag('event', 'select area', {'event_category' : 'choose Area',
'event_label' : document.querySelector('select#selectArea').value
});
});

$(document).on('click', 'ul#navlistPanel', function(e) {
gtag('event', 'navlistPanel', {'event_category' : 'navbar click',
'event_label' : document.querySelector('ul#navlistPanel > li.active > a').getAttribute('data-value')
});
});

$(document).on('click', 'ul#tabsetpanels', function(e) {
gtag('event', 'tab panels', {'event_category' : 'tab panel clicks',
'event_label' : document.querySelector('ul#tabsetpanels > li.active > a').getAttribute('data-value')
});
});


$(document).on('click', 'a#download_data', function(e) {
gtag('event', 'Download button', {'event_category' : 'Download button click'
});
});

$(document).on('shiny:disconnected', function(e) {
gtag('event', 'disconnect', {
'event_label' : 'Disconnect',
'event_category' : 'Disconnect'
});
});

</script>
22 changes: 22 additions & 0 deletions man/init_analytics.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

3 changes: 2 additions & 1 deletion man/tidy_code.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions tests/testthat/test-initialise_analytics.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
test_that("Blank code throws error", {
expect_error(initialise_analytics())
})

test_that("Long code throws error", {
expect_error(initialise_analytics("G-qwertyuiop"))
})

test_that("Short code throws error", {
expect_error(initialise_analytics("qwerty"))
})

test_that("Numeric throws error", {
expect_error(initialise_analytics(1234567890))
})
Loading