Spaces:
Sleeping
Sleeping
Your Name commited on
Commit Β·
eee4ed0
1
Parent(s): 359a85c
Restored ITS module to origianal working order after refactoring codebase.
Browse files1234567891011121314153 unmodified lines19202122232425262728293031323334353637382 unmodified lines4142434445464710 unmodified lines5859606162635 unmodified lines69707172737475767778798081828384858687888990919293949596972 unmodified lines1001011021031041051061071081091101111121131141151 unmodified line1171181191201211221231241251261271281291301311 unmodified line1331341351361371381391401411421431441455 unmodified lines1511521531541551561571581591601611621631641651661671681691701711721731748 unmodified lines18318418518618718818919019119219319419519692 unmodified lines2892902912922932942952962972982993003013023033043053063073083093103113123133143157 unmodified lines3233243253263273283299 unmodified lines33934034134234334434534634734834935035135235335435535635710 unmodified lines3683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983995 unmodified lines4054064074084094104114124134144154164174183 unmodified lines422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533# --- server.R ---function(input, output, session) {data_trigger <- reactiveVal(0)# ββ 1. FAST DATA FETCHING (VIA POOL) ββββββββββββββββββββββββββββββββββββββget_data <- reactive({input$refreshdata_trigger()if (!dbExistsTable(db_pool, "monthly_sales")) return(data.frame())df <- dbGetQuery(db_pool, "SELECT e.primary_name, s.*, EXTRACT(YEAR FROM s.report_date) AS year_numFROM monthly_sales s3 unmodified lines})# ββ 2. UPLOAD βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββobserveEvent(input$process_upload, {req(input$file1)prog <- shiny::Progress$new(message = "Processing...", value = 0.2)on.exit(prog$close())tryCatch({raw <- read_csv(input$file1$datapath, show_col_types = FALSE)clean <- raw %>%mutate(report_date = ym(MoYear),across(c(AmtBid, AmtBooked), ~ as.numeric(gsub("[\\$,]", "", .))),clean_name = case_when(Estimator == "Scott W. Hutchings" ~ "Scott Hutchings",Estimator %in% c("SW", "SH") ~ "Scott Hutchings",TRUE ~ Estimator))dbExecute(db_pool, "CREATE TABLE IF NOT EXISTS estimators (id SERIAL PRIMARY KEY, primary_name VARCHAR(100) UNIQUE NOT NULL, active BOOLEAN DEFAULT TRUE);")dbExecute(db_pool, "CREATE TABLE IF NOT EXISTS monthly_sales (id SERIAL PRIMARY KEY, estimator_id INTEGER REFERENCES estimators(id), report_date DATE NOT NULL, amt_bid NUMERIC(15,2), qty_bid INTEGER, amt_booked NUMERIC(15,2), qty_booked INTEGER, UNIQUE(estimator_id, report_date));")2 unmodified linestryCatch(dbExecute(db_pool, "INSERT INTO estimators (primary_name) VALUES ($1) ON CONFLICT DO NOTHING", params = list(nm)), error = function(e) NULL)est_map <- dbGetQuery(db_pool, "SELECT id, primary_name FROM estimators")upload <- clean %>%left_join(est_map, by = c("clean_name" = "primary_name")) %>%select(estimator_id = id, report_date, amt_bid = AmtBid, qty_bid = QtyBid, amt_booked = AmtBooked, qty_booked = QtyBooked)10 unmodified lines})# ββ FILTERING βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfiltered_data <- reactive({req(input$dateRange)df <- get_data()5 unmodified lines})lag_win_rate <- reactive({df <- filtered_data()lag <- input$win_lagif (nrow(df) == 0 || lag == 0) return(NULL)all_data <- get_data()max_data_date <- max(all_data$report_date, na.rm = TRUE)cutoff_date <- max_data_date %m-% months(lag)bookings_lookup <- df %>% select(primary_name, report_date, amt_booked, qty_booked) %>% rename(book_date = report_date)bid_months <- df %>% select(primary_name, report_date, amt_bid, qty_bid) %>% distinct() %>% filter(report_date <= cutoff_date)if (nrow(bid_months) == 0) return(NULL)result <- bid_months %>%rowwise() %>%mutate(lag_booked_amt = sum(bookings_lookup$amt_booked[bookings_lookup$primary_name == .data$primary_name & bookings_lookup$book_date > report_date & bookings_lookup$book_date <= report_date %m+% months(lag)], na.rm = TRUE),lag_booked_qty = sum(bookings_lookup$qty_booked[bookings_lookup$primary_name == .data$primary_name & bookings_lookup$book_date > report_date & bookings_lookup$book_date <= report_date %m+% months(lag)], na.rm = TRUE)) %>% ungroup()result})# ββ MAIN DROPDOWN UPDATERS ββββββββββββββββββββββββββββββββββββββββββββββββobserve({df <- get_data()if (nrow(df) == 0) return()2 unmodified linesest_list <- sort(unique(df$primary_name))updatePickerInput(session, "estimatorSelect", choices = est_list, selected = isolate(input$estimatorSelect))# Update ITS Sidebar Estimators (Only those with 18+ months history)eligible <- df %>% group_by(primary_name) %>% summarise(n = n(), .groups = "drop") %>% filter(n >= 18) %>% pull(primary_name) %>% sort()updatePickerInput(session, "its_estimator", choices = eligible, selected = if(!is.null(isolate(input$its_estimator))) isolate(input$its_estimator) else eligible[1])yrs <- sort(unique(df$year_num), decreasing = TRUE)cur_yr <- isolate(input$quarter_year_select)updateSelectInput(session, "quarter_year_select", choices = yrs, selected = if (!is.null(cur_yr) && cur_yr %in% yrs) cur_yr else yrs[1])max_dt <- max(df$report_date, na.rm = TRUE)updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))})1 unmodified linedf <- get_data()if (nrow(df) == 0) return()max_dt <- max(df$report_date, na.rm = TRUE)updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))updatePickerInput(session, "estimatorSelect", selected = character(0))updateRadioGroupButtons(session, "view_mode", selected = "Aggregate")updateRadioGroupButtons(session, "time_granularity", selected = "Monthly")updateRadioGroupButtons(session, "annual_granularity", selected = "year")updateRadioGroupButtons(session, "yoy_position", selected = "dodge")updateRadioGroupButtons(session, "trend_series", selected = "booked")updateMaterialSwitch(session, "show_trendline", value = FALSE)updateMaterialSwitch(session, "show_trendline_qty", value = FALSE)updateSliderInput(session, "win_lag", value = 3)})1 unmodified lineoutput$date_verification_table <- renderDataTable({d <- get_data()if (nrow(d) == 0) return(NULL)d %>% arrange(report_date) %>% mutate(`Raw Format (MoYear)` = format(report_date, "%y-%m"), `Parsed Date` = format(report_date, "%B %Y"), `Full Date Stored` = as.character(report_date)) %>% select(Estimator = primary_name, `Raw Format (MoYear)`, `Parsed Date`, `Full Date Stored`) %>% distinct() %>% head(50)}, options = list(pageLength = 10, scrollX = TRUE, dom = "ftp"))output$trend_box_title <- renderText({ paste("Statistical Process Control β", input$time_granularity, "View") })# ββ KPIs ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββoutput$kpi_total_bid <- renderValueBox(valueBox(dollar(sum(filtered_data()$amt_bid, na.rm = TRUE), accuracy = 1), "Total Bid Volume", icon = icon("file-invoice-dollar"), color = "blue"))output$kpi_total_booked <- renderValueBox(valueBox(dollar(sum(filtered_data()$amt_booked, na.rm = TRUE), accuracy = 1), "Total Booked Revenue", icon = icon("money-bill-wave"), color = "green"))output$kpi_win_rate_amt <- renderValueBox({5 unmodified linesoutput$kpi_lag_win_rate <- renderValueBox({lag <- input$win_lagif (lag == 0) return(valueBox("N/A", HTML("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>Set lag > 0 in sidebar</small>"), icon = icon("clock"), color = "purple"))lwr <- lag_win_rate()if (is.null(lwr) || nrow(lwr) == 0) return(valueBox("β", HTML("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>Insufficient complete windows in range</small>"), icon = icon("clock"), color = "purple"))r <- sum(lwr$lag_booked_amt, na.rm = TRUE) / sum(lwr$amt_bid, na.rm = TRUE)max_dt <- max(get_data()$report_date, na.rm = TRUE)cutoff_dt <- max_dt %m-% months(lag)excl_label <- paste0("Bids after ", format(cutoff_dt, "%b %Y"), " excluded (incomplete window)")valueBox(percent(r, 0.1), HTML(paste0("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>", excl_label, "</small>")), icon = icon("clock"), color = "purple")})# ββ CORRELATION INSIGHT βββββββββββββββββββββββββββββββββββββββββββββββββββoutput$correlation_insight <- renderUI({d <- filtered_data()if (nrow(d) < 10) return(tags$p("Waiting for sufficient data points...", class = "text-muted"))if (sd(d$qty_bid, na.rm = TRUE) == 0 || sd(d$amt_booked, na.rm = TRUE) == 0) return(tags$p("Insufficient variance for correlation.", class = "text-muted"))r <- cor(d$qty_bid, d$amt_booked, use = "complete.obs")txt <- if (is.na(r)) {"<span class='insight-text'>β οΈ Data insufficient for Pearson correlation.</span>"8 unmodified lines})# ββ SPC CHARTS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββoutput$trend_dollars <- renderPlotly({d <- filtered_data()req(input$time_granularity, input$view_mode, input$baselineRange)validate(need(nrow(d) > 0, "No data."))is_q <- input$time_granularity == "Quarterly"by_person <- input$view_mode == "Individual"show_both <- isTRUE(input$trend_series == "both")if (by_person) {n <- length(unique(d$primary_name))92 unmodified lines# ββ INTERVENTION ANALYSIS (ITS) ENGINE ββββββββββββββββββββββββββββββββββββits_series <- reactive({df <- get_data()req(nrow(df) > 0, input$its_estimator, input$its_metric)metric <- input$its_metricseries <- df %>%filter(primary_name == input$its_estimator) %>%arrange(report_date) %>%mutate(date_group = floor_date(report_date, "month")) %>%group_by(date_group) %>%summarise(amt_bid = sum(amt_bid, na.rm = TRUE), amt_booked = sum(amt_booked, na.rm = TRUE),qty_booked = sum(qty_booked, na.rm = TRUE), qty_bid = sum(qty_bid, na.rm = TRUE), .groups = "drop") %>%mutate(win_rate = ifelse(amt_bid > 0, amt_booked / amt_bid, NA_real_),value = .data[[metric]],t = row_number()) %>% filter(!is.na(value))series})its_result <- reactiveVal(NULL)its_selected_bp <- reactiveVal(NULL)observeEvent(input$its_breakpoints_table_rows_selected, {7 unmodified lines})observeEvent(input$its_run, {series <- its_series()validate_msg <- NULLif (nrow(series) < 18) validate_msg <- "Need at least 18 monthly observations."if (!is.null(validate_msg)) { its_result(list(error = validate_msg)); return() }9 unmodified linestryCatch({bp_fit <- breakpoints(value ~ t, data = series, h = 6)bp_idx <- bp_fit$breakpointsif (!any(is.na(bp_idx)) && length(bp_idx) > 0) {bp_dates <- series$date_group[bp_idx]fs <- Fstats(value ~ t, data = series)bp_table <- tibble(Date = bp_dates, `Time Index` = bp_idx, `F-Statistic` = round(fs$Fstats[bp_idx], 2),`Months Before` = bp_idx, `Months After` = nrow(series) - bp_idx)}}, error = function(e) NULL)}active_date <- NULLif (!is.null(manual_dt) && !is.na(manual_dt) && manual_dt >= min(series$date_group) && manual_dt <= max(series$date_group)) {active_date <- floor_date(as.Date(manual_dt), "month")} else if (length(bp_dates) > 0) {active_date <- bp_dates[1]10 unmodified linesif (is.null(fit)) { its_result(list(error = "Model could not be fitted. Try a different date.")); return() }cf <- coeftest(fit)cf_df <- as.data.frame(cf) %>% tibble::rownames_to_column("Term") %>%mutate(Term = recode(Term, `(Intercept)` = "Intercept (baseline level)", `t` = "Pre-intervention trend", `D` = "Level change", `t_post` = "Slope change"),Estimate = round(Estimate, 2), `Std Error` = round(`Std. Error`, 2), `t value` = round(`t value`, 3),`p value` = ifelse(`Pr(>|t|)` < 0.001, "< 0.001", as.character(round(`Pr(>|t|)`, 3))),Significant = ifelse(`Pr(>|t|)` < 0.05, "Yes *", "No")) %>%select(Term, Estimate, `Std Error`, `t value`, `p value`, Significant)model_df <- model_df %>% mutate(fitted = fitted(fit), resid = residuals(fit), counterfact = coef(fit)[1] + coef(fit)[2] * t)pre <- model_df %>% filter(t <= t0)post <- model_df %>% filter(t >= t0)b2 <- coef(fit)["D"]; b3 <- coef(fit)["t_post"]; p2 <- cf[3, 4]; p3 <- cf[4, 4]level_txt <- if (p2 < 0.05) {dir <- if (b2 > 0) "increased" else "decreased"paste0("The outcome ", dir, " immediately by ", if (metric %in% c("amt_booked","amt_bid")) dollar(abs(round(b2))) else round(abs(b2), 1), " at the intervention point (p = ", round(p2, 3), ").")} else { paste0("No significant immediate level change detected (p = ", round(p2, 3), ").") }slope_txt <- if (p3 < 0.05) {dir <- if (b3 > 0) "accelerated" else "decelerated"paste0("The monthly trajectory ", dir, " by ", if (metric %in% c("amt_booked","amt_bid")) dollar(abs(round(b3))) else round(abs(b3), 3), " per month after the intervention (p = ", round(p3, 3), ").")} else { paste0("No significant change in monthly trajectory detected (p = ", round(p3, 3), ").") }overall <- if (p2 < 0.05 || p3 < 0.05) "Significant intervention effect detected." else "No statistically significant intervention effect detected."its_result(list(series = model_df, pre = pre, post = post, fit = fit, coef_df = cf_df, breakpoints = bp_table, active_date = active_date, t0 = t0, metric = metric, estimator = input$its_estimator, level_txt = level_txt, slope_txt = slope_txt, overall = overall, r2 = round(summary(fit)$r.squared, 3), autodetect = autodetect))})output$its_summary_ui <- renderUI({5 unmodified linestagList(tags$table(style = "width:100%; border-collapse:collapse; font-size:13px;",tags$tr(tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50; width:40%;", "Estimator"), tags$td(style = "padding:6px 10px; color:#5A6A72;", res$estimator)),tags$tr(style = "background:#f4f6f9;", tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50;", "Outcome Metric"), tags$td(style = "padding:6px 10px; color:#5A6A72;", metric_label[res$metric])),tags$tr(tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50;", "Intervention Date"), tags$td(style = "padding:6px 10px; color:#5A6A72;", format(res$active_date, "%B %Y"), if (!is.null(input$its_manual_date) && !is.na(input$its_manual_date) && floor_date(as.Date(input$its_manual_date), "month") == res$active_date) tags$span(" (manager-specified)", style = "color:#e67e22; font-size:11px;") else tags$span(" (auto-detected)", style = "color:#27ae60; font-size:11px;"))),tags$tr(style = "background:#f4f6f9;", tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50;", "Model R\u00b2"), tags$td(style = "padding:6px 10px; color:#5A6A72;", res$r2))),tags$hr(style = "margin:12px 0;"),tags$p(style = "font-size:13px; color:#2c3e50; font-weight:600;", res$overall),tags$p(style = "font-size:12px; color:#5A6A72; margin:4px 0;", tags$b("Level change: "), res$level_txt),tags$p(style = "font-size:12px; color:#5A6A72; margin:4px 0;", tags$b("Slope change: "), res$slope_txt))})3 unmodified linesif (is.null(res) || !is.null(res$error)) return(plotly_empty())series <- res$series; pre <- res$pre; post <- res$post; metric <- res$metricfmt <- if (metric %in% c("amt_booked","amt_bid")) function(x) dollar(round(x)) else if (metric == "win_rate") function(x) percent(x, 0.1) else function(x) comma(round(x))y_label <- c(amt_booked="Booked Revenue ($)", amt_bid="Bid Volume ($)", qty_booked="Jobs Booked", win_rate="Win Rate")[metric]p <- ggplot(series, aes(x = date_group)) +geom_point(aes(y = value, text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>Actual: ", fmt(value))), color = "#95a5a6", size = 2.2, alpha = 0.8) +geom_line(aes(y = counterfact), color = "#c0392b", linetype = "dotted", linewidth = 0.7, alpha = 0.6) +geom_line(data = pre, aes(y = fitted), color = "#2980b9", linewidth = 1.1) +geom_line(data = post, aes(y = fitted), color = "#27ae60", linewidth = 1.1) +geom_vline(xintercept = as.numeric(res$active_date), color = "#e67e22", linetype = "dashed", linewidth = 0.9) +annotate("text", x = res$active_date, y = max(series$value, na.rm = TRUE) * 0.95, label = paste("Intervention\n", format(res$active_date, "%b %Y")), hjust = -0.08, size = 3, color = "#e67e22") +scale_y_continuous(labels = if (metric %in% c("amt_booked","amt_bid")) dollar_format(accuracy = 1) else if (metric == "win_rate") percent_format(accuracy = 1) else comma_format(accuracy = 1)) +labs(x = NULL, y = y_label, title = paste0(res$estimator, " β ITS: ", y_label), caption = "Blue = pre-int. trend | Green = post-int. trend | Red dotted = counterfactual") +theme_minimal() + theme(plot.caption = element_text(size = 8, color = "#95a5a6"), plot.title = element_text(size = 12, face = "bold", color = "#2c3e50"))ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h"))})output$its_breakpoints_table <- renderDataTable({res <- its_result(); if (is.null(res) || !is.null(res$error)) return(NULL)if (is.null(res$breakpoints) || nrow(res$breakpoints) == 0) return(data.frame(Message = "No significant breakpoints detected automatically."))res$breakpoints %>% mutate(Date = format(Date, "%B %Y")) %>% arrange(desc(`F-Statistic`))}, selection = "single", options = list(dom = "t", pageLength = 10, scrollX = TRUE))output$its_coef_table <- renderDataTable({res <- its_result(); if (is.null(res) || !is.null(res$error)) return(NULL); res$coef_df}, options = list(dom = "t", pageLength = 10, scrollX = TRUE))# ββ ADVANCED ANALYTICS (FUNNEL & HEATMAP) βββββββββββββββββββββββββββββββββoutput$bid_funnel_chart <- renderPlotly({d <- filtered_data(); validate(need(nrow(d) > 0, "No data."))funnel <- d %>% group_by(primary_name) %>% summarise(Bid = sum(amt_bid, na.rm = TRUE), Booked = sum(amt_booked, na.rm = TRUE), .groups = "drop") %>% filter(Bid > 0) %>% mutate(Win_Rate = Booked / Bid, primary_name = fct_reorder(primary_name, Bid)) %>% pivot_longer(c(Bid, Booked), names_to = "Type", values_to = "Amount") %>% mutate(Win_Label = ifelse(Type == "Booked", paste0(percent(Win_Rate, 0.1), " win rate"), NA_character_))p <- ggplot(funnel, aes(x = primary_name, y = Amount, fill = Type, text = paste0("<b>", primary_name, "</b><br>", Type, ": ", dollar(Amount, accuracy = 1), ifelse(!is.na(Win_Label), paste0("<br>", Win_Label), "")))) + geom_col(position = "dodge", width = 0.65) + geom_text(aes(label = Win_Label), position = position_dodge(width = 0.65), hjust = -0.1, size = 3, na.rm = TRUE, color = "#2c3e50") + scale_fill_manual(values = c("Bid" = "#95a5a6", "Booked" = "#27ae60")) + scale_y_continuous(labels = dollar_format(accuracy = 1), expand = expansion(mult = c(0, 0.25))) + coord_flip() + labs(x = "", y = "Amount ($)", fill = "") + theme_minimal() + theme(legend.position = "top", panel.grid.major.y = element_blank())ggplotly(p, tooltip = "text")})output$seasonality_heatmap <- renderPlotly({df <- get_data(); sel <- input$estimatorSelectif (!is.null(sel) && length(sel) > 0) df <- df %>% filter(primary_name %in% sel)validate(need(nrow(df) > 0, "No data."))hm_metric <- if(!is.null(input$heatmap_metric)) input$heatmap_metric else "amt_booked"metric_sym <- sym(hm_metric); metric_label <- if(hm_metric == "amt_booked") "Booked ($)" else "Bid ($)"heat <- df %>% mutate(Month = month(report_date, label = TRUE, abbr = TRUE), Year = as.integer(year(report_date))) %>% group_by(Year, Month) %>% summarise(Value = sum(!!metric_sym, na.rm = TRUE), .groups = "drop") %>% complete(Year, Month, fill = list(Value = 0)) %>% mutate(Month = factor(Month, levels = rev(month.abb)))p <- ggplot(heat, aes(x = factor(Year), y = Month, fill = Value, text = paste0("<b>", Month, " ", Year, "</b><br>", metric_label, ": ", dollar(Value, accuracy = 1)))) + geom_tile(color = "white", linewidth = 0.4) + scale_fill_gradient(low = "#eaf4fb", high = if(hm_metric == "amt_booked") "#1a5276" else "#7f8c8d", labels = dollar_format(scale = 1e-3, suffix = "K", accuracy = 1), name = metric_label) + labs(x = "Year", y = "") + theme_minimal() + theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank(), legend.position = "right")ggplotly(p, tooltip = "text")})# ββ K-MEANS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββoutput$scatter_matrix <- renderPlotly({dat <- filtered_data(); validate(need(nrow(dat) > 0, "Upload data to begin.")); lwr <- lag_win_rate()ds_df <- dat %>% group_by(primary_name) %>% summarise(Total_Bid = sum(amt_bid, na.rm = TRUE), Total_Booked = sum(amt_booked, na.rm = TRUE), Jobs_Bid = sum(qty_bid, na.rm = TRUE), .groups = "drop") %>% mutate(Avg_Job_Size = Total_Bid / Jobs_Bid, Win_Rate_SM = Total_Booked / Total_Bid)if (!is.null(lwr) && nrow(lwr) > 0) { lag_summary <- lwr %>% group_by(primary_name) %>% summarise(Lag_Win_Rate = sum(lag_booked_amt, na.rm = TRUE) / sum(amt_bid, na.rm = TRUE), .groups = "drop"); ds_df <- ds_df %>% left_join(lag_summary, by = "primary_name") %>% mutate(Win_Rate = coalesce(Lag_Win_Rate, Win_Rate_SM)) } else { ds_df$Win_Rate <- ds_df$Win_Rate_SM }ds_df <- ds_df %>% filter(Total_Bid > 0, !is.na(Win_Rate), !is.infinite(Win_Rate), !is.na(Avg_Job_Size), !is.infinite(Avg_Job_Size)); validate(need(nrow(ds_df) >= 3, "Need at least 3 active estimators to cluster."))set.seed(42)if (any(sapply(ds_df[, c("Total_Bid", "Win_Rate", "Avg_Job_Size")], function(x) sd(x, na.rm = TRUE) == 0))) { ds_df$Archetype <- "Archetype 1" } else { feats <- ds_df %>% select(Total_Bid, Win_Rate, Avg_Job_Size) %>% scale(); k <- min(3, nrow(ds_df) - 1); km <- kmeans(feats, centers = k, nstart = 25); ds_df$Cluster <- as.factor(km$cluster); cl_means <- ds_df %>% group_by(Cluster) %>% summarise(mean_wr = mean(Win_Rate, na.rm = TRUE), .groups = "drop") %>% arrange(desc(mean_wr)); arch_map <- setNames(c("High-Efficiency", "Selective", "High-Volume")[seq_len(nrow(cl_means))], cl_means$Cluster); ds_df$Archetype <- arch_map[as.character(ds_df$Cluster)] }p <- ggplot(ds_df, aes(x = Total_Bid, y = Win_Rate, color = Archetype, size = Total_Booked, text = paste0("<b>", primary_name, "</b><br>", "Archetype: ", Archetype, "<br>", "Pipeline Effort: ", dollar(Total_Bid, 1), "<br>", "Win Rate: ", percent(Win_Rate, 0.1), "<br>", "Avg Job Size: ", dollar(Avg_Job_Size, 1), "<br>", "Total Booked: ", dollar(Total_Booked, 1)))) + geom_point(alpha = 0.85) + scale_color_manual(values = c("High-Efficiency" = "#27ae60", "Selective" = "#f39c12", "High-Volume" = "#e74c3c")) + scale_x_continuous(labels = dollar_format(accuracy = 1)) + scale_y_continuous(labels = percent_format(accuracy = 1)) + labs(x = "Total Amount Bid", y = "Win Rate", color = "Archetype") + theme_minimal() + theme(legend.position = "right")ggplotly(p, tooltip = "text")})# ββ ANNUAL, YOY, QUARTERLY ββββββββββββββββββββββββββββββββββββββββββββββββoutput$annual_bar_chart <- renderPlotly({d <- filtered_data(); validate(need(nrow(d) > 0, "No data.")); gran <- input$annual_granularity; by_person <- !is.null(input$estimatorSelect) && length(input$estimatorSelect) <= 5d <- d %>% mutate(x_group = case_when(gran == "year" ~ as.character(year(report_date)), gran == "quarter" ~ paste0(year(report_date), " Q", quarter(report_date)), gran == "month" ~ format(report_date, "%Y-%m"), TRUE ~ as.character(year(report_date)))); x_levels <- d %>% arrange(report_date) %>% pull(x_group) %>% unique(); d <- d %>% mutate(x_group = factor(x_group, levels = x_levels))if (by_person) { annual <- d %>% group_by(x_group, primary_name) %>% summarise(Booked = sum(amt_booked, na.rm = TRUE), .groups = "drop"); p <- ggplot(annual, aes(x_group, Booked, fill = primary_name, text = paste0("<b>", x_group, "</b><br>", primary_name, "<br>", dollar(round(Booked), accuracy = 1)))) + geom_col(position = "dodge") + scale_fill_brewer(palette = "Paired")} else { annual <- d %>% group_by(x_group) %>% summarise(Bid = sum(amt_bid, na.rm = TRUE), Booked = sum(amt_booked, na.rm = TRUE), .groups = "drop") %>% pivot_longer(c(Bid, Booked), names_to = "Type", values_to = "Value"); p <- ggplot(annual, aes(x_group, Value, fill = Type, text = paste0("<b>", x_group, "</b><br>", Type, ": ", dollar(round(Value), accuracy = 1)))) + geom_col(position = "dodge") + scale_fill_manual(values = c("Bid" = "#95a5a6", "Booked" = "#27ae60")) }ggplotly(p + scale_y_continuous(labels = dollar_format(accuracy = 1)) + labs(x = "", y = "", fill = "") + theme_minimal() + theme(axis.text.x = element_text(angle = if (gran != "year") 45 else 0, hjust = 1)), tooltip = "text")})output$yoy_chart <- renderPlotly({d <- filtered_data(); req(input$yoy_metric, input$view_mode); validate(need(nrow(d) > 0, "No data.")); msym <- sym(input$yoy_metric); bar_pos <- input$yoy_positionif (input$view_mode == "Individual") { validate(need(length(unique(d$primary_name)) <= 10, "Select 10 or fewer estimators for Individual YoY.")); ag <- d %>% group_by(year_num, primary_name) %>% summarise(V = sum(!!msym, na.rm = TRUE), .groups = "drop") %>% arrange(year_num) %>% group_by(primary_name) %>% mutate(G = (V - lag(V)) / lag(V)) %>% filter(!is.na(G)); p <- ggplot(ag, aes(factor(year_num), G, fill = primary_name, text = paste0(year_num, " β ", primary_name, "<br>Growth: ", percent(G, 0.1)))) + geom_col(position = bar_pos) + scale_fill_brewer(palette = "Paired")} else { ag <- d %>% group_by(year_num) %>% summarise(V = sum(!!msym, na.rm = TRUE), .groups = "drop") %>% arrange(year_num) %>% mutate(G = (V - lag(V)) / lag(V)) %>% filter(!is.na(G)); p <- ggplot(ag, aes(factor(year_num), G, fill = G > 0, text = paste0(year_num, "<br>Growth: ", percent(G, 0.1)))) + geom_col(show.legend = FALSE) + scale_fill_manual(values = c("TRUE" = "#27ae60", "FALSE" = "#c0392b")) }ggplotly(p + geom_hline(yintercept = 0) + scale_y_continuous(labels = percent_format()) + labs(x = "Year", y = "Growth %") + theme_minimal(), tooltip = "text")})output$quarterly_breakdown_chart <- renderPlotly({d <- filtered_data(); req(input$quarter_year_select); validate(need(nrow(d) > 0, "No data.")); q <- d %>% filter(year_num == as.numeric(input$quarter_year_select)) %>% mutate(Quarter = paste0("Q", quarter(report_date))) %>% group_by(Quarter) %>% summarise(Revenue = sum(amt_booked, na.rm = TRUE), .groups = "drop"); p <- ggplot(q, aes(Quarter, Revenue, text = paste0(Quarter, "<br>", dollar(Revenue, 1)))) + geom_col(fill = "#3c8dbc", width = 0.6) + scale_y_continuous(labels = dollar_format(accuracy = 1)) + labs(x = "", y = "Revenue ($)") + theme_minimal() + theme(panel.grid.major.x = element_blank()); ggplotly(p, tooltip = "text")})# ββ LEADERBOARD & EXPORT ββββββββββββββββββββββββββββββββββββββββββββββββββoutput$leaderboard_table <- renderDataTable({d <- filtered_data(); if (nrow(d) == 0) return(NULL); lb <- d %>% group_by(primary_name) %>% summarise(Total_Bids = sum(amt_bid, na.rm = TRUE), Total_Booked = sum(amt_booked, na.rm = TRUE), Jobs_Won = sum(qty_booked, na.rm = TRUE), Jobs_Bid = sum(qty_bid, na.rm = TRUE), .groups = "drop") %>% mutate(Win_Rate = Total_Booked / Total_Bids, Avg_Job_Size = Total_Bids / Jobs_Bid)if (input$win_lag > 0) { lwr <- lag_win_rate(); if (!is.null(lwr)) { lag_col <- lwr %>% group_by(primary_name) %>% summarise(Lag_WR = sum(lag_booked_amt, na.rm = TRUE) / sum(amt_bid, na.rm = TRUE), .groups = "drop"); lb <- lb %>% left_join(lag_col, by = "primary_name") } }lb <- lb %>% mutate(Total_Bids = dollar(Total_Bids, accuracy = 1), Total_Booked = dollar(Total_Booked, accuracy = 1), Win_Rate = percent(Win_Rate, accuracy = 0.1), Avg_Job_Size = dollar(Avg_Job_Size, accuracy = 1)) %>% rename(Estimator = primary_name, `Total Revenue` = Total_Booked, `Total Bids` = Total_Bids, `Win % (same-mo)` = Win_Rate, `Jobs Won` = Jobs_Won, `Jobs Bid` = Jobs_Bid, `Avg Job Size` = Avg_Job_Size)if ("Lag_WR" %in% names(lb)) lb <- lb %>% mutate(Lag_WR = percent(Lag_WR, accuracy = 0.1)) %>% rename(`Win % (lag-adj)` = Lag_WR)datatable(lb, options = list(pageLength = 15, scrollX = TRUE, order = list(list(2, "desc"))), rownames = FALSE)})output$db_status_text <- renderText({ paste("Database records loaded:", comma(nrow(get_data()))) })output$preview_table <- renderDataTable({ d <- get_data(); if (nrow(d) == 0) return(NULL); d %>% arrange(desc(report_date)) %>% head(5) %>% select(Estimator = primary_name, Date = report_date, Bid = amt_bid, Booked = amt_booked) }, options = list(dom = "t", searching = FALSE))output$download_report <- downloadHandler(filename = function() { paste0("Estimator_Intelligence_", format(Sys.Date(), "%Y-%m-%d"), ".xlsx") },content = function(file) {d <- filtered_data(); req(nrow(d) > 0)withProgress(message = "Building Excel reportβ¦", value = 0.2, {wb <- createWorkbook(); header_style <- createStyle(fontName="Calibri",fontSize=11,fontColour="#FFFFFF",fgFill="#2c3e50",halign="LEFT",valign="CENTER",textDecoration="bold",border="Bottom",borderColour="#27ae60"); title_style <- createStyle(fontName="Calibri",fontSize=14,textDecoration="bold",fontColour="#2c3e50"); alt_row_style <- createStyle(fgFill="#f4f6f9"); dollar_style <- createStyle(numFmt="$#,##0"); pct_style <- createStyle(numFmt="0.0%")addWorksheet(wb,"Summary"); setColWidths(wb,"Summary",cols=1:3,widths=c(30,22,22)); writeData(wb,"Summary","Estimator Intelligence Report",startRow=1,startCol=1); addStyle(wb,"Summary",title_style,rows=1,cols=1)sel_label <- if (is.null(isolate(input$estimatorSelect))||length(isolate(input$estimatorSelect))==0)"All Estimators" else paste(isolate(input$estimatorSelect),collapse=", ")meta <- data.frame(Field=c("Reporting Period","Estimator Scope","Win Rate Lag","Generated"),Value=c(paste(format(isolate(input$dateRange[1]),"%b %d %Y"),"β",format(isolate(input$dateRange[2]),"%b %d %Y")),sel_label,paste(isolate(input$win_lag),"month(s)"),format(Sys.Date(),"%B %d, %Y")),stringsAsFactors=F)writeData(wb,"Summary",meta,startRow=3,startCol=1,colNames=F)kpi_data <- data.frame(Metric=c("Total Bid Volume","Total Booked Revenue","Dollar Win Rate","Active Estimators"),Value=c(dollar(sum(d$amt_bid,na.rm=T),accuracy=1),dollar(sum(d$amt_booked,na.rm=T),accuracy=1),percent(sum(d$amt_booked,na.rm=T)/sum(d$amt_bid,na.rm=T),accuracy=0.1),as.character(length(unique(d$primary_name)))),stringsAsFactors=F)writeData(wb,"Summary",kpi_data,startRow=9,startCol=1,colNames=T);addStyle(wb,"Summary",header_style,rows=9,cols=1:2)addWorksheet(wb,"Leaderboard"); setColWidths(wb,"Leaderboard",cols=1:7,widths=c(22,18,18,10,10,14,14)); lb_raw <- d %>% group_by(Estimator=primary_name) %>% summarise(`Total Bids`=sum(amt_bid,na.rm=T),`Total Revenue`=sum(amt_booked,na.rm=T),`Jobs Bid`=sum(qty_bid,na.rm=T),`Jobs Won`=sum(qty_booked,na.rm=T),`Win Rate`=`Total Revenue`/`Total Bids`,`Avg Job Size`=`Total Bids`/`Jobs Bid`,.groups="drop") %>% arrange(desc(`Total Revenue`)); writeData(wb,"Leaderboard",lb_raw,startRow=1,colNames=T);addStyle(wb,"Leaderboard",header_style,rows=1,cols=1:7);addStyle(wb,"Leaderboard",dollar_style,rows=2:(nrow(lb_raw)+1),cols=c(2,3,7),gridExpand=T);addStyle(wb,"Leaderboard",pct_style,rows=2:(nrow(lb_raw)+1),cols=6,gridExpand=T)setProgress(0.6)addWorksheet(wb,"Monthly Detail"); setColWidths(wb,"Monthly Detail",cols=1:7,widths=c(22,14,14,10,14,10,14)); monthly_raw <- d %>% arrange(primary_name,report_date) %>% mutate(Date=format(report_date,"%b %Y"),Win_Rate=ifelse(amt_bid>0,amt_booked/amt_bid,0)) %>% select(Estimator=primary_name,Date,`Bid ($)`=amt_bid,`Jobs Bid`=qty_bid,`Booked ($)`=amt_booked,`Jobs Won`=qty_booked,`Win Rate`=Win_Rate); writeData(wb,"Monthly Detail",monthly_raw,startRow=1,colNames=T);addStyle(wb,"Monthly Detail",header_style,rows=1,cols=1:7);addStyle(wb,"Monthly Detail",dollar_style,rows=2:(nrow(monthly_raw)+1),cols=c(3,5),gridExpand=T);addStyle(wb,"Monthly Detail",pct_style,rows=2:(nrow(monthly_raw)+1),cols=7,gridExpand=T)setProgress(0.9); saveWorkbook(wb,file,overwrite=T)})})1234567891011121314153 unmodified lines19202122232425262728293031323334353637382 unmodified lines4142434445464710 unmodified lines585960616263645 unmodified lines70717273747576777879808182838485868788899091929394952 unmodified lines98991001011021031041051061071081091101111121131141151161171181191201211221231241251 unmodified line1271281291301311321331341351361371381391401411 unmodified line1431441451461471481491501511521531541551561571581591601611625 unmodified lines1681691701711721731741751761771781791801811821831841851861871888 unmodified lines19719819920020120220320420520620720820921092 unmodified lines3033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343357 unmodified lines3433443453463473483493503513523533543553563573583593609 unmodified lines37037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640710 unmodified lines4184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934945 unmodified lines5005015025035045055065075085095105115125135145155165175185195205215225235245255265273 unmodified lines531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919# --- server.R ---function(input, output, session) {data_trigger <- reactiveVal(0)# ββ 1. FAST DATA FETCHING (VIA POOL) ββββββββββββββββββββββββββββββββββββββget_data <- reactive({input$refreshdata_trigger()if (!dbExistsTable(db_pool, "monthly_sales")) return(data.frame())df <- dbGetQuery(db_pool, "SELECT e.primary_name, s.*, EXTRACT(YEAR FROM s.report_date) AS year_numFROM monthly_sales s3 unmodified lines})# ββ 2. UPLOAD βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββobserveEvent(input$process_upload, {req(input$file1)prog <- shiny::Progress$new(message = "Processing...", value = 0.2)on.exit(prog$close())tryCatch({raw <- read_csv(input$file1$datapath, show_col_types = FALSE)clean <- raw %>%mutate(report_date = ym(MoYear),across(c(AmtBid, AmtBooked), ~ as.numeric(gsub("[\\$,]", "", .))),clean_name = case_when(Estimator == "Scott W. Hutchings" ~ "Scott Hutchings",Estimator %in% c("SW", "SH") ~ "Scott Hutchings",TRUE ~ Estimator))dbExecute(db_pool, "CREATE TABLE IF NOT EXISTS estimators (id SERIAL PRIMARY KEY, primary_name VARCHAR(100) UNIQUE NOT NULL, active BOOLEAN DEFAULT TRUE);")dbExecute(db_pool, "CREATE TABLE IF NOT EXISTS monthly_sales (id SERIAL PRIMARY KEY, estimator_id INTEGER REFERENCES estimators(id), report_date DATE NOT NULL, amt_bid NUMERIC(15,2), qty_bid INTEGER, amt_booked NUMERIC(15,2), qty_booked INTEGER, UNIQUE(estimator_id, report_date));")2 unmodified linestryCatch(dbExecute(db_pool, "INSERT INTO estimators (primary_name) VALUES ($1) ON CONFLICT DO NOTHING", params = list(nm)), error = function(e) NULL)est_map <- dbGetQuery(db_pool, "SELECT id, primary_name FROM estimators")upload <- clean %>%left_join(est_map, by = c("clean_name" = "primary_name")) %>%select(estimator_id = id, report_date, amt_bid = AmtBid, qty_bid = QtyBid, amt_booked = AmtBooked, qty_booked = QtyBooked)10 unmodified lines})# ββ FILTERING βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββfiltered_data <- reactive({req(input$dateRange)df <- get_data()5 unmodified lines})lag_win_rate <- reactive({df <- filtered_data()lag <- input$win_lagif (nrow(df) == 0 || lag == 0) return(NULL)all_data <- get_data()max_data_date <- max(all_data$report_date, na.rm = TRUE)cutoff_date <- max_data_date %m-% months(lag)bookings_lookup <- df %>% select(primary_name, report_date, amt_booked, qty_booked) %>% rename(book_date = report_date)bid_months <- df %>% select(primary_name, report_date, amt_bid, qty_bid) %>% distinct() %>% filter(report_date <= cutoff_date)if (nrow(bid_months) == 0) return(NULL)result <- bid_months %>%rowwise() %>%mutate(lag_booked_amt = sum(bookings_lookup$amt_booked[bookings_lookup$primary_name == .data$primary_name & bookings_lookup$book_date > report_date & bookings_lookup$book_date <= report_date %m+% months(lag)], na.rm = TRUE),lag_booked_qty = sum(bookings_lookup$qty_booked[bookings_lookup$primary_name == .data$primary_name & bookings_lookup$book_date > report_date & bookings_lookup$book_date <= report_date %m+% months(lag)], na.rm = TRUE)) %>% ungroup()result})# ββ MAIN DROPDOWN UPDATERS ββββββββββββββββββββββββββββββββββββββββββββββββobserve({df <- get_data()if (nrow(df) == 0) return()2 unmodified linesest_list <- sort(unique(df$primary_name))updatePickerInput(session, "estimatorSelect", choices = est_list, selected = isolate(input$estimatorSelect))# ββ BUG FIX 1: its_estimator auto-selection βββββββββββββββββββββββββββ# pickerInput returns character(0) (NOT NULL) when empty, so !is.null() always# passed and selected = character(0) was being sent, leaving nothing pre-selected.# Now we check length() > 0 AND that the current value is still a valid choice.eligible <- df %>%group_by(primary_name) %>%summarise(n = n(), .groups = "drop") %>%filter(n >= 18) %>%pull(primary_name) %>%sort()cur_its <- isolate(input$its_estimator)selected_its <- if (length(cur_its) > 0 && cur_its %in% eligible) cur_its else eligible[1]updatePickerInput(session, "its_estimator", choices = eligible, selected = selected_its)# ββ END BUG FIX 1 ββββββββββββββββββββββββββββββββββββββββββββββββββββyrs <- sort(unique(df$year_num), decreasing = TRUE)cur_yr <- isolate(input$quarter_year_select)updateSelectInput(session, "quarter_year_select", choices = yrs, selected = if (!is.null(cur_yr) && cur_yr %in% yrs) cur_yr else yrs[1])max_dt <- max(df$report_date, na.rm = TRUE)updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))})1 unmodified linedf <- get_data()if (nrow(df) == 0) return()max_dt <- max(df$report_date, na.rm = TRUE)updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))updatePickerInput(session, "estimatorSelect", selected = character(0))updateRadioGroupButtons(session, "view_mode", selected = "Aggregate")updateRadioGroupButtons(session, "time_granularity", selected = "Monthly")updateRadioGroupButtons(session, "annual_granularity", selected = "year")updateRadioGroupButtons(session, "yoy_position", selected = "dodge")updateRadioGroupButtons(session, "trend_series", selected = "booked")updateMaterialSwitch(session, "show_trendline", value = FALSE)updateMaterialSwitch(session, "show_trendline_qty", value = FALSE)updateSliderInput(session, "win_lag", value = 3)})1 unmodified lineoutput$date_verification_table <- renderDataTable({d <- get_data()if (nrow(d) == 0) return(NULL)d %>% arrange(report_date) %>%mutate(`Raw Format (MoYear)` = format(report_date, "%y-%m"),`Parsed Date` = format(report_date, "%B %Y"),`Full Date Stored` = as.character(report_date)) %>%select(Estimator = primary_name, `Raw Format (MoYear)`, `Parsed Date`, `Full Date Stored`) %>%distinct() %>% head(50)}, options = list(pageLength = 10, scrollX = TRUE, dom = "ftp"))output$trend_box_title <- renderText({ paste("Statistical Process Control β", input$time_granularity, "View") })# ββ KPIs ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββoutput$kpi_total_bid <- renderValueBox(valueBox(dollar(sum(filtered_data()$amt_bid, na.rm = TRUE), accuracy = 1), "Total Bid Volume", icon = icon("file-invoice-dollar"), color = "blue"))output$kpi_total_booked <- renderValueBox(valueBox(dollar(sum(filtered_data()$amt_booked, na.rm = TRUE), accuracy = 1), "Total Booked Revenue", icon = icon("money-bill-wave"), color = "green"))output$kpi_win_rate_amt <- renderValueBox({5 unmodified linesoutput$kpi_lag_win_rate <- renderValueBox({lag <- input$win_lagif (lag == 0) return(valueBox("N/A", HTML("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>Set lag > 0 in sidebar</small>"), icon = icon("clock"), color = "purple"))lwr <- lag_win_rate()if (is.null(lwr) || nrow(lwr) == 0) return(valueBox("β", HTML("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>Insufficient complete windows in range</small>"), icon = icon("clock"), color = "purple"))r <- sum(lwr$lag_booked_amt, na.rm = TRUE) / sum(lwr$amt_bid, na.rm = TRUE)max_dt <- max(get_data()$report_date, na.rm = TRUE)cutoff_dt <- max_dt %m-% months(lag)excl_label <- paste0("Bids after ", format(cutoff_dt, "%b %Y"), " excluded (incomplete window)")valueBox(percent(r, 0.1), HTML(paste0("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>", excl_label, "</small>")), icon = icon("clock"), color = "purple")})# ββ CORRELATION INSIGHT βββββββββββββββββββββββββββββββββββββββββββββββββββoutput$correlation_insight <- renderUI({d <- filtered_data()if (nrow(d) < 10) return(tags$p("Waiting for sufficient data points...", class = "text-muted"))if (sd(d$qty_bid, na.rm = TRUE) == 0 || sd(d$amt_booked, na.rm = TRUE) == 0) return(tags$p("Insufficient variance for correlation.", class = "text-muted"))r <- cor(d$qty_bid, d$amt_booked, use = "complete.obs")txt <- if (is.na(r)) {"<span class='insight-text'>β οΈ Data insufficient for Pearson correlation.</span>"8 unmodified lines})# ββ SPC CHARTS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββoutput$trend_dollars <- renderPlotly({d <- filtered_data()req(input$time_granularity, input$view_mode, input$baselineRange)validate(need(nrow(d) > 0, "No data."))is_q <- input$time_granularity == "Quarterly"by_person <- input$view_mode == "Individual"show_both <- isTRUE(input$trend_series == "both")if (by_person) {n <- length(unique(d$primary_name))92 unmodified lines# ββ INTERVENTION ANALYSIS (ITS) ENGINE ββββββββββββββββββββββββββββββββββββits_series <- reactive({df <- get_data()metric <- input$its_metricreq(nrow(df) > 0, input$its_estimator, metric)series <- df %>%filter(primary_name == input$its_estimator) %>%arrange(report_date) %>%mutate(date_group = floor_date(report_date, "month")) %>%group_by(date_group) %>%summarise(amt_bid = sum(amt_bid, na.rm = TRUE),amt_booked = sum(amt_booked, na.rm = TRUE),qty_booked = sum(qty_booked, na.rm = TRUE),qty_bid = sum(qty_bid, na.rm = TRUE),.groups = "drop") %>%mutate(win_rate = ifelse(amt_bid > 0, amt_booked / amt_bid, NA_real_),value = .data[[metric]],t = row_number()) %>%filter(!is.na(value))series})its_result <- reactiveVal(NULL)its_selected_bp <- reactiveVal(NULL)observeEvent(input$its_breakpoints_table_rows_selected, {7 unmodified lines})observeEvent(input$its_run, {# ββ BUG FIX 2: tryCatch around its_series() call ββββββββββββββββββββββ# req() inside its_series throws a silent condition that previously# propagated here and caused the entire observeEvent to abort with zero# user feedback. Now we catch that and display a helpful message instead.series <- tryCatch(its_series(), error = function(e) NULL)if (is.null(series)) {its_result(list(error = "Please select an estimator from the dropdown, then click Run Analysis."))return()}# ββ END BUG FIX 2 ββββββββββββββββββββββοΏ½οΏ½βββββββββββββββββββββββββββββvalidate_msg <- NULLif (nrow(series) < 18) validate_msg <- "Need at least 18 monthly observations."if (!is.null(validate_msg)) { its_result(list(error = validate_msg)); return() }9 unmodified linestryCatch({bp_fit <- breakpoints(value ~ t, data = series, h = 6)bp_idx <- bp_fit$breakpointsif (!any(is.na(bp_idx)) && length(bp_idx) > 0) {bp_dates <- series$date_group[bp_idx]# ββ BUG FIX 3: Fstats time-series subscripting ββββββββββββββββββ# Fstats() returns a TRIMMED time series. bp_idx is a row position# in series (e.g. 20), but fs$Fstats[20] returns the 20th element# of the trimmed ts β not the stat at row 20. We now use time()# to map bp_idx values onto the correct ts positions.fs <- Fstats(value ~ t, data = series)fs_times <- as.integer(time(fs$Fstats))fs_vals <- as.numeric(fs$Fstats)fstat_at_bp <- sapply(bp_idx, function(i) {pos <- which(fs_times == i)if (length(pos) > 0) round(fs_vals[pos], 2) else NA_real_})bp_table <- tibble(Date = bp_dates,`Time Index` = bp_idx,`F-Statistic` = fstat_at_bp,`Months Before` = bp_idx,`Months After` = nrow(series) - bp_idx)# ββ END BUG FIX 3 ββββββββββββββββββββββββββββββββββββββββββββββ}}, error = function(e) NULL)}active_date <- NULLif (!is.null(manual_dt) && !is.na(manual_dt) &&manual_dt >= min(series$date_group) && manual_dt <= max(series$date_group)) {active_date <- floor_date(as.Date(manual_dt), "month")} else if (length(bp_dates) > 0) {active_date <- bp_dates[1]10 unmodified linesif (is.null(fit)) { its_result(list(error = "Model could not be fitted. Try a different date.")); return() }cf <- coeftest(fit)# Build cf_df by indexing the coeftest matrix directly by column name.# as.data.frame(cf) is unreliable β R mangles column names like# "Std. Error" β "Std..Error" and "Pr(>|t|)" β "Pr...t.." depending# on R/lmtest version, causing downstream mutate() to crash with# "object 'Estimate' not found".cf_df <- data.frame(Term = recode(rownames(cf),`(Intercept)` = "Intercept (baseline level)",`t` = "Pre-intervention trend",`D` = "Level change",`t_post` = "Slope change"),Estimate = round(cf[, "Estimate"], 2),`Std Error` = round(cf[, "Std. Error"], 2),`t value` = round(cf[, "t value"], 3),`p value` = ifelse(cf[, "Pr(>|t|)"] < 0.001,"< 0.001",as.character(round(cf[, "Pr(>|t|)"], 3))),Significant = ifelse(cf[, "Pr(>|t|)"] < 0.05, "Yes *", "No"),stringsAsFactors = FALSE,check.names = FALSE)model_df <- model_df %>%mutate(fitted = fitted(fit),resid = residuals(fit),counterfact = coef(fit)[1] + coef(fit)[2] * t)pre <- model_df %>% filter(t <= t0)post <- model_df %>% filter(t >= t0)b2 <- coef(fit)["D"]; b3 <- coef(fit)["t_post"]p2 <- cf[3, 4]; p3 <- cf[4, 4]level_txt <- if (p2 < 0.05) {dir <- if (b2 > 0) "increased" else "decreased"paste0("The outcome ", dir, " immediately by ",if (metric %in% c("amt_booked","amt_bid")) dollar(abs(round(b2))) else round(abs(b2), 1)," at the intervention point (p = ", round(p2, 3), ").")} else {paste0("No significant immediate level change detected (p = ", round(p2, 3), ").")}slope_txt <- if (p3 < 0.05) {dir <- if (b3 > 0) "accelerated" else "decelerated"paste0("The monthly trajectory ", dir, " by ",if (metric %in% c("amt_booked","amt_bid")) dollar(abs(round(b3))) else round(abs(b3), 3)," per month after the intervention (p = ", round(p3, 3), ").")} else {paste0("No significant change in monthly trajectory detected (p = ", round(p3, 3), ").")}overall <- if (p2 < 0.05 || p3 < 0.05) "Significant intervention effect detected." else "No statistically significant intervention effect detected."its_result(list(series = model_df,pre = pre,post = post,fit = fit,coef_df = cf_df,breakpoints = bp_table,active_date = active_date,t0 = t0,metric = metric,estimator = input$its_estimator,level_txt = level_txt,slope_txt = slope_txt,overall = overall,r2 = round(summary(fit)$r.squared, 3),autodetect = autodetect))})output$its_summary_ui <- renderUI({5 unmodified linestagList(tags$table(style = "width:100%; border-collapse:collapse; font-size:13px;",tags$tr(tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50; width:40%;", "Estimator"),tags$td(style = "padding:6px 10px; color:#5A6A72;", res$estimator)),tags$tr(style = "background:#f4f6f9;",tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50;", "Outcome Metric"),tags$td(style = "padding:6px 10px; color:#5A6A72;", metric_label[res$metric])),tags$tr(tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50;", "Intervention Date"),tags$td(style = "padding:6px 10px; color:#5A6A72;",format(res$active_date, "%B %Y"),if (!is.null(input$its_manual_date) && !is.na(input$its_manual_date) &&floor_date(as.Date(input$its_manual_date), "month") == res$active_date)tags$span(" (manager-specified)", style = "color:#e67e22; font-size:11px;")elsetags$span(" (auto-detected)", style = "color:#27ae60; font-size:11px;"))),tags$tr(style = "background:#f4f6f9;",tags$td(style = "padding:6px 10px; font-weight:600; color:#2c3e50;", "Model R\u00b2"),tags$td(style = "padding:6px 10px; color:#5A6A72;", res$r2))),tags$hr(style = "margin:12px 0;"),tags$p(style = "font-size:13px; color:#2c3e50; font-weight:600;", res$overall),tags$p(style = "font-size:12px; color:#5A6A72; margin:4px 0;", tags$b("Level change: "), res$level_txt),tags$p(style = "font-size:12px; color:#5A6A72; margin:4px 0;", tags$b("Slope change: "), res$slope_txt))})3 unmodified linesif (is.null(res) || !is.null(res$error)) return(plotly_empty())series <- res$series; pre <- res$pre; post <- res$post; metric <- res$metricfmt <- if (metric %in% c("amt_booked","amt_bid")) function(x) dollar(round(x)) elseif (metric == "win_rate") function(x) percent(x, 0.1) elsefunction(x) comma(round(x))y_label <- c(amt_booked = "Booked Revenue ($)", amt_bid = "Bid Volume ($)",qty_booked = "Jobs Booked", win_rate = "Win Rate")[metric]p <- ggplot(series, aes(x = date_group)) +geom_point(aes(y = value,text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>Actual: ", fmt(value))),color = "#95a5a6", size = 2.2, alpha = 0.8) +geom_line(aes(y = counterfact), color = "#c0392b", linetype = "dotted", linewidth = 0.7, alpha = 0.6) +geom_line(data = pre, aes(y = fitted), color = "#2980b9", linewidth = 1.1) +geom_line(data = post, aes(y = fitted), color = "#27ae60", linewidth = 1.1) +geom_vline(xintercept = as.numeric(res$active_date), color = "#e67e22", linetype = "dashed", linewidth = 0.9) +annotate("text", x = res$active_date, y = max(series$value, na.rm = TRUE) * 0.95,label = paste("Intervention\n", format(res$active_date, "%b %Y")),hjust = -0.08, size = 3, color = "#e67e22") +scale_y_continuous(labels = if (metric %in% c("amt_booked","amt_bid")) dollar_format(accuracy = 1) elseif (metric == "win_rate") percent_format(accuracy = 1) elsecomma_format(accuracy = 1)) +labs(x = NULL, y = y_label,title = paste0(res$estimator, " β ITS: ", y_label),caption = "Blue = pre-int. trend | Green = post-int. trend | Red dotted = counterfactual") +theme_minimal() +theme(plot.caption = element_text(size = 8, color = "#95a5a6"),plot.title = element_text(size = 12, face = "bold", color = "#2c3e50"))ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h"))})output$its_breakpoints_table <- renderDataTable({res <- its_result()if (is.null(res) || !is.null(res$error)) return(NULL)if (is.null(res$breakpoints) || nrow(res$breakpoints) == 0)return(data.frame(Message = "No significant breakpoints detected automatically."))res$breakpoints %>% mutate(Date = format(Date, "%B %Y")) %>% arrange(desc(`F-Statistic`))}, selection = "single", options = list(dom = "t", pageLength = 10, scrollX = TRUE))output$its_coef_table <- renderDataTable({res <- its_result()if (is.null(res) || !is.null(res$error)) return(NULL)res$coef_df}, options = list(dom = "t", pageLength = 10, scrollX = TRUE))# ββ ADVANCED ANALYTICS (FUNNEL & HEATMAP) βββββββββββββββββββββββββββββββββoutput$bid_funnel_chart <- renderPlotly({d <- filtered_data()validate(need(nrow(d) > 0, "No data."))funnel <- d %>%group_by(primary_name) %>%summarise(Bid = sum(amt_bid, na.rm = TRUE), Booked = sum(amt_booked, na.rm = TRUE), .groups = "drop") %>%filter(Bid > 0) %>%mutate(Win_Rate = Booked / Bid, primary_name = fct_reorder(primary_name, Bid)) %>%pivot_longer(c(Bid, Booked), names_to = "Type", values_to = "Amount") %>%mutate(Win_Label = ifelse(Type == "Booked", paste0(percent(Win_Rate, 0.1), " win rate"), NA_character_))p <- ggplot(funnel, aes(x = primary_name, y = Amount, fill = Type,text = paste0("<b>", primary_name, "</b><br>", Type, ": ", dollar(Amount, accuracy = 1),ifelse(!is.na(Win_Label), paste0("<br>", Win_Label), "")))) +geom_col(position = "dodge", width = 0.65) +geom_text(aes(label = Win_Label), position = position_dodge(width = 0.65),hjust = -0.1, size = 3, na.rm = TRUE, color = "#2c3e50") +scale_fill_manual(values = c("Bid" = "#95a5a6", "Booked" = "#27ae60")) +scale_y_continuous(labels = dollar_format(accuracy = 1), expand = expansion(mult = c(0, 0.25))) +coord_flip() + labs(x = "", y = "Amount ($)", fill = "") +theme_minimal() + theme(legend.position = "top", panel.grid.major.y = element_blank())ggplotly(p, tooltip = "text")})output$seasonality_heatmap <- renderPlotly({df <- get_data()sel <- input$estimatorSelectif (!is.null(sel) && length(sel) > 0) df <- df %>% filter(primary_name %in% sel)validate(need(nrow(df) > 0, "No data."))hm_metric <- if (!is.null(input$heatmap_metric)) input$heatmap_metric else "amt_booked"metric_sym <- sym(hm_metric)metric_label <- if (hm_metric == "amt_booked") "Booked ($)" else "Bid ($)"heat <- df %>%mutate(Month = month(report_date, label = TRUE, abbr = TRUE),Year = as.integer(year(report_date))) %>%group_by(Year, Month) %>%summarise(Value = sum(!!metric_sym, na.rm = TRUE), .groups = "drop") %>%complete(Year, Month, fill = list(Value = 0)) %>%mutate(Month = factor(Month, levels = rev(month.abb)))p <- ggplot(heat, aes(x = factor(Year), y = Month, fill = Value,text = paste0("<b>", Month, " ", Year, "</b><br>", metric_label, ": ", dollar(Value, accuracy = 1)))) +geom_tile(color = "white", linewidth = 0.4) +scale_fill_gradient(low = "#eaf4fb",high = if (hm_metric == "amt_booked") "#1a5276" else "#7f8c8d",labels = dollar_format(scale = 1e-3, suffix = "K", accuracy = 1),name = metric_label) +labs(x = "Year", y = "") +theme_minimal() +theme(axis.text.x = element_text(angle = 45, hjust = 1), panel.grid = element_blank(), legend.position = "right")ggplotly(p, tooltip = "text")})# ββ K-MEANS βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββoutput$scatter_matrix <- renderPlotly({dat <- filtered_data()validate(need(nrow(dat) > 0, "Upload data to begin."))lwr <- lag_win_rate()ds_df <- dat %>%group_by(primary_name) %>%summarise(Total_Bid = sum(amt_bid, na.rm = TRUE),Total_Booked = sum(amt_booked, na.rm = TRUE),Jobs_Bid = sum(qty_bid, na.rm = TRUE),.groups = "drop") %>%mutate(Avg_Job_Size = Total_Bid / Jobs_Bid, Win_Rate_SM = Total_Booked / Total_Bid)if (!is.null(lwr) && nrow(lwr) > 0) {lag_summary <- lwr %>%group_by(primary_name) %>%summarise(Lag_Win_Rate = sum(lag_booked_amt, na.rm = TRUE) / sum(amt_bid, na.rm = TRUE), .groups = "drop")ds_df <- ds_df %>% left_join(lag_summary, by = "primary_name") %>%mutate(Win_Rate = coalesce(Lag_Win_Rate, Win_Rate_SM))} else {ds_df$Win_Rate <- ds_df$Win_Rate_SM}ds_df <- ds_df %>%filter(Total_Bid > 0, !is.na(Win_Rate), !is.infinite(Win_Rate),!is.na(Avg_Job_Size), !is.infinite(Avg_Job_Size))validate(need(nrow(ds_df) >= 3, "Need at least 3 active estimators to cluster."))set.seed(42)if (any(sapply(ds_df[, c("Total_Bid", "Win_Rate", "Avg_Job_Size")], function(x) sd(x, na.rm = TRUE) == 0))) {ds_df$Archetype <- "Archetype 1"} else {feats <- ds_df %>% select(Total_Bid, Win_Rate, Avg_Job_Size) %>% scale()k <- min(3, nrow(ds_df) - 1)km <- kmeans(feats, centers = k, nstart = 25)ds_df$Cluster <- as.factor(km$cluster)cl_means <- ds_df %>% group_by(Cluster) %>% summarise(mean_wr = mean(Win_Rate, na.rm = TRUE), .groups = "drop") %>% arrange(desc(mean_wr))arch_map <- setNames(c("High-Efficiency", "Selective", "High-Volume")[seq_len(nrow(cl_means))], cl_means$Cluster)ds_df$Archetype <- arch_map[as.character(ds_df$Cluster)]}p <- ggplot(ds_df, aes(x = Total_Bid, y = Win_Rate, color = Archetype, size = Total_Booked,text = paste0("<b>", primary_name, "</b><br>","Archetype: ", Archetype, "<br>","Pipeline Effort: ", dollar(Total_Bid, 1), "<br>","Win Rate: ", percent(Win_Rate, 0.1), "<br>","Avg Job Size: ", dollar(Avg_Job_Size, 1), "<br>","Total Booked: ", dollar(Total_Booked, 1)))) +geom_point(alpha = 0.85) +scale_color_manual(values = c("High-Efficiency" = "#27ae60", "Selective" = "#f39c12", "High-Volume" = "#e74c3c")) +scale_x_continuous(labels = dollar_format(accuracy = 1)) +scale_y_continuous(labels = percent_format(accuracy = 1)) +labs(x = "Total Amount Bid", y = "Win Rate", color = "Archetype") +theme_minimal() + theme(legend.position = "right")ggplotly(p, tooltip = "text")})# ββ ANNUAL, YOY, QUARTERLY ββββββββββββββββββββββββββββββββββββββββββββββββoutput$annual_bar_chart <- renderPlotly({d <- filtered_data()validate(need(nrow(d) > 0, "No data."))gran <- input$annual_granularityby_person <- !is.null(input$estimatorSelect) && length(input$estimatorSelect) <= 5d <- d %>% mutate(x_group = case_when(gran == "year" ~ as.character(year(report_date)),gran == "quarter" ~ paste0(year(report_date), " Q", quarter(report_date)),gran == "month" ~ format(report_date, "%Y-%m"),TRUE ~ as.character(year(report_date))))x_levels <- d %>% arrange(report_date) %>% pull(x_group) %>% unique()d <- d %>% mutate(x_group = factor(x_group, levels = x_levels))if (by_person) {annual <- d %>% group_by(x_group, primary_name) %>% summarise(Booked = sum(amt_booked, na.rm = TRUE), .groups = "drop")p <- ggplot(annual, aes(x_group, Booked, fill = primary_name,text = paste0("<b>", x_group, "</b><br>", primary_name, "<br>", dollar(round(Booked), accuracy = 1)))) +geom_col(position = "dodge") + scale_fill_brewer(palette = "Paired")} else {annual <- d %>% group_by(x_group) %>%summarise(Bid = sum(amt_bid, na.rm = TRUE), Booked = sum(amt_booked, na.rm = TRUE), .groups = "drop") %>%pivot_longer(c(Bid, Booked), names_to = "Type", values_to = "Value")p <- ggplot(annual, aes(x_group, Value, fill = Type,text = paste0("<b>", x_group, "</b><br>", Type, ": ", dollar(round(Value), accuracy = 1)))) +geom_col(position = "dodge") + scale_fill_manual(values = c("Bid" = "#95a5a6", "Booked" = "#27ae60"))}ggplotly(p + scale_y_continuous(labels = dollar_format(accuracy = 1)) +labs(x = "", y = "", fill = "") + theme_minimal() +theme(axis.text.x = element_text(angle = if (gran != "year") 45 else 0, hjust = 1)),tooltip = "text")})output$yoy_chart <- renderPlotly({d <- filtered_data()req(input$yoy_metric, input$view_mode)validate(need(nrow(d) > 0, "No data."))msym <- sym(input$yoy_metric)bar_pos <- input$yoy_positionif (input$view_mode == "Individual") {validate(need(length(unique(d$primary_name)) <= 10, "Select 10 or fewer estimators for Individual YoY."))ag <- d %>%group_by(year_num, primary_name) %>%summarise(V = sum(!!msym, na.rm = TRUE), .groups = "drop") %>%arrange(year_num) %>%group_by(primary_name) %>%mutate(G = (V - lag(V)) / lag(V)) %>%filter(!is.na(G))p <- ggplot(ag, aes(factor(year_num), G, fill = primary_name,text = paste0(year_num, " β ", primary_name, "<br>Growth: ", percent(G, 0.1)))) +geom_col(position = bar_pos) + scale_fill_brewer(palette = "Paired")} else {ag <- d %>%group_by(year_num) %>%summarise(V = sum(!!msym, na.rm = TRUE), .groups = "drop") %>%arrange(year_num) %>%mutate(G = (V - lag(V)) / lag(V)) %>%filter(!is.na(G))p <- ggplot(ag, aes(factor(year_num), G, fill = G > 0,text = paste0(year_num, "<br>Growth: ", percent(G, 0.1)))) +geom_col(show.legend = FALSE) +scale_fill_manual(values = c("TRUE" = "#27ae60", "FALSE" = "#c0392b"))}ggplotly(p + geom_hline(yintercept = 0) +scale_y_continuous(labels = percent_format()) +labs(x = "Year", y = "Growth %") + theme_minimal(),tooltip = "text")})output$quarterly_breakdown_chart <- renderPlotly({d <- filtered_data()req(input$quarter_year_select)validate(need(nrow(d) > 0, "No data."))q <- d %>%filter(year_num == as.numeric(input$quarter_year_select)) %>%mutate(Quarter = paste0("Q", quarter(report_date))) %>%group_by(Quarter) %>%summarise(Revenue = sum(amt_booked, na.rm = TRUE), .groups = "drop")p <- ggplot(q, aes(Quarter, Revenue, text = paste0(Quarter, "<br>", dollar(Revenue, 1)))) +geom_col(fill = "#3c8dbc", width = 0.6) +scale_y_continuous(labels = dollar_format(accuracy = 1)) +labs(x = "", y = "Revenue ($)") + theme_minimal() +theme(panel.grid.major.x = element_blank())ggplotly(p, tooltip = "text")})# ββ LEADERBOARD & EXPORT ββββββββββββββββββββββββββββββββββββββββββββββββββoutput$leaderboard_table <- renderDataTable({d <- filtered_data()if (nrow(d) == 0) return(NULL)lb <- d %>%group_by(primary_name) %>%summarise(Total_Bids = sum(amt_bid, na.rm = TRUE),Total_Booked = sum(amt_booked, na.rm = TRUE),Jobs_Won = sum(qty_booked, na.rm = TRUE),Jobs_Bid = sum(qty_bid, na.rm = TRUE),.groups = "drop") %>%mutate(Win_Rate = Total_Booked / Total_Bids, Avg_Job_Size = Total_Bids / Jobs_Bid)if (input$win_lag > 0) {lwr <- lag_win_rate()if (!is.null(lwr)) {lag_col <- lwr %>%group_by(primary_name) %>%summarise(Lag_WR = sum(lag_booked_amt, na.rm = TRUE) / sum(amt_bid, na.rm = TRUE), .groups = "drop")lb <- lb %>% left_join(lag_col, by = "primary_name")}}lb <- lb %>%mutate(Total_Bids = dollar(Total_Bids, accuracy = 1),Total_Booked = dollar(Total_Booked, accuracy = 1),Win_Rate = percent(Win_Rate, accuracy = 0.1),Avg_Job_Size = dollar(Avg_Job_Size, accuracy = 1)) %>%rename(Estimator = primary_name,`Total Revenue` = Total_Booked,`Total Bids` = Total_Bids,`Win % (same-mo)` = Win_Rate,`Jobs Won` = Jobs_Won,`Jobs Bid` = Jobs_Bid,`Avg Job Size` = Avg_Job_Size)if ("Lag_WR" %in% names(lb))lb <- lb %>% mutate(Lag_WR = percent(Lag_WR, accuracy = 0.1)) %>% rename(`Win % (lag-adj)` = Lag_WR)datatable(lb, options = list(pageLength = 15, scrollX = TRUE, order = list(list(2, "desc"))), rownames = FALSE)})output$db_status_text <- renderText({ paste("Database records loaded:", comma(nrow(get_data()))) })output$preview_table <- renderDataTable({d <- get_data()if (nrow(d) == 0) return(NULL)d %>% arrange(desc(report_date)) %>% head(5) %>%select(Estimator = primary_name, Date = report_date, Bid = amt_bid, Booked = amt_booked)}, options = list(dom = "t", searching = FALSE))output$download_report <- downloadHandler(filename = function() { paste0("Estimator_Intelligence_", format(Sys.Date(), "%Y-%m-%d"), ".xlsx") },content = function(file) {d <- filtered_data(); req(nrow(d) > 0)withProgress(message = "Building Excel report\u2026", value = 0.2, {wb <- createWorkbook()header_style <- createStyle(fontName="Calibri", fontSize=11, fontColour="#FFFFFF", fgFill="#2c3e50",halign="LEFT", valign="CENTER", textDecoration="bold",border="Bottom", borderColour="#27ae60")title_style <- createStyle(fontName="Calibri", fontSize=14, textDecoration="bold", fontColour="#2c3e50")dollar_style <- createStyle(numFmt="$#,##0")pct_style <- createStyle(numFmt="0.0%")addWorksheet(wb, "Summary")setColWidths(wb, "Summary", cols = 1:3, widths = c(30, 22, 22))writeData(wb, "Summary", "Estimator Intelligence Report", startRow = 1, startCol = 1)addStyle(wb, "Summary", title_style, rows = 1, cols = 1)sel_label <- if (is.null(isolate(input$estimatorSelect)) || length(isolate(input$estimatorSelect)) == 0)"All Estimators" else paste(isolate(input$estimatorSelect), collapse = ", ")meta <- data.frame(Field = c("Reporting Period", "Estimator Scope", "Win Rate Lag", "Generated"),Value = c(paste(format(isolate(input$dateRange[1]), "%b %d %Y"), "\u2014",format(isolate(input$dateRange[2]), "%b %d %Y")),sel_label,paste(isolate(input$win_lag), "month(s)"),format(Sys.Date(), "%B %d, %Y")),stringsAsFactors = FALSE)writeData(wb, "Summary", meta, startRow = 3, startCol = 1, colNames = FALSE)kpi_data <- data.frame(Metric = c("Total Bid Volume", "Total Booked Revenue", "Dollar Win Rate", "Active Estimators"),Value = c(dollar(sum(d$amt_bid, na.rm = TRUE), accuracy = 1),dollar(sum(d$amt_booked, na.rm = TRUE), accuracy = 1),percent(sum(d$amt_booked, na.rm = TRUE) / sum(d$amt_bid, na.rm = TRUE), accuracy = 0.1),as.character(length(unique(d$primary_name)))),stringsAsFactors = FALSE)writeData(wb, "Summary", kpi_data, startRow = 9, startCol = 1, colNames = TRUE)addStyle(wb, "Summary", header_style, rows = 9, cols = 1:2)addWorksheet(wb, "Leaderboard")setColWidths(wb, "Leaderboard", cols = 1:7, widths = c(22, 18, 18, 10, 10, 14, 14))lb_raw <- d %>%group_by(Estimator = primary_name) %>%summarise(`Total Bids` = sum(amt_bid, na.rm = TRUE),`Total Revenue` = sum(amt_booked, na.rm = TRUE),`Jobs Bid` = sum(qty_bid, na.rm = TRUE),`Jobs Won` = sum(qty_booked, na.rm = TRUE),`Win Rate` = `Total Revenue` / `Total Bids`,`Avg Job Size` = `Total Bids` / `Jobs Bid`,.groups = "drop") %>%arrange(desc(`Total Revenue`))writeData(wb, "Leaderboard", lb_raw, startRow = 1, colNames = TRUE)addStyle(wb, "Leaderboard", header_style, rows = 1, cols = 1:7)addStyle(wb, "Leaderboard", dollar_style, rows = 2:(nrow(lb_raw) + 1), cols = c(2, 3, 7), gridExpand = TRUE)addStyle(wb, "Leaderboard", pct_style, rows = 2:(nrow(lb_raw) + 1), cols = 6, gridExpand = TRUE)setProgress(0.6)addWorksheet(wb, "Monthly Detail")setColWidths(wb, "Monthly Detail", cols = 1:7, widths = c(22, 14, 14, 10, 14, 10, 14))monthly_raw <- d %>%arrange(primary_name, report_date) %>%mutate(Date = format(report_date, "%b %Y"),Win_Rate = ifelse(amt_bid > 0, amt_booked / amt_bid, 0)) %>%select(Estimator = primary_name,Date,`Bid ($)` = amt_bid,`Jobs Bid` = qty_bid,`Booked ($)` = amt_booked,`Jobs Won` = qty_booked,`Win Rate` = Win_Rate)writeData(wb, "Monthly Detail", monthly_raw, startRow = 1, colNames = TRUE)addStyle(wb, "Monthly Detail", header_style, rows = 1, cols = 1:7)addStyle(wb, "Monthly Detail", dollar_style, rows = 2:(nrow(monthly_raw) + 1), cols = c(3, 5), gridExpand = TRUE)addStyle(wb, "Monthly Detail", pct_style, rows = 2:(nrow(monthly_raw) + 1), cols = 7, gridExpand = TRUE)setProgress(0.9)saveWorkbook(wb, file, overwrite = TRUE)})})
12344 unmodified lines91011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666717 unmodified lines858687888990919293948 unmodified lines10310410510610710810911011111211311411511611711811912012112212312412512612717 unmodified lines1451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961978 unmodified lines2062072082092102112121 unmodified line21421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027111 unmodified lines2832842852862872882892902912922932942952961 unmodified line298299300301302303304305306307308# --- ui.R ---dashboardPage(title = "Estimator Intelligence",skin = "black",4 unmodified linesdashboardSidebar(width = 260,sidebarMenu(menuItem("Executive Dashboard", tabName = "dashboard", icon = icon("chart-area")),menuItem("Intervention Analysis", tabName = "its", icon = icon("flask")),menuItem("Data Management", tabName = "admin", icon = icon("database")),hr(),div(style = "padding:10px;",h5("Filter Controls",style = "color:#b8c7ce;text-transform:uppercase;font-size:12px;margin-bottom:10px;"),dateRangeInput("dateRange", "View Range",start = Sys.Date() %m-% months(24),end = Sys.Date(),separator = " to "),dateRangeInput("baselineRange", "SPC Baseline Period",start = Sys.Date() %m-% months(48),end = Sys.Date() %m-% months(25),separator = " to "),radioGroupButtons("view_mode", "Breakdown Mode",choices = c("Aggregate", "Individual"),selected = "Aggregate",status = "success", size = "sm", justified = TRUE),br(),radioGroupButtons("time_granularity", "Time Scale",choices = c("Monthly", "Quarterly"),selected = "Monthly",status = "primary", size = "sm", justified = TRUE),br(),sliderInput("win_lag", "Win Rate Lag (months)",min = 0, max = 6, value = 3, step = 1,ticks = FALSE),p(style = "font-size:10px;color:#b8c7ce;margin-top:-8px;","Match bids to bookings N months later. 0 = same-month (old behavior)."),pickerInput("estimatorSelect", "Estimators:",choices = NULL, multiple = TRUE,options = list(`actions-box` = TRUE,`live-search` = TRUE,`selected-text-format` = "count > 2",`count-selected-text` = "{0} Selected",`none-selected-text` = "All Estimators (Default)")),div(style = "margin-top:12px;display:flex;gap:6px;",actionButton("refresh", "Refresh",icon = icon("sync"), style = "flex:1;font-size:12px;",class = "btn-primary btn-sm btn-flat"),actionButton("reset_filters", "Reset",icon = icon("undo"), style = "flex:1;font-size:12px;",class = "btn-warning btn-sm btn-flat")))17 unmodified lines# ROW 1: KPIsfluidRow(valueBoxOutput("kpi_total_bid", width = 3),valueBoxOutput("kpi_total_booked", width = 3),valueBoxOutput("kpi_win_rate_amt", width = 3),valueBoxOutput("kpi_lag_win_rate", width = 3)),# ROW 2: CORRELATION INSIGHT8 unmodified linestabBox(title = textOutput("trend_box_title"),width = 12, side = "right",selected = "Control Chart: Revenue ($)",tabPanel("Control Chart: Revenue ($)",fluidRow(column(6,radioGroupButtons("trend_series", NULL,choices = c("Booked Only" = "booked", "Bid vs. Booked" = "both"),selected = "booked",status = "default", size = "xs")),column(6,materialSwitch("show_trendline",label = "Trend Lines (Individual)",value = FALSE,status = "primary",right = TRUE))),plotlyOutput("trend_dollars", height = "370px"),p(class = "text-muted", style = "font-size:11px;","SPC: Blue = Baseline Mean. Red dashed = UCL/LCL (Β±3 SD from Baseline Period). Red dots = anomalies. Trend line shows linear trajectory per estimator (Individual mode only).")),tabPanel("Control Chart: Quantity",div(style = "padding:6px 0 0 4px;",materialSwitch("show_trendline_qty",17 unmodified linesradioGroupButtons("annual_granularity", NULL,choices = c("By Year" = "year", "By Quarter" = "quarter", "By Month" = "month"),selected = "year",status = "default", size = "xs", justified = TRUE))),plotlyOutput("annual_bar_chart", height = "370px")),tabBox(title = "Growth & Breakdown", width = 6, side = "right",selected = "YoY Growth (%)",tabPanel("YoY Growth (%)",fluidRow(column(4, p(class="text-muted", style="font-size:11px;margin-top:10px;","Aggregate: Red/Green | Individual: Colored by Person")),column(4, pickerInput("yoy_metric", NULL,choices = c("Booked Revenue ($)" = "amt_booked","Bid Volume ($)" = "amt_bid","Jobs Booked (Qty)" = "qty_booked","Jobs Bid (Qty)" = "qty_bid"),selected = "amt_booked", width = "100%",options = list(style = "btn-default btn-sm"))),column(4, radioGroupButtons("yoy_position", NULL,choices = c("Grouped" = "dodge", "Stacked" = "stack"),selected = "dodge",status = "default", size = "xs", justified = TRUE))),plotlyOutput("yoy_chart", height = "330px")),tabPanel("Quarterly Deep Dive",fluidRow(column(7, p(class="text-muted", style="font-size:11px;margin-top:10px;","Revenue Breakdown by Quarter for Selected Year.")),column(5, selectInput("quarter_year_select", NULL,choices = NULL, width = "100%"))),plotlyOutput("quarterly_breakdown_chart", height = "350px")))),# ROW 5: NEW ANALYTICS TABSfluidRow(tabBox(title = "Advanced Analytics", width = 12, side = "right",selected = "Bid Funnel",tabPanel("Bid Funnel",plotlyOutput("bid_funnel_chart", height = "420px"),p(class = "text-muted", style = "font-size:11px;","Grouped bars show Total Bid $ vs. Total Booked $ per estimator. Win % annotated on each booked bar. Sorted by Total Bid descending.")),tabPanel("Seasonality Heatmap",plotlyOutput("seasonality_heatmap", height = "420px"),p(class = "text-muted", style = "font-size:11px;","Booked revenue by calendar month and year. Darker = higher revenue. Reveals consistent seasonal peaks and troughs across the full history.")))),8 unmodified lines# ROW 7: LEADERBOARDfluidRow(box(title = "Estimator Leaderboard β Click any column to sort",status = "warning", solidHeader = TRUE, width = 12,dataTableOutput("leaderboard_table")))1 unmodified line# ββ INTERVENTION ANALYSIS (ITS) ββββββββββββββββββββββββββββββββββββββtabItem(tabName = "its",fluidRow(box(title = "Intervention Settings", status = "primary",solidHeader = TRUE, width = 4,pickerInput("its_estimator", "Estimator",choices = NULL, multiple = FALSE,options = list(`live-search` = TRUE)),pickerInput("its_metric", "Outcome Metric",choices = c("Booked Revenue ($)" = "amt_booked","Bid Volume ($)" = "amt_bid","Jobs Booked (Qty)" = "qty_booked","Win Rate (same-mo.)" = "win_rate"), selected = "amt_booked"),hr(),dateInput("its_manual_date", "Option A β Specify Intervention Date",value = NULL, format = "M yyyy",min = "2010-01-01"),p(class = "text-muted", style = "font-size:11px;","The date a strategy change, new hire, process shift, or other intervention occurred."),hr(),materialSwitch("its_autodetect",label = "Option B β Auto-Detect Breakpoints",value = TRUE,status = "primary", right = TRUE),p(class = "text-muted", style = "font-size:11px;","Uses the strucchange algorithm to scan for the single most statistically significant structural break in the series."),br(),actionButton("its_run", "Run Analysis",icon = icon("play"),class = "btn-success btn-block",width = "100%")),box(title = "Intervention Effect β Statistical Summary",status = "primary", solidHeader = TRUE, width = 8,uiOutput("its_summary_ui"),p(class = "text-muted", style = "font-size:11px; margin-top:8px;","Segmented regression (OLS) with pre/post intervention terms. Level change = immediate shift at intervention date. Slope change = difference in monthly trajectory before vs. after."))),fluidRow(box(title = "Interrupted Time Series β Visual",status = "primary", solidHeader = TRUE, width = 12,plotlyOutput("its_chart", height = "440px"),p(class = "text-muted", style = "font-size:11px;","Grey points = actual monthly values. Blue line = pre-intervention fitted trend. Green line = post-intervention fitted trend. Vertical dashed line = intervention point. Red dotted = counterfactual."))),fluidRow(box(title = "Auto-Detected Structural Breaks",status = "warning", solidHeader = TRUE, width = 6,11 unmodified lines# ββ DATA MANAGEMENT βββββββββββββββββββββββββββββββββββββββββββββββββtabItem(tabName = "admin",fluidRow(box(title = "Upload Data", status = "danger", solidHeader = TRUE, width = 5,fileInput("file1", "Upload CSV", accept = ".csv"),actionButton("process_upload", "Process & Import",class = "btn-danger", width = "100%")),box(title = "System Status", status = "info", solidHeader = TRUE, width = 4,verbatimTextOutput("db_status_text"),dataTableOutput("preview_table")),box(title = "Export Report", status = "primary", solidHeader = TRUE, width = 3,p(class = "text-muted","Download a formatted Excel workbook of the current filtered view."),1 unmodified lineicon = icon("file-excel"),style = "width:100%;font-weight:600;"))),fluidRow(box(title = "Date Verification β Raw vs. Parsed",status = "warning", solidHeader = TRUE, width = 12,p(class = "text-muted", style = "font-size:12px;","Confirms MoYear values are parsed correctly. Format: YY-MM (e.g. '19-06' β June 2019)."),dataTableOutput("date_verification_table"))))123454 unmodified lines101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676817 unmodified lines868788899091929394958 unmodified lines10410510610710810911011111211311411511611711811912012112212312412512612712812913017 unmodified lines1481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162178 unmodified lines2262272282292302312321 unmodified line23423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329411 unmodified lines3063073083093103113123133143153163173183193203213221 unmodified line324325326327328329330331332333334335# --- ui.R ---dashboardPage(title = "Estimator Intelligence",skin = "black",4 unmodified linesdashboardSidebar(width = 260,sidebarMenu(menuItem("Executive Dashboard", tabName = "dashboard", icon = icon("chart-area")),menuItem("Intervention Analysis", tabName = "its", icon = icon("flask")),menuItem("Data Management", tabName = "admin", icon = icon("database")),hr(),div(style = "padding:10px;",h5("Filter Controls",style = "color:#b8c7ce;text-transform:uppercase;font-size:12px;margin-bottom:10px;"),dateRangeInput("dateRange", "View Range",start = Sys.Date() %m-% months(24),end = Sys.Date(),separator = " to "),dateRangeInput("baselineRange", "SPC Baseline Period",start = Sys.Date() %m-% months(48),end = Sys.Date() %m-% months(25),separator = " to "),radioGroupButtons("view_mode", "Breakdown Mode",choices = c("Aggregate", "Individual"),selected = "Aggregate",status = "success", size = "sm", justified = TRUE),br(),radioGroupButtons("time_granularity", "Time Scale",choices = c("Monthly", "Quarterly"),selected = "Monthly",status = "primary", size = "sm", justified = TRUE),br(),sliderInput("win_lag", "Win Rate Lag (months)",min = 0, max = 6, value = 3, step = 1, ticks = FALSE),p(style = "font-size:10px;color:#b8c7ce;margin-top:-8px;","Match bids to bookings N months later. 0 = same-month (old behavior)."),pickerInput("estimatorSelect", "Estimators:",choices = NULL, multiple = TRUE,options = list(`actions-box` = TRUE,`live-search` = TRUE,`selected-text-format` = "count > 2",`count-selected-text` = "{0} Selected",`none-selected-text` = "All Estimators (Default)")),div(style = "margin-top:12px;display:flex;gap:6px;",actionButton("refresh", "Refresh",icon = icon("sync"),style = "flex:1;font-size:12px;",class = "btn-primary btn-sm btn-flat"),actionButton("reset_filters", "Reset",icon = icon("undo"),style = "flex:1;font-size:12px;",class = "btn-warning btn-sm btn-flat")))17 unmodified lines# ROW 1: KPIsfluidRow(valueBoxOutput("kpi_total_bid", width = 3),valueBoxOutput("kpi_total_booked", width = 3),valueBoxOutput("kpi_win_rate_amt", width = 3),valueBoxOutput("kpi_lag_win_rate", width = 3)),# ROW 2: CORRELATION INSIGHT8 unmodified linestabBox(title = textOutput("trend_box_title"),width = 12, side = "right",selected = "Control Chart: Revenue ($)",tabPanel("Control Chart: Revenue ($)",fluidRow(column(6,radioGroupButtons("trend_series", NULL,choices = c("Booked Only" = "booked", "Bid vs. Booked" = "both"),selected = "booked",status = "default", size = "xs")),column(6,materialSwitch("show_trendline",label = "Trend Lines (Individual)",value = FALSE,status = "primary",right = TRUE))),plotlyOutput("trend_dollars", height = "370px"),p(class = "text-muted", style = "font-size:11px;","SPC: Blue = Baseline Mean. Red dashed = UCL/LCL (\u00b13 SD from Baseline Period). Red dots = anomalies. Trend line shows linear trajectory per estimator (Individual mode only).")),tabPanel("Control Chart: Quantity",div(style = "padding:6px 0 0 4px;",materialSwitch("show_trendline_qty",17 unmodified linesradioGroupButtons("annual_granularity", NULL,choices = c("By Year" = "year", "By Quarter" = "quarter", "By Month" = "month"),selected = "year",status = "default", size = "xs", justified = TRUE))),plotlyOutput("annual_bar_chart", height = "370px")),tabBox(title = "Growth & Breakdown", width = 6, side = "right",selected = "YoY Growth (%)",tabPanel("YoY Growth (%)",fluidRow(column(4, p(class = "text-muted", style = "font-size:11px;margin-top:10px;","Aggregate: Red/Green | Individual: Colored by Person")),column(4, pickerInput("yoy_metric", NULL,choices = c("Booked Revenue ($)" = "amt_booked","Bid Volume ($)" = "amt_bid","Jobs Booked (Qty)" = "qty_booked","Jobs Bid (Qty)" = "qty_bid"),selected = "amt_booked", width = "100%",options = list(style = "btn-default btn-sm"))),column(4, radioGroupButtons("yoy_position", NULL,choices = c("Grouped" = "dodge", "Stacked" = "stack"),selected = "dodge",status = "default", size = "xs", justified = TRUE))),plotlyOutput("yoy_chart", height = "330px")),tabPanel("Quarterly Deep Dive",fluidRow(column(7, p(class = "text-muted", style = "font-size:11px;margin-top:10px;","Revenue Breakdown by Quarter for Selected Year.")),column(5, selectInput("quarter_year_select", NULL, choices = NULL, width = "100%"))),plotlyOutput("quarterly_breakdown_chart", height = "350px")))),# ROW 5: ADVANCED ANALYTICSfluidRow(tabBox(title = "Advanced Analytics", width = 12, side = "right",selected = "Bid Funnel",tabPanel("Bid Funnel",plotlyOutput("bid_funnel_chart", height = "420px"),p(class = "text-muted", style = "font-size:11px;","Grouped bars show Total Bid $ vs. Total Booked $ per estimator. Win % annotated on each booked bar. Sorted by Total Bid descending.")),tabPanel("Seasonality Heatmap",# ββ NEW: metric toggle ββββββββββββββββββββββββββββββββfluidRow(column(12,radioGroupButtons("heatmap_metric",label = NULL,choices = c("Booked Revenue" = "amt_booked", "Bid Volume" = "amt_bid"),selected = "amt_booked",status = "default",size = "sm"))),# ββ END NEW βββββββββββββββββββββββββββββββββββββββββββplotlyOutput("seasonality_heatmap", height = "400px"),p(class = "text-muted", style = "font-size:11px;","Revenue or bid volume by calendar month and year. Darker = higher value. Reveals consistent seasonal peaks and troughs across the full history.")))),8 unmodified lines# ROW 7: LEADERBOARDfluidRow(box(title = "Estimator Leaderboard \u2014 Click any column to sort",status = "warning", solidHeader = TRUE, width = 12,dataTableOutput("leaderboard_table")))1 unmodified line# ββ INTERVENTION ANALYSIS (ITS) ββββββββββββββββββββββββββββββββββββββtabItem(tabName = "its",fluidRow(box(title = "Intervention Settings", status = "primary",solidHeader = TRUE, width = 4,pickerInput("its_estimator", "Estimator",choices = NULL, multiple = FALSE,options = list(`live-search` = TRUE)),pickerInput("its_metric", "Outcome Metric",choices = c("Booked Revenue ($)" = "amt_booked","Bid Volume ($)" = "amt_bid","Jobs Booked (Qty)" = "qty_booked","Win Rate (same-mo.)" = "win_rate"),selected = "amt_booked"),hr(),dateInput("its_manual_date", "Option A \u2014 Specify Intervention Date",value = NULL, format = "M yyyy",min = "2010-01-01"),p(class = "text-muted", style = "font-size:11px;","The date a strategy change, new hire, process shift, or other intervention occurred."),hr(),materialSwitch("its_autodetect",label = "Option B \u2014 Auto-Detect Breakpoints",value = TRUE,status = "primary", right = TRUE),p(class = "text-muted", style = "font-size:11px;","Uses the strucchange algorithm to scan for the single most statistically significant structural break in the series."),br(),actionButton("its_run", "Run Analysis",icon = icon("play"),class = "btn-success btn-block",width = "100%")),box(title = "Intervention Effect \u2014 Statistical Summary",status = "primary", solidHeader = TRUE, width = 8,uiOutput("its_summary_ui"),p(class = "text-muted", style = "font-size:11px; margin-top:8px;","Segmented regression (OLS) with pre/post intervention terms. Level change = immediate shift at intervention date. Slope change = difference in monthly trajectory before vs. after."))),fluidRow(box(title = "Interrupted Time Series \u2014 Visual",status = "primary", solidHeader = TRUE, width = 12,plotlyOutput("its_chart", height = "440px"),p(class = "text-muted", style = "font-size:11px;","Grey points = actual monthly values. Blue line = pre-intervention fitted trend. Green line = post-intervention fitted trend. Vertical dashed line = intervention point. Red dotted = counterfactual."))),fluidRow(box(title = "Auto-Detected Structural Breaks",status = "warning", solidHeader = TRUE, width = 6,11 unmodified lines# ββ DATA MANAGEMENT βββββββββββββββββββββββββββββββββββββββββββββββββtabItem(tabName = "admin",fluidRow(box(title = "Upload Data", status = "danger", solidHeader = TRUE, width = 5,fileInput("file1", "Upload CSV", accept = ".csv"),actionButton("process_upload", "Process & Import",class = "btn-danger", width = "100%")),box(title = "System Status", status = "info", solidHeader = TRUE, width = 4,verbatimTextOutput("db_status_text"),dataTableOutput("preview_table")),box(title = "Export Report", status = "primary", solidHeader = TRUE, width = 3,p(class = "text-muted","Download a formatted Excel workbook of the current filtered view."),1 unmodified lineicon = icon("file-excel"),style = "width:100%;font-weight:600;"))),fluidRow(box(title = "Date Verification \u2014 Raw vs. Parsed",status = "warning", solidHeader = TRUE, width = 12,p(class = "text-muted", style = "font-size:12px;","Confirms MoYear values are parsed correctly. Format: YY-MM (e.g. '19-06' \u2192 June 2019)."),dataTableOutput("date_verification_table"))))
server.R+504-118
ui.R+93-66