Your Name commited on
Commit
359a85c
Β·
1 Parent(s): 2691456

Feature release: Added Interrupted Time Series (ITS) module with Bai-Perron auto-detect and counterfactual modeling. Integrated Excel report generation and refined Dashboard UI/UX.

Browse files
Files changed (4) hide show
  1. global.R +6 -8
  2. server.R +320 -63
  3. setup_database.sql +1 -1
  4. ui.R +235 -42
global.R CHANGED
@@ -10,11 +10,12 @@ library(scales)
10
  library(DT)
11
  library(shinyWidgets)
12
  library(cluster)
13
- library(rmarkdown)
14
- library(pool) # NEW: For connection pooling
 
 
15
 
16
  # 1. ESTABLISH DATABASE CONNECTION POOL
17
- # This creates a stable pool of connections that all users share efficiently.
18
  db_pool <- dbPool(
19
  drv = RPostgres::Postgres(),
20
  dbname = Sys.getenv("DB_NAME", "sales_db"),
@@ -24,13 +25,11 @@ db_pool <- dbPool(
24
  password = Sys.getenv("DB_PASS", "")
25
  )
26
 
27
- # Ensure the pool closes safely when the app shuts down
28
  onStop(function() {
29
  poolClose(db_pool)
30
  })
31
 
32
- # 2. GLOBAL MATH FUNCTIONS
33
- # Moving the SPC math here keeps the server file clean and readable.
34
  spc_limits <- function(df, metric_col, is_quarterly, by_person = FALSE, bl_start, bl_end) {
35
  grp_date <- function(d) if (is_quarterly) floor_date(d, "quarter") else floor_date(d, "month")
36
 
@@ -76,5 +75,4 @@ spc_limits <- function(df, metric_col, is_quarterly, by_person = FALSE, bl_start
76
  LCL = pmax(0, bl_mean - 3 * bl_sd),
77
  Anomaly = ifelse(Val > UCL | Val < LCL, "Anomaly", "Normal"))
78
  }
79
- }
80
-
 
10
  library(DT)
11
  library(shinyWidgets)
12
  library(cluster)
13
+ library(openxlsx) # Tier 1 Excel report
14
+ library(strucchange) # ITS breakpoint detection
15
+ library(lmtest) # ITS coefficient testing
16
+ library(pool) # Connection pooling
17
 
18
  # 1. ESTABLISH DATABASE CONNECTION POOL
 
19
  db_pool <- dbPool(
20
  drv = RPostgres::Postgres(),
21
  dbname = Sys.getenv("DB_NAME", "sales_db"),
 
25
  password = Sys.getenv("DB_PASS", "")
26
  )
27
 
 
28
  onStop(function() {
29
  poolClose(db_pool)
30
  })
31
 
32
+ # 2. GLOBAL SPC LIMITS FUNCTION (Restored to prevent app crash)
 
33
  spc_limits <- function(df, metric_col, is_quarterly, by_person = FALSE, bl_start, bl_end) {
34
  grp_date <- function(d) if (is_quarterly) floor_date(d, "quarter") else floor_date(d, "month")
35
 
 
75
  LCL = pmax(0, bl_mean - 3 * bl_sd),
76
  Anomaly = ifelse(Val > UCL | Val < LCL, "Anomaly", "Normal"))
77
  }
78
+ }
 
server.R CHANGED
@@ -8,10 +8,8 @@ function(input, output, session) {
8
  input$refresh
9
  data_trigger()
10
 
11
- # We ask the pool if the table exists. It handles the connection automatically.
12
  if (!dbExistsTable(db_pool, "monthly_sales")) return(data.frame())
13
 
14
- # We fetch data using the pool
15
  df <- dbGetQuery(db_pool, "
16
  SELECT e.primary_name, s.*, EXTRACT(YEAR FROM s.report_date) AS year_num
17
  FROM monthly_sales s
@@ -43,7 +41,8 @@ function(input, output, session) {
43
  tryCatch(dbExecute(db_pool, "INSERT INTO estimators (primary_name) VALUES ($1) ON CONFLICT DO NOTHING", params = list(nm)), error = function(e) NULL)
44
 
45
  est_map <- dbGetQuery(db_pool, "SELECT id, primary_name FROM estimators")
46
- upload <- clean %>% left_join(est_map, by = c("clean_name" = "primary_name")) %>%
 
47
  select(estimator_id = id, report_date, amt_bid = AmtBid, qty_bid = QtyBid, amt_booked = AmtBooked, qty_booked = QtyBooked)
48
 
49
  dbWriteTable(db_pool, "staging_sales", upload, overwrite = TRUE, temporary = TRUE)
@@ -70,8 +69,10 @@ function(input, output, session) {
70
  })
71
 
72
  lag_win_rate <- reactive({
73
- df <- filtered_data(); lag <- input$win_lag
 
74
  if (nrow(df) == 0 || lag == 0) return(NULL)
 
75
  all_data <- get_data()
76
  max_data_date <- max(all_data$report_date, na.rm = TRUE)
77
  cutoff_date <- max_data_date %m-% months(lag)
@@ -80,29 +81,41 @@ function(input, output, session) {
80
  bid_months <- df %>% select(primary_name, report_date, amt_bid, qty_bid) %>% distinct() %>% filter(report_date <= cutoff_date)
81
  if (nrow(bid_months) == 0) return(NULL)
82
 
83
- result <- bid_months %>% rowwise() %>% mutate(
84
- 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),
85
- 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)
86
- ) %>% ungroup()
 
 
 
87
  result
88
  })
89
 
90
- # ── UPDATERS ──────────────────────────────────────────────────────────────
91
  observe({
92
  df <- get_data()
93
  if (nrow(df) == 0) return()
 
 
94
  est_list <- sort(unique(df$primary_name))
95
  updatePickerInput(session, "estimatorSelect", choices = est_list, selected = isolate(input$estimatorSelect))
96
- yrs <- sort(unique(df$year_num), decreasing = TRUE)
97
- cur_yr <- isolate(input$quarter_year_select)
 
 
 
 
 
98
  updateSelectInput(session, "quarter_year_select", choices = yrs, selected = if (!is.null(cur_yr) && cur_yr %in% yrs) cur_yr else yrs[1])
 
99
  max_dt <- max(df$report_date, na.rm = TRUE)
100
  updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)
101
  updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))
102
  })
103
 
104
  observeEvent(input$reset_filters, {
105
- df <- get_data(); if (nrow(df) == 0) return()
 
106
  max_dt <- max(df$report_date, na.rm = TRUE)
107
  updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)
108
  updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))
@@ -112,95 +125,331 @@ function(input, output, session) {
112
  updateRadioGroupButtons(session, "annual_granularity", selected = "year")
113
  updateRadioGroupButtons(session, "yoy_position", selected = "dodge")
114
  updateRadioGroupButtons(session, "trend_series", selected = "booked")
 
 
115
  updateSliderInput(session, "win_lag", value = 3)
116
  })
117
 
118
  output$date_verification_table <- renderDataTable({
119
- d <- get_data(); if (nrow(d) == 0) return(NULL)
 
120
  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)
121
  }, options = list(pageLength = 10, scrollX = TRUE, dom = "ftp"))
122
 
123
- output$trend_box_title <- renderText(paste("Statistical Process Control β€”", input$time_granularity, "View"))
124
 
125
  # ── KPIs ──────────────────────────────────────────────────────────────────
126
  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"))
127
  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"))
 
128
  output$kpi_win_rate_amt <- renderValueBox({
129
- d <- filtered_data(); r <- sum(d$amt_booked, na.rm = TRUE) / sum(d$amt_bid, na.rm = TRUE)
 
130
  valueBox(percent(r, 0.1), HTML("Same-Month Win Rate<br><small style='font-size:10px;opacity:0.75;'>Bids & bookings matched to same month</small>"), icon = icon("chart-line"), color = "yellow")
131
  })
 
132
  output$kpi_lag_win_rate <- renderValueBox({
133
- lag <- input$win_lag; if (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"))
134
- 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"))
 
 
 
 
135
  r <- sum(lwr$lag_booked_amt, na.rm = TRUE) / sum(lwr$amt_bid, na.rm = TRUE)
136
- max_dt <- max(get_data()$report_date, na.rm = TRUE); cutoff_dt <- max_dt %m-% months(lag)
137
- valueBox(percent(r, 0.1), HTML(paste0("Lag-Adjusted Win Rate<br><small style='font-size:10px;opacity:0.75;'>Bids after ", format(cutoff_dt, "%b %Y"), " excluded</small>")), icon = icon("clock"), color = "purple")
 
 
 
138
  })
139
 
 
140
  output$correlation_insight <- renderUI({
141
  d <- filtered_data()
142
  if (nrow(d) < 10) return(tags$p("Waiting for sufficient data points...", class = "text-muted"))
143
  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"))
 
144
  r <- cor(d$qty_bid, d$amt_booked, use = "complete.obs")
145
- txt <- if (is.na(r)) "<span class='insight-text'>⚠️ Data insufficient for Pearson correlation.</span>" else if (r < 0) paste0("<span class='insight-text'>πŸ”΄ <b>Negative Correlation (r=", round(r,2), "):</b> More bids β†’ lower revenue. Signals Estimator Fatigue.</span>") else if (r < 0.3) paste0("<span class='insight-text'>⚠️ <b>Weak Correlation (r=", round(r,2), "):</b> Bid quantity has minimal impact on revenue. Quality > quantity.</span>") else paste0("<span class='insight-text'>🟒 <b>Positive Correlation (r=", round(r,2), "):</b> Higher bid volume is translating to revenue. Pipeline mechanics are healthy.</span>")
 
 
 
 
 
 
 
 
146
  HTML(txt)
147
  })
148
 
149
- # ── SPC CHARTS ────────────────────────────────────────────────────────────
150
  output$trend_dollars <- renderPlotly({
151
- d <- filtered_data(); req(input$time_granularity, input$view_mode, input$baselineRange)
152
- validate(need(nrow(d) > 0, "No data.")); is_q <- input$time_granularity == "Quarterly"; by_person <- input$view_mode == "Individual"
153
- show_both <- isTRUE(input$trend_series == "both")
154
- if (by_person) { n <- length(unique(d$primary_name)); validate(need(n <= 4, paste0("⚠️ Select 4 or fewer estimators. Currently: ", n))) }
 
 
 
 
 
 
 
 
155
 
156
- # We call the global function, passing the UI dates explicitly
157
  ctrl <- spc_limits(d, "amt_booked", is_q, by_person, input$baselineRange[1], input$baselineRange[2])
158
 
159
  if (show_both) {
160
  grp_date <- function(dt) if (is_q) floor_date(dt, "quarter") else floor_date(dt, "month")
161
- if (by_person) { bid_trend <- d %>% mutate(date_group = grp_date(report_date)) %>% group_by(date_group, primary_name) %>% summarise(Bid = sum(amt_bid, na.rm = TRUE), .groups = "drop"); ctrl <- ctrl %>% left_join(bid_trend, by = c("date_group", "primary_name"))
162
- } else { bid_trend <- d %>% mutate(date_group = grp_date(report_date)) %>% group_by(date_group) %>% summarise(Bid = sum(amt_bid, na.rm = TRUE), .groups = "drop"); ctrl <- ctrl %>% left_join(bid_trend, by = "date_group") }
 
 
 
 
 
163
  }
164
 
165
  if (by_person) {
166
- p <- ggplot(ctrl, aes(x = date_group, y = Val, group = primary_name, text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", primary_name, "<br>Booked: ", dollar(round(Val), 1), "<br>Baseline Mean: ", dollar(round(BL_Mean), 1)))) +
167
- geom_line(aes(color = primary_name), linewidth = 0.9) + geom_point(aes(shape = Anomaly), size = 2) +
 
 
 
168
  { if (show_both) geom_line(aes(y = Bid, group = primary_name), linetype = "dotted", color = "#95a5a6", linewidth = 0.8) } +
169
- geom_hline(aes(yintercept = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) + geom_hline(aes(yintercept = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) + geom_hline(aes(yintercept = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
170
- scale_shape_manual(values = c("Normal" = 16, "Anomaly" = 8)) + scale_y_continuous(labels = dollar_format(accuracy = 1)) +
171
- facet_wrap(~primary_name, ncol = 2, scales = "free_y") + theme_minimal() + labs(x = "", y = "") + theme(legend.position = "none", strip.background = element_rect(fill = "#f4f6f9"), strip.text = element_text(face = "bold"))
172
- if (input$show_trend) { p <- p + geom_smooth(method = "lm", se = FALSE, color = "#8e44ad", linetype = "dashed", linewidth = 0.7) }
 
 
 
 
 
173
  } else {
174
- p <- ggplot(ctrl, aes(x = date_group, y = Val, group = 1, text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", "Booked: ", dollar(round(Val), 1), "<br>Baseline Mean: ", dollar(round(BL_Mean), 1), if (show_both) paste0("<br>Bid: ", dollar(round(Bid), 1)) else ""))) +
175
- geom_line(color = "#2c3e50", linewidth = 0.9) + geom_point(aes(color = Anomaly), size = 2) +
 
 
176
  { if (show_both) geom_line(aes(y = Bid, group = 1), color = "#95a5a6", linetype = "dotted", linewidth = 1) } +
177
- geom_line(aes(y = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) + geom_line(aes(y = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) + geom_line(aes(y = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
178
- scale_color_manual(values = c("Normal" = "#2c3e50", "Anomaly" = "#e74c3c")) + scale_y_continuous(labels = dollar_format(accuracy = 1)) + theme_minimal() + labs(x = "", y = "") + theme(legend.position = "none")
 
 
 
 
179
  }
180
  ggplotly(p, tooltip = "text")
181
  })
182
 
183
  output$trend_qty <- renderPlotly({
184
- d <- filtered_data(); req(input$time_granularity, input$view_mode, input$baselineRange)
185
- validate(need(nrow(d) > 0, "No data.")); is_q <- input$time_granularity == "Quarterly"; by_person <- input$view_mode == "Individual"
186
- if (by_person) { n <- length(unique(d$primary_name)); validate(need(n <= 4, paste0("⚠️ Select 4 or fewer estimators. Currently: ", n))) }
 
 
 
 
 
 
 
187
 
188
  ctrl <- spc_limits(d, "qty_booked", is_q, by_person, input$baselineRange[1], input$baselineRange[2])
189
 
190
  if (by_person) {
191
- p <- ggplot(ctrl, aes(x = date_group, y = Val, group = primary_name, text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", primary_name, "<br>Jobs: ", comma(Val, 1), "<br>Baseline Mean: ", comma(BL_Mean, 1)))) +
192
- geom_line(color = "#27ae60", linewidth = 0.9) + geom_point(aes(color = Anomaly), size = 2) +
193
- geom_hline(aes(yintercept = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) + geom_hline(aes(yintercept = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) + geom_hline(aes(yintercept = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
194
- scale_color_manual(values = c("Normal" = "#27ae60", "Anomaly" = "#e74c3c")) + scale_y_continuous(labels = comma_format(accuracy = 1)) + facet_wrap(~primary_name, ncol = 2, scales = "free_y") + theme_minimal() + labs(x = "", y = "") + theme(legend.position = "none", strip.background = element_rect(fill = "#f4f6f9"), strip.text = element_text(face = "bold"))
195
- if (input$show_trend) { p <- p + geom_smooth(method = "lm", se = FALSE, color = "#8e44ad", linetype = "dashed", linewidth = 0.7) }
 
 
 
 
 
 
 
 
 
196
  } else {
197
- p <- ggplot(ctrl, aes(x = date_group, y = Val, group = 1, text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", "Jobs Booked: ", comma(Val, 1), "<br>Baseline Mean: ", comma(BL_Mean, 1)))) +
198
- geom_line(color = "#27ae60", linewidth = 0.9) + geom_point(aes(color = Anomaly), size = 2) + geom_line(aes(y = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) + geom_line(aes(y = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) + geom_line(aes(y = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
199
- scale_color_manual(values = c("Normal" = "#27ae60", "Anomaly" = "#e74c3c")) + scale_y_continuous(labels = comma_format(accuracy = 1)) + theme_minimal() + labs(x = "", y = "") + theme(legend.position = "none")
 
 
 
 
 
 
 
200
  }
201
  ggplotly(p, tooltip = "text")
202
  })
203
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
204
  output$bid_funnel_chart <- renderPlotly({
205
  d <- filtered_data(); validate(need(nrow(d) > 0, "No data."))
206
  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_))
@@ -208,20 +457,18 @@ function(input, output, session) {
208
  ggplotly(p, tooltip = "text")
209
  })
210
 
211
- # ── SEASONALITY HEATMAP (CEO TWEAK: Using input$heatmap_metric) ─────────
212
  output$seasonality_heatmap <- renderPlotly({
213
- df <- get_data(); req(input$heatmap_metric); sel <- input$estimatorSelect
214
  if (!is.null(sel) && length(sel) > 0) df <- df %>% filter(primary_name %in% sel)
215
  validate(need(nrow(df) > 0, "No data."))
216
-
217
- metric_sym <- sym(input$heatmap_metric)
218
- metric_label <- if(input$heatmap_metric == "amt_booked") "Booked ($)" else "Bid ($)"
219
-
220
  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)))
221
- 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(input$heatmap_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")
222
  ggplotly(p, tooltip = "text")
223
  })
224
 
 
225
  output$scatter_matrix <- renderPlotly({
226
  dat <- filtered_data(); validate(need(nrow(dat) > 0, "Upload data to begin.")); lwr <- lag_win_rate()
227
  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)
@@ -233,6 +480,7 @@ function(input, output, session) {
233
  ggplotly(p, tooltip = "text")
234
  })
235
 
 
236
  output$annual_bar_chart <- renderPlotly({
237
  d <- filtered_data(); validate(need(nrow(d) > 0, "No data.")); gran <- input$annual_granularity; by_person <- !is.null(input$estimatorSelect) && length(input$estimatorSelect) <= 5
238
  d <- 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))
@@ -252,6 +500,7 @@ function(input, output, session) {
252
  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")
253
  })
254
 
 
255
  output$leaderboard_table <- renderDataTable({
256
  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)
257
  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") } }
@@ -264,14 +513,22 @@ function(input, output, session) {
264
  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))
265
 
266
  output$download_report <- downloadHandler(
267
- filename = function() { paste0("Estimator_Report_", Sys.Date(), ".html") },
268
  content = function(file) {
269
- tempReport <- file.path(tempdir(), "report_auto.Rmd")
270
- rmd_code <- c(
271
- "---", "title: 'Estimator Intelligence β€” Executive Summary'", paste0("date: '", Sys.Date(), "'"), "output: html_document", "---", "", "### Filter Settings Applied", paste0("**Date Range:** ", format(input$dateRange[1], "%B %d, %Y"), " to ", format(input$dateRange[2], "%B %d, %Y"), " "), paste0("**Estimators Included:** ", if(is.null(input$estimatorSelect)) "All Company" else paste(input$estimatorSelect, collapse=", "), " "), "", "### Key Performance Indicators", paste0("Total Bid Volume: **", dollar(sum(filtered_data()$amt_bid, na.rm=T), accuracy=1), "** "), paste0("Total Booked Revenue: **", dollar(sum(filtered_data()$amt_booked, na.rm=T), accuracy=1), "** "), paste0("Average Win Rate (Same-Month): **", percent(sum(filtered_data()$amt_booked, na.rm=T)/sum(filtered_data()$amt_bid, na.rm=T), 0.1), "** "), "", "### Instructions to Save as PDF", "1. Open this file in Google Chrome or Microsoft Edge.", "2. Press **Ctrl+P** (Windows) or **Cmd+P** (Mac).", "3. Change the Destination printer to **'Save as PDF'**.", "4. Ensure 'Background graphics' is checked for optimal styling."
272
- )
273
- writeLines(rmd_code, tempReport)
274
- rmarkdown::render(tempReport, output_file = file, envir = new.env(parent = globalenv()), quiet = TRUE)
 
 
 
 
 
 
 
 
275
  }
276
  )
277
  }
 
8
  input$refresh
9
  data_trigger()
10
 
 
11
  if (!dbExistsTable(db_pool, "monthly_sales")) return(data.frame())
12
 
 
13
  df <- dbGetQuery(db_pool, "
14
  SELECT e.primary_name, s.*, EXTRACT(YEAR FROM s.report_date) AS year_num
15
  FROM monthly_sales s
 
41
  tryCatch(dbExecute(db_pool, "INSERT INTO estimators (primary_name) VALUES ($1) ON CONFLICT DO NOTHING", params = list(nm)), error = function(e) NULL)
42
 
43
  est_map <- dbGetQuery(db_pool, "SELECT id, primary_name FROM estimators")
44
+ upload <- clean %>%
45
+ left_join(est_map, by = c("clean_name" = "primary_name")) %>%
46
  select(estimator_id = id, report_date, amt_bid = AmtBid, qty_bid = QtyBid, amt_booked = AmtBooked, qty_booked = QtyBooked)
47
 
48
  dbWriteTable(db_pool, "staging_sales", upload, overwrite = TRUE, temporary = TRUE)
 
69
  })
70
 
71
  lag_win_rate <- reactive({
72
+ df <- filtered_data()
73
+ lag <- input$win_lag
74
  if (nrow(df) == 0 || lag == 0) return(NULL)
75
+
76
  all_data <- get_data()
77
  max_data_date <- max(all_data$report_date, na.rm = TRUE)
78
  cutoff_date <- max_data_date %m-% months(lag)
 
81
  bid_months <- df %>% select(primary_name, report_date, amt_bid, qty_bid) %>% distinct() %>% filter(report_date <= cutoff_date)
82
  if (nrow(bid_months) == 0) return(NULL)
83
 
84
+ result <- bid_months %>%
85
+ rowwise() %>%
86
+ mutate(
87
+ 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),
88
+ 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)
89
+ ) %>% ungroup()
90
+
91
  result
92
  })
93
 
94
+ # ── MAIN DROPDOWN UPDATERS ────────────────────────────────────────────────
95
  observe({
96
  df <- get_data()
97
  if (nrow(df) == 0) return()
98
+
99
+ # Update Main Sidebar Estimators
100
  est_list <- sort(unique(df$primary_name))
101
  updatePickerInput(session, "estimatorSelect", choices = est_list, selected = isolate(input$estimatorSelect))
102
+
103
+ # Update ITS Sidebar Estimators (Only those with 18+ months history)
104
+ eligible <- df %>% group_by(primary_name) %>% summarise(n = n(), .groups = "drop") %>% filter(n >= 18) %>% pull(primary_name) %>% sort()
105
+ updatePickerInput(session, "its_estimator", choices = eligible, selected = if(!is.null(isolate(input$its_estimator))) isolate(input$its_estimator) else eligible[1])
106
+
107
+ yrs <- sort(unique(df$year_num), decreasing = TRUE)
108
+ cur_yr <- isolate(input$quarter_year_select)
109
  updateSelectInput(session, "quarter_year_select", choices = yrs, selected = if (!is.null(cur_yr) && cur_yr %in% yrs) cur_yr else yrs[1])
110
+
111
  max_dt <- max(df$report_date, na.rm = TRUE)
112
  updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)
113
  updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))
114
  })
115
 
116
  observeEvent(input$reset_filters, {
117
+ df <- get_data()
118
+ if (nrow(df) == 0) return()
119
  max_dt <- max(df$report_date, na.rm = TRUE)
120
  updateDateRangeInput(session, "dateRange", start = max_dt %m-% months(24), end = max_dt)
121
  updateDateRangeInput(session, "baselineRange", start = max_dt %m-% months(60), end = max_dt %m-% months(25))
 
125
  updateRadioGroupButtons(session, "annual_granularity", selected = "year")
126
  updateRadioGroupButtons(session, "yoy_position", selected = "dodge")
127
  updateRadioGroupButtons(session, "trend_series", selected = "booked")
128
+ updateMaterialSwitch(session, "show_trendline", value = FALSE)
129
+ updateMaterialSwitch(session, "show_trendline_qty", value = FALSE)
130
  updateSliderInput(session, "win_lag", value = 3)
131
  })
132
 
133
  output$date_verification_table <- renderDataTable({
134
+ d <- get_data()
135
+ if (nrow(d) == 0) return(NULL)
136
  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)
137
  }, options = list(pageLength = 10, scrollX = TRUE, dom = "ftp"))
138
 
139
+ output$trend_box_title <- renderText({ paste("Statistical Process Control β€”", input$time_granularity, "View") })
140
 
141
  # ── KPIs ──────────────────────────────────────────────────────────────────
142
  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"))
143
  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"))
144
+
145
  output$kpi_win_rate_amt <- renderValueBox({
146
+ d <- filtered_data()
147
+ r <- sum(d$amt_booked, na.rm = TRUE) / sum(d$amt_bid, na.rm = TRUE)
148
  valueBox(percent(r, 0.1), HTML("Same-Month Win Rate<br><small style='font-size:10px;opacity:0.75;'>Bids & bookings matched to same month</small>"), icon = icon("chart-line"), color = "yellow")
149
  })
150
+
151
  output$kpi_lag_win_rate <- renderValueBox({
152
+ lag <- input$win_lag
153
+ if (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"))
154
+
155
+ lwr <- lag_win_rate()
156
+ 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"))
157
+
158
  r <- sum(lwr$lag_booked_amt, na.rm = TRUE) / sum(lwr$amt_bid, na.rm = TRUE)
159
+ max_dt <- max(get_data()$report_date, na.rm = TRUE)
160
+ cutoff_dt <- max_dt %m-% months(lag)
161
+ excl_label <- paste0("Bids after ", format(cutoff_dt, "%b %Y"), " excluded (incomplete window)")
162
+
163
+ 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")
164
  })
165
 
166
+ # ── CORRELATION INSIGHT ───────────────────────────────────────────────────
167
  output$correlation_insight <- renderUI({
168
  d <- filtered_data()
169
  if (nrow(d) < 10) return(tags$p("Waiting for sufficient data points...", class = "text-muted"))
170
  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"))
171
+
172
  r <- cor(d$qty_bid, d$amt_booked, use = "complete.obs")
173
+ txt <- if (is.na(r)) {
174
+ "<span class='insight-text'>⚠️ Data insufficient for Pearson correlation.</span>"
175
+ } else if (r < 0) {
176
+ paste0("<span class='insight-text'>πŸ”΄ <b>Negative Correlation (r=", round(r,2), "):</b> More bids β†’ lower revenue. Signals Estimator Fatigue β€” bid fewer, higher-probability jobs.</span>")
177
+ } else if (r < 0.3) {
178
+ paste0("<span class='insight-text'>⚠️ <b>Weak Correlation (r=", round(r,2), "):</b> Bid quantity has minimal impact on revenue. Quality > quantity.</span>")
179
+ } else {
180
+ paste0("<span class='insight-text'>🟒 <b>Positive Correlation (r=", round(r,2), "):</b> Higher bid volume is translating to revenue. Pipeline mechanics are healthy.</span>")
181
+ }
182
  HTML(txt)
183
  })
184
 
185
+ # ── SPC CHARTS ───────────────────────────────────────────────────────────
186
  output$trend_dollars <- renderPlotly({
187
+ d <- filtered_data()
188
+ req(input$time_granularity, input$view_mode, input$baselineRange)
189
+ validate(need(nrow(d) > 0, "No data."))
190
+
191
+ is_q <- input$time_granularity == "Quarterly"
192
+ by_person <- input$view_mode == "Individual"
193
+ show_both <- isTRUE(input$trend_series == "both")
194
+
195
+ if (by_person) {
196
+ n <- length(unique(d$primary_name))
197
+ validate(need(n <= 4, paste0("⚠️ Select 4 or fewer estimators. Currently: ", n)))
198
+ }
199
 
 
200
  ctrl <- spc_limits(d, "amt_booked", is_q, by_person, input$baselineRange[1], input$baselineRange[2])
201
 
202
  if (show_both) {
203
  grp_date <- function(dt) if (is_q) floor_date(dt, "quarter") else floor_date(dt, "month")
204
+ if (by_person) {
205
+ bid_trend <- d %>% mutate(date_group = grp_date(report_date)) %>% group_by(date_group, primary_name) %>% summarise(Bid = sum(amt_bid, na.rm = TRUE), .groups = "drop")
206
+ ctrl <- ctrl %>% left_join(bid_trend, by = c("date_group", "primary_name"))
207
+ } else {
208
+ bid_trend <- d %>% mutate(date_group = grp_date(report_date)) %>% group_by(date_group) %>% summarise(Bid = sum(amt_bid, na.rm = TRUE), .groups = "drop")
209
+ ctrl <- ctrl %>% left_join(bid_trend, by = "date_group")
210
+ }
211
  }
212
 
213
  if (by_person) {
214
+ show_trend <- isTRUE(input$show_trendline)
215
+ p <- ggplot(ctrl, aes(x = date_group, y = Val, group = primary_name,
216
+ text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", primary_name, "<br>Booked: ", dollar(round(Val), 1), "<br>Baseline Mean: ", dollar(round(BL_Mean), 1)))) +
217
+ geom_line(aes(color = primary_name), linewidth = 0.9) +
218
+ geom_point(aes(shape = Anomaly), size = 2) +
219
  { if (show_both) geom_line(aes(y = Bid, group = primary_name), linetype = "dotted", color = "#95a5a6", linewidth = 0.8) } +
220
+ { if (show_trend) geom_smooth(aes(group = primary_name, color = primary_name), method = "lm", se = TRUE, linewidth = 0.7, linetype = "solid", alpha = 0.12) } +
221
+ geom_hline(aes(yintercept = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) +
222
+ geom_hline(aes(yintercept = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
223
+ geom_hline(aes(yintercept = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
224
+ scale_shape_manual(values = c("Normal" = 16, "Anomaly" = 8)) +
225
+ scale_y_continuous(labels = dollar_format(accuracy = 1)) +
226
+ facet_wrap(~primary_name, ncol = 2, scales = "free_y") +
227
+ theme_minimal() + labs(x = "", y = "") +
228
+ theme(legend.position = "none", strip.background = element_rect(fill = "#f4f6f9"), strip.text = element_text(face = "bold"))
229
  } else {
230
+ p <- ggplot(ctrl, aes(x = date_group, y = Val, group = 1,
231
+ text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", "Booked: ", dollar(round(Val), 1), "<br>Baseline Mean: ", dollar(round(BL_Mean), 1), if (show_both) paste0("<br>Bid: ", dollar(round(Bid), 1)) else ""))) +
232
+ geom_line(color = "#2c3e50", linewidth = 0.9) +
233
+ geom_point(aes(color = Anomaly), size = 2) +
234
  { if (show_both) geom_line(aes(y = Bid, group = 1), color = "#95a5a6", linetype = "dotted", linewidth = 1) } +
235
+ geom_line(aes(y = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) +
236
+ geom_line(aes(y = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
237
+ geom_line(aes(y = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
238
+ scale_color_manual(values = c("Normal" = "#2c3e50", "Anomaly" = "#e74c3c")) +
239
+ scale_y_continuous(labels = dollar_format(accuracy = 1)) +
240
+ theme_minimal() + labs(x = "", y = "") + theme(legend.position = "none")
241
  }
242
  ggplotly(p, tooltip = "text")
243
  })
244
 
245
  output$trend_qty <- renderPlotly({
246
+ d <- filtered_data()
247
+ req(input$time_granularity, input$view_mode, input$baselineRange)
248
+ validate(need(nrow(d) > 0, "No data."))
249
+ is_q <- input$time_granularity == "Quarterly"
250
+ by_person <- input$view_mode == "Individual"
251
+
252
+ if (by_person) {
253
+ n <- length(unique(d$primary_name))
254
+ validate(need(n <= 4, paste0("⚠️ Select 4 or fewer estimators. Currently: ", n)))
255
+ }
256
 
257
  ctrl <- spc_limits(d, "qty_booked", is_q, by_person, input$baselineRange[1], input$baselineRange[2])
258
 
259
  if (by_person) {
260
+ show_trend_qty <- isTRUE(input$show_trendline_qty)
261
+ p <- ggplot(ctrl, aes(x = date_group, y = Val, group = primary_name,
262
+ text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", primary_name, "<br>Jobs: ", comma(Val, 1), "<br>Baseline Mean: ", comma(BL_Mean, 1)))) +
263
+ geom_line(color = "#27ae60", linewidth = 0.9) +
264
+ geom_point(aes(color = Anomaly), size = 2) +
265
+ { if (show_trend_qty) geom_smooth(aes(group = primary_name), method = "lm", se = TRUE, color = "#27ae60", fill = "#27ae60", linewidth = 0.7, alpha = 0.12) } +
266
+ geom_hline(aes(yintercept = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) +
267
+ geom_hline(aes(yintercept = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
268
+ geom_hline(aes(yintercept = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
269
+ scale_color_manual(values = c("Normal" = "#27ae60", "Anomaly" = "#e74c3c")) +
270
+ scale_y_continuous(labels = comma_format(accuracy = 1)) +
271
+ facet_wrap(~primary_name, ncol = 2, scales = "free_y") +
272
+ theme_minimal() + labs(x = "", y = "") +
273
+ theme(legend.position = "none", strip.background = element_rect(fill = "#f4f6f9"), strip.text = element_text(face = "bold"))
274
  } else {
275
+ p <- ggplot(ctrl, aes(x = date_group, y = Val, group = 1,
276
+ text = paste0("<b>", format(date_group, "%b %Y"), "</b><br>", "Jobs Booked: ", comma(Val, 1), "<br>Baseline Mean: ", comma(BL_Mean, 1)))) +
277
+ geom_line(color = "#27ae60", linewidth = 0.9) +
278
+ geom_point(aes(color = Anomaly), size = 2) +
279
+ geom_line(aes(y = BL_Mean), color = "#2980b9", linetype = "solid", alpha = 0.5) +
280
+ geom_line(aes(y = UCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
281
+ geom_line(aes(y = LCL), color = "#c0392b", linetype = "dashed", alpha = 0.5) +
282
+ scale_color_manual(values = c("Normal" = "#27ae60", "Anomaly" = "#e74c3c")) +
283
+ scale_y_continuous(labels = comma_format(accuracy = 1)) +
284
+ theme_minimal() + labs(x = "", y = "") + theme(legend.position = "none")
285
  }
286
  ggplotly(p, tooltip = "text")
287
  })
288
 
289
+ # ── INTERVENTION ANALYSIS (ITS) ENGINE ────────────────────────────────────
290
+
291
+ its_series <- reactive({
292
+ df <- get_data()
293
+ req(nrow(df) > 0, input$its_estimator, input$its_metric)
294
+ metric <- input$its_metric
295
+
296
+ series <- df %>%
297
+ filter(primary_name == input$its_estimator) %>%
298
+ arrange(report_date) %>%
299
+ mutate(date_group = floor_date(report_date, "month")) %>%
300
+ group_by(date_group) %>%
301
+ summarise(amt_bid = sum(amt_bid, na.rm = TRUE), amt_booked = sum(amt_booked, na.rm = TRUE),
302
+ qty_booked = sum(qty_booked, na.rm = TRUE), qty_bid = sum(qty_bid, na.rm = TRUE), .groups = "drop") %>%
303
+ mutate(
304
+ win_rate = ifelse(amt_bid > 0, amt_booked / amt_bid, NA_real_),
305
+ value = .data[[metric]],
306
+ t = row_number()
307
+ ) %>% filter(!is.na(value))
308
+
309
+ series
310
+ })
311
+
312
+ its_result <- reactiveVal(NULL)
313
+ its_selected_bp <- reactiveVal(NULL)
314
+
315
+ observeEvent(input$its_breakpoints_table_rows_selected, {
316
+ bps <- its_result()$breakpoints
317
+ idx <- input$its_breakpoints_table_rows_selected
318
+ if (!is.null(bps) && !is.null(idx) && idx <= nrow(bps)) {
319
+ sel_date <- bps$Date[idx]
320
+ updateDateInput(session, "its_manual_date", value = sel_date)
321
+ its_selected_bp(sel_date)
322
+ }
323
+ })
324
+
325
+ observeEvent(input$its_run, {
326
+ series <- its_series()
327
+ validate_msg <- NULL
328
+ if (nrow(series) < 18) validate_msg <- "Need at least 18 monthly observations."
329
+ if (!is.null(validate_msg)) { its_result(list(error = validate_msg)); return() }
330
+
331
+ metric <- input$its_metric
332
+ manual_dt <- input$its_manual_date
333
+ autodetect <- isTRUE(input$its_autodetect)
334
+
335
+ bp_table <- NULL
336
+ bp_dates <- c()
337
+
338
+ if (autodetect) {
339
+ tryCatch({
340
+ bp_fit <- breakpoints(value ~ t, data = series, h = 6)
341
+ bp_idx <- bp_fit$breakpoints
342
+ if (!any(is.na(bp_idx)) && length(bp_idx) > 0) {
343
+ bp_dates <- series$date_group[bp_idx]
344
+ fs <- Fstats(value ~ t, data = series)
345
+ bp_table <- tibble(
346
+ Date = bp_dates, `Time Index` = bp_idx, `F-Statistic` = round(fs$Fstats[bp_idx], 2),
347
+ `Months Before` = bp_idx, `Months After` = nrow(series) - bp_idx
348
+ )
349
+ }
350
+ }, error = function(e) NULL)
351
+ }
352
+
353
+ active_date <- NULL
354
+ if (!is.null(manual_dt) && !is.na(manual_dt) && manual_dt >= min(series$date_group) && manual_dt <= max(series$date_group)) {
355
+ active_date <- floor_date(as.Date(manual_dt), "month")
356
+ } else if (length(bp_dates) > 0) {
357
+ active_date <- bp_dates[1]
358
+ } else {
359
+ active_date <- series$date_group[round(nrow(series) / 2)]
360
+ }
361
+
362
+ t0 <- which(series$date_group == active_date)
363
+ if (length(t0) == 0) t0 <- which.min(abs(series$date_group - active_date))
364
+
365
+ model_df <- series %>% mutate(D = as.integer(t >= t0), t_post = (t - t0) * D)
366
+
367
+ fit <- tryCatch(lm(value ~ t + D + t_post, data = model_df), error = function(e) NULL)
368
+ if (is.null(fit)) { its_result(list(error = "Model could not be fitted. Try a different date.")); return() }
369
+
370
+ cf <- coeftest(fit)
371
+ cf_df <- as.data.frame(cf) %>% tibble::rownames_to_column("Term") %>%
372
+ mutate(Term = recode(Term, `(Intercept)` = "Intercept (baseline level)", `t` = "Pre-intervention trend", `D` = "Level change", `t_post` = "Slope change"),
373
+ Estimate = round(Estimate, 2), `Std Error` = round(`Std. Error`, 2), `t value` = round(`t value`, 3),
374
+ `p value` = ifelse(`Pr(>|t|)` < 0.001, "< 0.001", as.character(round(`Pr(>|t|)`, 3))),
375
+ Significant = ifelse(`Pr(>|t|)` < 0.05, "Yes *", "No")) %>%
376
+ select(Term, Estimate, `Std Error`, `t value`, `p value`, Significant)
377
+
378
+ model_df <- model_df %>% mutate(fitted = fitted(fit), resid = residuals(fit), counterfact = coef(fit)[1] + coef(fit)[2] * t)
379
+ pre <- model_df %>% filter(t <= t0)
380
+ post <- model_df %>% filter(t >= t0)
381
+
382
+ b2 <- coef(fit)["D"]; b3 <- coef(fit)["t_post"]; p2 <- cf[3, 4]; p3 <- cf[4, 4]
383
+
384
+ level_txt <- if (p2 < 0.05) {
385
+ dir <- if (b2 > 0) "increased" else "decreased"
386
+ 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), ").")
387
+ } else { paste0("No significant immediate level change detected (p = ", round(p2, 3), ").") }
388
+
389
+ slope_txt <- if (p3 < 0.05) {
390
+ dir <- if (b3 > 0) "accelerated" else "decelerated"
391
+ 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), ").")
392
+ } else { paste0("No significant change in monthly trajectory detected (p = ", round(p3, 3), ").") }
393
+
394
+ overall <- if (p2 < 0.05 || p3 < 0.05) "Significant intervention effect detected." else "No statistically significant intervention effect detected."
395
+
396
+ 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))
397
+ })
398
+
399
+ output$its_summary_ui <- renderUI({
400
+ res <- its_result()
401
+ if (is.null(res)) return(tags$p("Configure settings and click 'Run Analysis'.", class = "text-muted"))
402
+ if (!is.null(res$error)) return(tags$p(res$error, style = "color:#c0392b;"))
403
+
404
+ metric_label <- c(amt_booked = "Booked Revenue ($)", amt_bid = "Bid Volume ($)", qty_booked = "Jobs Booked", win_rate = "Win Rate")
405
+
406
+ tagList(
407
+ tags$table(style = "width:100%; border-collapse:collapse; font-size:13px;",
408
+ 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)),
409
+ 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])),
410
+ 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;"))),
411
+ 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))
412
+ ),
413
+ tags$hr(style = "margin:12px 0;"),
414
+ tags$p(style = "font-size:13px; color:#2c3e50; font-weight:600;", res$overall),
415
+ tags$p(style = "font-size:12px; color:#5A6A72; margin:4px 0;", tags$b("Level change: "), res$level_txt),
416
+ tags$p(style = "font-size:12px; color:#5A6A72; margin:4px 0;", tags$b("Slope change: "), res$slope_txt)
417
+ )
418
+ })
419
+
420
+ output$its_chart <- renderPlotly({
421
+ res <- its_result()
422
+ if (is.null(res) || !is.null(res$error)) return(plotly_empty())
423
+
424
+ series <- res$series; pre <- res$pre; post <- res$post; metric <- res$metric
425
+ fmt <- 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))
426
+ y_label <- c(amt_booked="Booked Revenue ($)", amt_bid="Bid Volume ($)", qty_booked="Jobs Booked", win_rate="Win Rate")[metric]
427
+
428
+ p <- ggplot(series, aes(x = date_group)) +
429
+ 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) +
430
+ geom_line(aes(y = counterfact), color = "#c0392b", linetype = "dotted", linewidth = 0.7, alpha = 0.6) +
431
+ geom_line(data = pre, aes(y = fitted), color = "#2980b9", linewidth = 1.1) +
432
+ geom_line(data = post, aes(y = fitted), color = "#27ae60", linewidth = 1.1) +
433
+ geom_vline(xintercept = as.numeric(res$active_date), color = "#e67e22", linetype = "dashed", linewidth = 0.9) +
434
+ 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") +
435
+ 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)) +
436
+ 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") +
437
+ theme_minimal() + theme(plot.caption = element_text(size = 8, color = "#95a5a6"), plot.title = element_text(size = 12, face = "bold", color = "#2c3e50"))
438
+
439
+ ggplotly(p, tooltip = "text") %>% layout(legend = list(orientation = "h"))
440
+ })
441
+
442
+ output$its_breakpoints_table <- renderDataTable({
443
+ res <- its_result(); if (is.null(res) || !is.null(res$error)) return(NULL)
444
+ if (is.null(res$breakpoints) || nrow(res$breakpoints) == 0) return(data.frame(Message = "No significant breakpoints detected automatically."))
445
+ res$breakpoints %>% mutate(Date = format(Date, "%B %Y")) %>% arrange(desc(`F-Statistic`))
446
+ }, selection = "single", options = list(dom = "t", pageLength = 10, scrollX = TRUE))
447
+
448
+ output$its_coef_table <- renderDataTable({
449
+ res <- its_result(); if (is.null(res) || !is.null(res$error)) return(NULL); res$coef_df
450
+ }, options = list(dom = "t", pageLength = 10, scrollX = TRUE))
451
+
452
+ # ── ADVANCED ANALYTICS (FUNNEL & HEATMAP) ─────────────────────────────────
453
  output$bid_funnel_chart <- renderPlotly({
454
  d <- filtered_data(); validate(need(nrow(d) > 0, "No data."))
455
  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_))
 
457
  ggplotly(p, tooltip = "text")
458
  })
459
 
 
460
  output$seasonality_heatmap <- renderPlotly({
461
+ df <- get_data(); sel <- input$estimatorSelect
462
  if (!is.null(sel) && length(sel) > 0) df <- df %>% filter(primary_name %in% sel)
463
  validate(need(nrow(df) > 0, "No data."))
464
+ hm_metric <- if(!is.null(input$heatmap_metric)) input$heatmap_metric else "amt_booked"
465
+ metric_sym <- sym(hm_metric); metric_label <- if(hm_metric == "amt_booked") "Booked ($)" else "Bid ($)"
 
 
466
  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)))
467
+ 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")
468
  ggplotly(p, tooltip = "text")
469
  })
470
 
471
+ # ── K-MEANS ───────────────────────────────────────────────────────────────
472
  output$scatter_matrix <- renderPlotly({
473
  dat <- filtered_data(); validate(need(nrow(dat) > 0, "Upload data to begin.")); lwr <- lag_win_rate()
474
  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)
 
480
  ggplotly(p, tooltip = "text")
481
  })
482
 
483
+ # ── ANNUAL, YOY, QUARTERLY ────────────────────────────────────────────────
484
  output$annual_bar_chart <- renderPlotly({
485
  d <- filtered_data(); validate(need(nrow(d) > 0, "No data.")); gran <- input$annual_granularity; by_person <- !is.null(input$estimatorSelect) && length(input$estimatorSelect) <= 5
486
  d <- 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))
 
500
  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")
501
  })
502
 
503
+ # ── LEADERBOARD & EXPORT ──────────────────────────────────────────────────
504
  output$leaderboard_table <- renderDataTable({
505
  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)
506
  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") } }
 
513
  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))
514
 
515
  output$download_report <- downloadHandler(
516
+ filename = function() { paste0("Estimator_Intelligence_", format(Sys.Date(), "%Y-%m-%d"), ".xlsx") },
517
  content = function(file) {
518
+ d <- filtered_data(); req(nrow(d) > 0)
519
+ withProgress(message = "Building Excel report…", value = 0.2, {
520
+ 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%")
521
+ 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)
522
+ sel_label <- if (is.null(isolate(input$estimatorSelect))||length(isolate(input$estimatorSelect))==0)"All Estimators" else paste(isolate(input$estimatorSelect),collapse=", ")
523
+ 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)
524
+ writeData(wb,"Summary",meta,startRow=3,startCol=1,colNames=F)
525
+ 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)
526
+ writeData(wb,"Summary",kpi_data,startRow=9,startCol=1,colNames=T);addStyle(wb,"Summary",header_style,rows=9,cols=1:2)
527
+ 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)
528
+ setProgress(0.6)
529
+ 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)
530
+ setProgress(0.9); saveWorkbook(wb,file,overwrite=T)
531
+ })
532
  }
533
  )
534
  }
setup_database.sql CHANGED
@@ -7,7 +7,7 @@ sys_con <- dbConnect(RPostgres::Postgres(),
7
  dbname = "postgres", # Default system DB
8
  host = "localhost",
9
  user = "postgres",
10
- password = "your_password_here") # <--- UPDATE THIS
11
 
12
 
13
  tryCatch({
 
7
  dbname = "postgres", # Default system DB
8
  host = "localhost",
9
  user = "postgres",
10
+ password = "your_password_here") #
11
 
12
 
13
  tryCatch({
ui.R CHANGED
@@ -3,37 +3,66 @@ dashboardPage(
3
  title = "Estimator Intelligence",
4
  skin = "black",
5
 
6
- dashboardHeader(title = span("Estimator Intelligence", style = "font-weight:bold;font-size:18px;")),
 
7
 
8
  dashboardSidebar(
9
  width = 260,
10
  sidebarMenu(
11
  menuItem("Executive Dashboard", tabName = "dashboard", icon = icon("chart-area")),
 
12
  menuItem("Data Management", tabName = "admin", icon = icon("database")),
13
  hr(),
14
 
15
  div(style = "padding:10px;",
16
- h5("Filter Controls", style = "color:#b8c7ce;text-transform:uppercase;font-size:12px;margin-bottom:10px;"),
 
17
 
18
- dateRangeInput("dateRange", "View Range", start = Sys.Date() %m-% months(24), end = Sys.Date(), separator = " to "),
19
- dateRangeInput("baselineRange", "SPC Baseline Period", start = Sys.Date() %m-% months(48), end = Sys.Date() %m-% months(25), separator = " to "),
 
 
20
 
21
- radioGroupButtons("view_mode", "Breakdown Mode", choices = c("Aggregate", "Individual"), selected = "Aggregate", status = "success", size = "sm", justified = TRUE),
22
- materialSwitch(inputId = "show_trend", label = "Show Individual Trend Lines", status = "primary", right = TRUE),
 
 
 
 
 
 
 
23
  br(),
24
 
25
- radioGroupButtons("time_granularity", "Time Scale", choices = c("Monthly", "Quarterly"), selected = "Monthly", status = "primary", size = "sm", justified = TRUE),
 
 
 
26
  br(),
27
 
28
- sliderInput("win_lag", "Win Rate Lag (months)", min = 0, max = 6, value = 3, step = 1, ticks = FALSE),
29
- p(style = "font-size:10px;color:#b8c7ce;margin-top:-8px;", "Match bids to bookings N months later."),
 
 
 
30
 
31
- pickerInput("estimatorSelect", "Estimators:", choices = NULL, multiple = TRUE,
32
- options = list(`actions-box` = TRUE, `live-search` = TRUE, `selected-text-format` = "count > 2", `count-selected-text` = "{0} Selected", `none-selected-text` = "All Estimators (Default)")),
 
 
 
 
 
 
 
33
 
34
  div(style = "margin-top:12px;display:flex;gap:6px;",
35
- actionButton("refresh", "Refresh", icon = icon("sync"), style = "flex:1;font-size:12px;", class = "btn-primary btn-sm btn-flat"),
36
- actionButton("reset_filters", "Reset", icon = icon("undo"), style = "flex:1;font-size:12px;", class = "btn-warning btn-sm btn-flat")
 
 
 
 
37
  )
38
  )
39
  )
@@ -50,66 +79,230 @@ dashboardPage(
50
  "))),
51
 
52
  tabItems(
 
 
53
  tabItem(tabName = "dashboard",
 
 
 
 
 
 
 
 
 
 
54
  fluidRow(
55
- valueBoxOutput("kpi_total_bid", width = 3), valueBoxOutput("kpi_total_booked", width = 3),
56
- valueBoxOutput("kpi_win_rate_amt", width = 3), valueBoxOutput("kpi_lag_win_rate", width = 3)
 
57
  ),
58
- fluidRow(box(title = "Data Science Insight: Pipeline Correlation", status = "info", solidHeader = TRUE, width = 12, uiOutput("correlation_insight"))),
 
59
  fluidRow(
60
- tabBox(title = textOutput("trend_box_title"), width = 12, side = "right", selected = "Control Chart: Revenue ($)",
 
 
61
  tabPanel("Control Chart: Revenue ($)",
62
- fluidRow(column(12, radioGroupButtons("trend_series", NULL, choices = c("Booked Only" = "booked", "Bid vs. Booked" = "both"), selected = "booked", status = "default", size = "xs"))),
63
- plotlyOutput("trend_dollars", height = "380px"),
64
- p(class = "text-muted", style = "font-size:11px;", "SPC: Blue line = Baseline Mean. Red dashed = UCL/LCL. Red dots = anomalies.")),
65
- tabPanel("Control Chart: Quantity", plotlyOutput("trend_qty", height = "400px"))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
66
  )
67
  ),
 
 
68
  fluidRow(
69
- box(title = "Annual Performance", status = "primary", solidHeader = TRUE, width = 6,
70
- fluidRow(column(12, radioGroupButtons("annual_granularity", NULL, choices = c("By Year" = "year", "By Quarter" = "quarter", "By Month" = "month"), selected = "year", status = "default", size = "xs", justified = TRUE))),
 
 
 
 
 
 
 
 
71
  plotlyOutput("annual_bar_chart", height = "370px")),
72
- tabBox(title = "Growth & Breakdown", width = 6, side = "right", selected = "YoY Growth (%)",
 
 
73
  tabPanel("YoY Growth (%)",
74
  fluidRow(
75
- column(4, p(class="text-muted", style="font-size:11px;margin-top:10px;", "Aggregate: Red/Green | Individual: Colored by Person")),
76
- 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"))),
77
- column(4, radioGroupButtons("yoy_position", NULL, choices = c("Grouped"="dodge", "Stacked"="stack"), selected = "dodge", status = "default", size = "xs", justified = TRUE))
 
 
 
 
 
 
 
 
 
 
78
  ),
79
  plotlyOutput("yoy_chart", height = "330px")),
80
  tabPanel("Quarterly Deep Dive",
81
- fluidRow(column(7, p(class="text-muted", style="font-size:11px;margin-top:10px;", "Revenue Breakdown by Quarter.")), column(5, selectInput("quarter_year_select", NULL, choices = NULL, width = "100%"))),
 
 
 
 
 
82
  plotlyOutput("quarterly_breakdown_chart", height = "350px"))
83
  )
84
  ),
 
 
85
  fluidRow(
86
- tabBox(title = "Advanced Analytics", width = 12, side = "right", selected = "Bid Funnel",
87
- tabPanel("Bid Funnel", plotlyOutput("bid_funnel_chart", height = "420px")),
 
 
 
 
88
  tabPanel("Seasonality Heatmap",
89
- # CEO TWEAK: Added the Bid vs Booked toggle for the Heatmap
90
- fluidRow(column(12, radioGroupButtons("heatmap_metric", NULL, choices = c("Booked Revenue" = "amt_booked", "Bid Volume" = "amt_bid"), selected = "amt_booked", status = "default", size = "xs"))),
91
- plotlyOutput("seasonality_heatmap", height = "390px"),
92
- p(class = "text-muted", style = "font-size:11px;", "Reveals consistent seasonal peaks and troughs across the full history."))
93
  )
94
  ),
95
- fluidRow(box(title = "K-Means Behavioral Segmentation", status = "primary", solidHeader = TRUE, width = 12, plotlyOutput("scatter_matrix", height = "400px"))),
96
- fluidRow(box(title = "Estimator Leaderboard", status = "warning", solidHeader = TRUE, width = 12, dataTableOutput("leaderboard_table")))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  ),
98
 
 
99
  tabItem(tabName = "admin",
100
  fluidRow(
101
  box(title = "Upload Data", status = "danger", solidHeader = TRUE, width = 5,
102
  fileInput("file1", "Upload CSV", accept = ".csv"),
103
- actionButton("process_upload", "Process & Import", class = "btn-danger", width = "100%")),
 
104
  box(title = "System Status", status = "info", solidHeader = TRUE, width = 4,
105
- verbatimTextOutput("db_status_text"), dataTableOutput("preview_table")),
 
106
  box(title = "Export Report", status = "primary", solidHeader = TRUE, width = 3,
107
- p(class = "text-muted", "Download a dynamic HTML Executive Summary. (Open in browser and Save as PDF)."),
108
- downloadButton("download_report", "Download HTML Report", style = "width:100%;font-weight:600;"))
 
 
 
109
  ),
110
  fluidRow(
111
- box(title = "Date Verification β€” Raw vs. Parsed", status = "warning", solidHeader = TRUE, width = 12,
112
- p(class = "text-muted", style = "font-size:12px;", "Confirms MoYear values are parsed correctly. Format: YY-MM (e.g. '19-06' β†’ June 2019)."),
 
 
113
  dataTableOutput("date_verification_table"))
114
  )
115
  )
 
3
  title = "Estimator Intelligence",
4
  skin = "black",
5
 
6
+ dashboardHeader(title = span("Estimator Intelligence",
7
+ style = "font-weight:bold;font-size:18px;")),
8
 
9
  dashboardSidebar(
10
  width = 260,
11
  sidebarMenu(
12
  menuItem("Executive Dashboard", tabName = "dashboard", icon = icon("chart-area")),
13
+ menuItem("Intervention Analysis", tabName = "its", icon = icon("flask")),
14
  menuItem("Data Management", tabName = "admin", icon = icon("database")),
15
  hr(),
16
 
17
  div(style = "padding:10px;",
18
+ h5("Filter Controls",
19
+ style = "color:#b8c7ce;text-transform:uppercase;font-size:12px;margin-bottom:10px;"),
20
 
21
+ dateRangeInput("dateRange", "View Range",
22
+ start = Sys.Date() %m-% months(24),
23
+ end = Sys.Date(),
24
+ separator = " to "),
25
 
26
+ dateRangeInput("baselineRange", "SPC Baseline Period",
27
+ start = Sys.Date() %m-% months(48),
28
+ end = Sys.Date() %m-% months(25),
29
+ separator = " to "),
30
+
31
+ radioGroupButtons("view_mode", "Breakdown Mode",
32
+ choices = c("Aggregate", "Individual"),
33
+ selected = "Aggregate",
34
+ status = "success", size = "sm", justified = TRUE),
35
  br(),
36
 
37
+ radioGroupButtons("time_granularity", "Time Scale",
38
+ choices = c("Monthly", "Quarterly"),
39
+ selected = "Monthly",
40
+ status = "primary", size = "sm", justified = TRUE),
41
  br(),
42
 
43
+ sliderInput("win_lag", "Win Rate Lag (months)",
44
+ min = 0, max = 6, value = 3, step = 1,
45
+ ticks = FALSE),
46
+ p(style = "font-size:10px;color:#b8c7ce;margin-top:-8px;",
47
+ "Match bids to bookings N months later. 0 = same-month (old behavior)."),
48
 
49
+ pickerInput("estimatorSelect", "Estimators:",
50
+ choices = NULL, multiple = TRUE,
51
+ options = list(
52
+ `actions-box` = TRUE,
53
+ `live-search` = TRUE,
54
+ `selected-text-format` = "count > 2",
55
+ `count-selected-text` = "{0} Selected",
56
+ `none-selected-text` = "All Estimators (Default)"
57
+ )),
58
 
59
  div(style = "margin-top:12px;display:flex;gap:6px;",
60
+ actionButton("refresh", "Refresh",
61
+ icon = icon("sync"), style = "flex:1;font-size:12px;",
62
+ class = "btn-primary btn-sm btn-flat"),
63
+ actionButton("reset_filters", "Reset",
64
+ icon = icon("undo"), style = "flex:1;font-size:12px;",
65
+ class = "btn-warning btn-sm btn-flat")
66
  )
67
  )
68
  )
 
79
  "))),
80
 
81
  tabItems(
82
+
83
+ # ── EXECUTIVE DASHBOARD ──────────────────────────────────────────────
84
  tabItem(tabName = "dashboard",
85
+
86
+ # ROW 1: KPIs
87
+ fluidRow(
88
+ valueBoxOutput("kpi_total_bid", width = 3),
89
+ valueBoxOutput("kpi_total_booked", width = 3),
90
+ valueBoxOutput("kpi_win_rate_amt", width = 3),
91
+ valueBoxOutput("kpi_lag_win_rate", width = 3)
92
+ ),
93
+
94
+ # ROW 2: CORRELATION INSIGHT
95
  fluidRow(
96
+ box(title = "Data Science Insight: Pipeline Correlation",
97
+ status = "info", solidHeader = TRUE, width = 12,
98
+ uiOutput("correlation_insight"))
99
  ),
100
+
101
+ # ROW 3: SPC CHARTS
102
  fluidRow(
103
+ tabBox(title = textOutput("trend_box_title"),
104
+ width = 12, side = "right",
105
+ selected = "Control Chart: Revenue ($)",
106
  tabPanel("Control Chart: Revenue ($)",
107
+ fluidRow(
108
+ column(6,
109
+ radioGroupButtons("trend_series", NULL,
110
+ choices = c("Booked Only" = "booked", "Bid vs. Booked" = "both"),
111
+ selected = "booked",
112
+ status = "default", size = "xs")
113
+ ),
114
+ column(6,
115
+ materialSwitch("show_trendline",
116
+ label = "Trend Lines (Individual)",
117
+ value = FALSE,
118
+ status = "primary",
119
+ right = TRUE)
120
+ )
121
+ ),
122
+ plotlyOutput("trend_dollars", height = "370px"),
123
+ p(class = "text-muted", style = "font-size:11px;",
124
+ "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).")),
125
+ tabPanel("Control Chart: Quantity",
126
+ div(style = "padding:6px 0 0 4px;",
127
+ materialSwitch("show_trendline_qty",
128
+ label = "Trend Lines (Individual)",
129
+ value = FALSE,
130
+ status = "primary",
131
+ right = TRUE)
132
+ ),
133
+ plotlyOutput("trend_qty", height = "385px"),
134
+ p(class = "text-muted", style = "font-size:11px;",
135
+ "Anomalies in jobs booked vs. the fixed Baseline Period mean. Trend line shows trajectory per estimator (Individual mode only.)"))
136
  )
137
  ),
138
+
139
+ # ROW 4: ANNUAL & YOY
140
  fluidRow(
141
+ box(title = "Annual Performance",
142
+ status = "primary", solidHeader = TRUE, width = 6,
143
+ fluidRow(
144
+ column(12,
145
+ radioGroupButtons("annual_granularity", NULL,
146
+ choices = c("By Year" = "year", "By Quarter" = "quarter", "By Month" = "month"),
147
+ selected = "year",
148
+ status = "default", size = "xs", justified = TRUE)
149
+ )
150
+ ),
151
  plotlyOutput("annual_bar_chart", height = "370px")),
152
+
153
+ tabBox(title = "Growth & Breakdown", width = 6, side = "right",
154
+ selected = "YoY Growth (%)",
155
  tabPanel("YoY Growth (%)",
156
  fluidRow(
157
+ column(4, p(class="text-muted", style="font-size:11px;margin-top:10px;",
158
+ "Aggregate: Red/Green | Individual: Colored by Person")),
159
+ column(4, pickerInput("yoy_metric", NULL,
160
+ choices = c("Booked Revenue ($)" = "amt_booked",
161
+ "Bid Volume ($)" = "amt_bid",
162
+ "Jobs Booked (Qty)" = "qty_booked",
163
+ "Jobs Bid (Qty)" = "qty_bid"),
164
+ selected = "amt_booked", width = "100%",
165
+ options = list(style = "btn-default btn-sm"))),
166
+ column(4, radioGroupButtons("yoy_position", NULL,
167
+ choices = c("Grouped" = "dodge", "Stacked" = "stack"),
168
+ selected = "dodge",
169
+ status = "default", size = "xs", justified = TRUE))
170
  ),
171
  plotlyOutput("yoy_chart", height = "330px")),
172
  tabPanel("Quarterly Deep Dive",
173
+ fluidRow(
174
+ column(7, p(class="text-muted", style="font-size:11px;margin-top:10px;",
175
+ "Revenue Breakdown by Quarter for Selected Year.")),
176
+ column(5, selectInput("quarter_year_select", NULL,
177
+ choices = NULL, width = "100%"))
178
+ ),
179
  plotlyOutput("quarterly_breakdown_chart", height = "350px"))
180
  )
181
  ),
182
+
183
+ # ROW 5: NEW ANALYTICS TABS
184
  fluidRow(
185
+ tabBox(title = "Advanced Analytics", width = 12, side = "right",
186
+ selected = "Bid Funnel",
187
+ tabPanel("Bid Funnel",
188
+ plotlyOutput("bid_funnel_chart", height = "420px"),
189
+ p(class = "text-muted", style = "font-size:11px;",
190
+ "Grouped bars show Total Bid $ vs. Total Booked $ per estimator. Win % annotated on each booked bar. Sorted by Total Bid descending.")),
191
  tabPanel("Seasonality Heatmap",
192
+ plotlyOutput("seasonality_heatmap", height = "420px"),
193
+ p(class = "text-muted", style = "font-size:11px;",
194
+ "Booked revenue by calendar month and year. Darker = higher revenue. Reveals consistent seasonal peaks and troughs across the full history."))
 
195
  )
196
  ),
197
+
198
+ # ROW 6: K-MEANS CLUSTERING
199
+ fluidRow(
200
+ box(title = "K-Means Behavioral Segmentation (3-Feature Model)",
201
+ status = "primary", solidHeader = TRUE, width = 12,
202
+ plotlyOutput("scatter_matrix", height = "400px"),
203
+ p(class = "text-muted", style = "font-size:11px;",
204
+ "Clusters on: Pipeline Effort (Total Bid $), Efficiency (Lag-Adjusted Win Rate %), Selectivity (Avg Job Size $). Point size = Total Booked. Hover for details."))
205
+ ),
206
+
207
+ # ROW 7: LEADERBOARD
208
+ fluidRow(
209
+ box(title = "Estimator Leaderboard β€” Click any column to sort",
210
+ status = "warning", solidHeader = TRUE, width = 12,
211
+ dataTableOutput("leaderboard_table"))
212
+ )
213
+ ),
214
+
215
+ # ── INTERVENTION ANALYSIS (ITS) ──────────────────────────────────────
216
+ tabItem(tabName = "its",
217
+ fluidRow(
218
+ box(title = "Intervention Settings", status = "primary",
219
+ solidHeader = TRUE, width = 4,
220
+
221
+ pickerInput("its_estimator", "Estimator",
222
+ choices = NULL, multiple = FALSE,
223
+ options = list(`live-search` = TRUE)),
224
+
225
+ pickerInput("its_metric", "Outcome Metric",
226
+ choices = c(
227
+ "Booked Revenue ($)" = "amt_booked",
228
+ "Bid Volume ($)" = "amt_bid",
229
+ "Jobs Booked (Qty)" = "qty_booked",
230
+ "Win Rate (same-mo.)" = "win_rate"
231
+ ), selected = "amt_booked"),
232
+
233
+ hr(),
234
+ dateInput("its_manual_date", "Option A β€” Specify Intervention Date",
235
+ value = NULL, format = "M yyyy",
236
+ min = "2010-01-01"),
237
+ p(class = "text-muted", style = "font-size:11px;",
238
+ "The date a strategy change, new hire, process shift, or other intervention occurred."),
239
+
240
+ hr(),
241
+ materialSwitch("its_autodetect",
242
+ label = "Option B β€” Auto-Detect Breakpoints",
243
+ value = TRUE,
244
+ status = "primary", right = TRUE),
245
+ p(class = "text-muted", style = "font-size:11px;",
246
+ "Uses the strucchange algorithm to scan for the single most statistically significant structural break in the series."),
247
+
248
+ br(),
249
+ actionButton("its_run", "Run Analysis",
250
+ icon = icon("play"),
251
+ class = "btn-success btn-block",
252
+ width = "100%")
253
+ ),
254
+ box(title = "Intervention Effect β€” Statistical Summary",
255
+ status = "primary", solidHeader = TRUE, width = 8,
256
+ uiOutput("its_summary_ui"),
257
+ p(class = "text-muted", style = "font-size:11px; margin-top:8px;",
258
+ "Segmented regression (OLS) with pre/post intervention terms. Level change = immediate shift at intervention date. Slope change = difference in monthly trajectory before vs. after.")
259
+ )
260
+ ),
261
+ fluidRow(
262
+ box(title = "Interrupted Time Series β€” Visual",
263
+ status = "primary", solidHeader = TRUE, width = 12,
264
+ plotlyOutput("its_chart", height = "440px"),
265
+ p(class = "text-muted", style = "font-size:11px;",
266
+ "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.")
267
+ )
268
+ ),
269
+ fluidRow(
270
+ box(title = "Auto-Detected Structural Breaks",
271
+ status = "warning", solidHeader = TRUE, width = 6,
272
+ dataTableOutput("its_breakpoints_table"),
273
+ p(class = "text-muted", style = "font-size:11px; margin-top:6px;",
274
+ "All significant breakpoints detected by the strucchange algorithm, ranked by F-statistic. Click a row to set it as the active intervention date.")),
275
+
276
+ box(title = "Coefficient Detail",
277
+ status = "info", solidHeader = TRUE, width = 6,
278
+ dataTableOutput("its_coef_table"),
279
+ p(class = "text-muted", style = "font-size:11px; margin-top:6px;",
280
+ "Full regression output. p < 0.05 indicates a statistically significant effect."))
281
+ )
282
  ),
283
 
284
+ # ── DATA MANAGEMENT ─────────────────────────────────────────────────
285
  tabItem(tabName = "admin",
286
  fluidRow(
287
  box(title = "Upload Data", status = "danger", solidHeader = TRUE, width = 5,
288
  fileInput("file1", "Upload CSV", accept = ".csv"),
289
+ actionButton("process_upload", "Process & Import",
290
+ class = "btn-danger", width = "100%")),
291
  box(title = "System Status", status = "info", solidHeader = TRUE, width = 4,
292
+ verbatimTextOutput("db_status_text"),
293
+ dataTableOutput("preview_table")),
294
  box(title = "Export Report", status = "primary", solidHeader = TRUE, width = 3,
295
+ p(class = "text-muted",
296
+ "Download a formatted Excel workbook of the current filtered view."),
297
+ downloadButton("download_report", "Download Excel Report",
298
+ icon = icon("file-excel"),
299
+ style = "width:100%;font-weight:600;"))
300
  ),
301
  fluidRow(
302
+ box(title = "Date Verification β€” Raw vs. Parsed",
303
+ status = "warning", solidHeader = TRUE, width = 12,
304
+ p(class = "text-muted", style = "font-size:12px;",
305
+ "Confirms MoYear values are parsed correctly. Format: YY-MM (e.g. '19-06' β†’ June 2019)."),
306
  dataTableOutput("date_verification_table"))
307
  )
308
  )