library(ssh)
## Warning: package 'ssh' was built under R version 4.2.3
## Linking to libssh v0.10.5
#cn <- ssh_connect("cam@analytics-for-cam.vm.statshelix.com")
#ssh_tunnel(cn, port = 5432, target = '10.42.42.1:5432')

#proc <- callr::r_bg(function(){
  #session <- ssh::ssh_connect("cam@analytics-for-cam.vm.statshelix.com")
  #ssh::ssh_tunnel(session, port = 5432, target = '10.42.42.1:5432')
#})
library(DBI)
## Warning: package 'DBI' was built under R version 4.2.3
library(RODBC)
## Warning: package 'RODBC' was built under R version 4.2.3
library(odbc)
## Warning: package 'odbc' was built under R version 4.2.3
library(dplyr)
## Warning: package 'dplyr' was built under R version 4.2.3
## 
## Attaching package: 'dplyr'
## The following objects are masked from 'package:stats':
## 
##     filter, lag
## The following objects are masked from 'package:base':
## 
##     intersect, setdiff, setequal, union
library(dbplyr)
## Warning: package 'dbplyr' was built under R version 4.2.3
## 
## Attaching package: 'dbplyr'
## The following objects are masked from 'package:dplyr':
## 
##     ident, sql
library(jsonlite)
library(lubridate)
## 
## Attaching package: 'lubridate'
## The following objects are masked from 'package:base':
## 
##     date, intersect, setdiff, union
library(ggplot2)
library(plotly)
## 
## Attaching package: 'plotly'
## The following object is masked from 'package:ggplot2':
## 
##     last_plot
## The following object is masked from 'package:stats':
## 
##     filter
## The following object is masked from 'package:graphics':
## 
##     layout
library(tidyr)
## Warning: package 'tidyr' was built under R version 4.2.3
users_input <- dbGetQuery(con, "SELECT * FROM for_cam.users")
events <- dbGetQuery(con, "SELECT * FROM analytics.analytics_track_events")
idles <- dbGetQuery(con, "SELECT * FROM analytics.analytics_events")


#md <- users[4]
#md1 <- apply(md, 1, fromJSON, flatten=T)

data prep

actives <- idles %>%
  filter(!idle) %>%
  mutate(
    active_day = round_date(event_timestamp,unit='day')
  )

users <- users_input %>%
  mutate(
    weekly_cohort = floor_date(created_at, unit='week'),
    monthly_cohort = floor_date(created_at, unit='month')
  )

events_all <- events %>%
  group_by(user_id) %>%
  arrange(event_timestamp) %>%
  mutate(
    event_number = row_number()
  )

events_all <- events_all %>%
  group_by(user_id, session_id) %>%
  arrange(event_timestamp, event_number) %>%
  mutate(
    session_number = row_number()
  )

active_summary <- actives %>%
  group_by(user_id) %>%
  summarize(
    first_active = min(active_day),
    last_active = max(active_day),
    days_active = n_distinct(active_day)
  )

user_activity <- users %>%
  left_join(active_summary, join_by(id == user_id)) %>%
  mutate(
    days_active = ifelse(is.na(days_active), 0, days_active),
    second_day = ifelse(days_active >= 2, TRUE, FALSE),
    third_day = ifelse(days_active >= 3, TRUE, FALSE),
    fourth_day = ifelse(days_active >= 4, TRUE, FALSE),
    fifth_day = ifelse(days_active >= 5, TRUE, FALSE)
  )

Cohort Sizes

cohort_counts_general <- user_activity %>%
  group_by(weekly_cohort) %>%
  summarize(cohort_size = n())

cohort_counts_detail <- user_activity %>%
  group_by(weekly_cohort, days_active) %>%
  summarize(users_with_n_active = n()) #%>%
## `summarise()` has grouped output by 'weekly_cohort'. You can override using the
## `.groups` argument.
  # ungroup(days_active) %>%
  # group_by(weekly_cohort) %>%
  # summarize(cohort_size = n()) %>%
  # ungroup()

cohort_sizes <- ggplot(cohort_counts_general) + geom_bar(aes(x = weekly_cohort, y = cohort_size), stat = 'identity') + theme_minimal()
ggplotly(cohort_sizes)
## Warning: Removed 1 rows containing missing values (position_stack).
cohort_sizes_detail <- ggplot(cohort_counts_detail) + geom_bar(aes(x = weekly_cohort, fill = days_active, y = users_with_n_active), stat = 'identity') + theme_minimal() + scale_fill_viridis_c()
ggplotly(cohort_sizes_detail)
## Warning: Removed 33 rows containing missing values (position_stack).
cohort_sizes_0 <- ggplot(cohort_counts_detail %>% filter(days_active > 0)) + geom_bar(aes(x = weekly_cohort, fill = days_active, y = users_with_n_active), stat = 'identity') + theme_minimal() + scale_fill_viridis_c()
ggplotly(cohort_sizes_0)
## Warning: Removed 32 rows containing missing values (position_stack).

% of users with second/fifth day by weekly cohort

day_percent <- user_activity %>%
  group_by(weekly_cohort) %>%
  summarize(percent_2 = mean(second_day), 
            percent_3 = mean(third_day),
            percent_4 = mean(fourth_day),
            percent_5 = mean(fifth_day))

day_percent_0 <- user_activity %>%
  filter(days_active > 0) %>%
  group_by(weekly_cohort) %>%
  summarize(percent_2 = mean(second_day), 
            percent_3 = mean(third_day),
            percent_4 = mean(fourth_day),
            percent_5 = mean(fifth_day))

day_2_cohort <- ggplot(day_percent) + geom_bar(aes(x = weekly_cohort, y = percent_2), stat= 'identity') + theme_minimal()
day_2_cohort_0 <- ggplot(day_percent_0) + geom_bar(aes(x = weekly_cohort, y = percent_2), stat='identity') + theme_minimal()

ggplotly(day_2_cohort)
## Warning: Removed 1 rows containing missing values (position_stack).
ggplotly(day_2_cohort_0)
## Warning: Removed 1 rows containing missing values (position_stack).
day_5_cohort <- ggplot(day_percent) + geom_bar(aes(x = weekly_cohort, y = percent_5), stat= 'identity') + theme_minimal()
day_5_cohort_0 <- ggplot(day_percent_0) + geom_bar(aes(x = weekly_cohort, y = percent_5), stat='identity') + theme_minimal()

ggplotly(day_5_cohort)
## Warning: Removed 1 rows containing missing values (position_stack).
ggplotly(day_5_cohort_0)
## Warning: Removed 1 rows containing missing values (position_stack).

first day activity

first_day <- actives %>%
  group_by(user_id) %>%
  slice_min(active_day) %>%
  group_by(user_id, session_id, active_day) %>%
  summarize(active_min = n()) %>%
  inner_join(events_all, join_by(user_id, session_id)) %>%
  left_join(active_summary, join_by(user_id))
## `summarise()` has grouped output by 'user_id', 'session_id'. You can override
## using the `.groups` argument.
first_day_wide <- first_day %>%
  group_by(user_id, active_day, active_min, first_active, last_active, days_active, event_type) %>%
  summarize(event_count = n()) %>%
  pivot_wider(names_from = event_type, values_from = event_count, values_fill = 0) %>%
  mutate(across(onboarding:pasteBlock, .fns = list(flag= ~ ifelse(.x > 0, 1,0)))) %>%
  mutate(
    has_second_day = ifelse(days_active > 1, 1,0)
  )
## `summarise()` has grouped output by 'user_id', 'active_day', 'active_min',
## 'first_active', 'last_active', 'days_active'. You can override using the
## `.groups` argument.
library(MASS)
## 
## Attaching package: 'MASS'
## The following object is masked from 'package:plotly':
## 
##     select
## The following object is masked from 'package:dplyr':
## 
##     select
fdw_pred <- first_day_wide %>% ungroup() %>% dplyr::select(!c(user_id, active_day, days_active))
base_model <- glm(has_second_day ~ 1, data = first_day_wide, family=binomial())
scope_model <- glm(has_second_day ~ . -has_second_day , data= fdw_pred, family=binomial())
## Warning: glm.fit: algorithm did not converge
## Warning: glm.fit: fitted probabilities numerically 0 or 1 occurred
step_model <- stepAIC(base_model, direction='both', scope=scope_model, trace=TRUE)
## Start:  AIC=635.01
## has_second_day ~ 1
i1 <- sapply(first_day_wide, is.numeric)
y1 <- "has_second_day" #change it to actual column name
x1 <- setdiff(names(first_day_wide)[i1], y1)
as.data.frame(cor(first_day_wide[x1], first_day_wide[[y1]])) %>% arrange(desc(V1))
##                                            V1
## days_active                       0.416821996
## active_min                        0.356967743
## copyBlock_flag                    0.256111223
## ai-generator_flag                 0.221126736
## ai-generator                      0.218304352
## ai-json-parse-error_flag          0.213558293
## ai                                0.197458955
## createBlock                       0.176407939
## deleteBlock                       0.135723092
## navigate                          0.131825842
## createSheet                       0.118260228
## ai_flag                           0.116611213
## deleteBlock_flag                  0.113790830
## Chart Selection                   0.111321685
## copyBlock                         0.108760326
## import-datasource                 0.105273393
## copySheet                         0.097103340
## publicShareSheet                  0.097103340
## copySheet_flag                    0.097103340
## publicShareSheet_flag             0.097103340
## screen-too-small_flag             0.095898760
## Chart Selection_flag              0.095696673
## deleteSheet_flag                  0.093198267
## ai-json-parse-error               0.085570323
## deleteSheet                       0.076600322
## screen-too-small                  0.070871620
## login                             0.070513418
## ai-optimization-error_flag        0.062657574
## feedback                          0.061425621
## feedback_flag                     0.061425621
## import-datasource_flag            0.058370131
## upload-data-navigation            0.054782268
## tutorial                          0.054046691
## createBlock_flag                  0.046231546
## crash                             0.043677682
## crash_flag                        0.043677682
## tutorial_flag                     0.030872330
## upload-data-navigation_flag       0.021255080
## navigate_flag                     0.018979510
## ai-optimization-error            -0.001751594
## companyChange                    -0.010277751
## createTeam                       -0.010277751
## pasteBlock                       -0.010277751
## companyChange_flag               -0.010277751
## createTeam_flag                  -0.010277751
## pasteBlock_flag                  -0.010277751
## roleChange                       -0.014542194
## roleChange_flag                  -0.014542194
## ai-generate-questions-error      -0.015504143
## ai-generate-questions-error_flag -0.017819380
## shareSheet                       -0.021729501
## signup_agree_terms               -0.023027761
## signup_newsletter                -0.023027761
## signup_role                      -0.023027761
## shareSheet_flag                  -0.023027761
## signup_agree_terms_flag          -0.023027761
## signup_newsletter_flag           -0.023027761
## signup_role_flag                 -0.023027761
## createSheet_flag                 -0.036701970
## onboarding                       -0.155261298
## onboarding_flag                  -0.177157269
mean(first_day_wide$has_second_day)
## [1] 0.09571286

Weekly Active Users

weekly_active <- actives %>%
  mutate(week = floor_date(active_day, unit='week')) %>%
  group_by(user_id, week) %>%
  summarize(active_sessions = n()) %>%
  group_by(week) %>%
  summarize(weekly_active_users = n())
## `summarise()` has grouped output by 'user_id'. You can override using the
## `.groups` argument.
wau <- ggplotly(ggplot(weekly_active) + geom_line(aes(x = week, y = weekly_active_users)) + theme_minimal())

wau

Minutes per Week

weekly_minutes <- actives %>%
  mutate(week = floor_date(active_day, unit='week')) %>%
  group_by(week) %>%
  summarize(active_minutes = n())

minutes <- ggplotly(ggplot(weekly_minutes) + geom_line(aes(x = week, y = active_minutes)) + theme_minimal())

minutes

Minutes per User per Week (Stickiness)

muw <- weekly_active %>% 
  left_join(weekly_minutes, by = join_by(week)) %>%
  mutate(minutes_per_user = active_minutes / weekly_active_users)

muw_plot <- ggplotly(ggplot(muw) + geom_line(aes(x = week, y = minutes_per_user)) + theme_minimal())

muw_plot

Weekly Data Sources (Imports)

events <- events %>%
  mutate(week = floor_date(event_timestamp, unit='week'))

weekly_imports <- events %>%
  filter(event_type == "import-datasource") %>%
  group_by(week, user_id) %>%
  summarize(imports_per_week = n()) %>%
  group_by(week) %>%
  summarize(imports_per_week = sum(imports_per_week), unique_importers = n())
## `summarise()` has grouped output by 'week'. You can override using the
## `.groups` argument.
weekly_imports_plot <- ggplotly(ggplot(weekly_imports) + geom_bar(aes(x = week, y = imports_per_week, fill = unique_importers), stat = 'identity') + theme_minimal())

weekly_imports_plot

Blocks Created

library(purrr)
## Warning: package 'purrr' was built under R version 4.2.3
## 
## Attaching package: 'purrr'
## The following object is masked from 'package:jsonlite':
## 
##     flatten
ai_gen <- events %>%
  filter(event_type == 'ai-generator') %>%
  rowwise() %>% # Apply the following operations row by row
  mutate(parsed_event_data = list(fromJSON(event_data, flatten = TRUE))) %>%
  unnest_wider(parsed_event_data)

human_gen <- events %>%
  filter(event_type == 'createBlock') %>%
  rowwise() %>%
  mutate(parsed_event_data = list(fromJSON(event_data, flatten = TRUE))) %>%
  unnest_wider(parsed_event_data) %>% 
  dplyr::select(-block_connections)

ai_blocks <- ai_gen %>%
  dplyr::select(user_id, session_id, type, event_timestamp, week) %>%
  rename(block_type = type) %>%
  mutate(source = 'ai') %>%
  filter(!is.na(block_type))

human_blocks <- human_gen %>%
  dplyr::select(user_id, session_id, block_type, event_timestamp, week) %>%
  mutate(source = 'human')

all_blocks_created <- human_blocks %>% 
  rbind(ai_blocks) %>%
  as_tibble()

#action = block-created, type has block type
all_blocks_created_compare_plot <- ggplotly(ggplot(all_blocks_created) + geom_bar(aes(x = block_type, fill = block_type)) + facet_wrap(vars(source), nrow=2) + theme_minimal() + theme(axis.title.x=element_blank(),
        axis.text.x=element_blank(),
        axis.ticks.x=element_blank()))

all_blocks_created_compare_plot
all_blocks_created_weekly_plot <- ggplotly(ggplot(all_blocks_created) + geom_bar(aes(x = week, fill = source)) + theme_minimal())

all_blocks_created_weekly_plot
ai_sheet_created <- ai_gen %>%
  filter(action == 'sheet-generation-finished' | action == 'shet-generation-finished') %>%
  dplyr::select(user_id, session_id, event_timestamp, week) %>%
  mutate(source = 'ai')
  

human_sheet_created <- events %>%
  filter(event_type == 'createSheet') %>%
  dplyr::select(user_id, session_id, event_timestamp, week) %>%
  mutate(source = 'human')

all_sheets_created <- human_sheet_created %>%
  rbind(ai_sheet_created)

all_sheets_created_weekly_plot <- ggplotly(ggplot(all_sheets_created) + geom_bar(aes(x = week, fill = source)) + theme_minimal())

all_sheets_created_weekly_plot